control.c 241 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2017, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file control.c
  6. * \brief Implementation for Tor's control-socket interface.
  7. *
  8. * A "controller" is an external program that monitors and controls a Tor
  9. * instance via a text-based protocol. It connects to Tor via a connection
  10. * to a local socket.
  11. *
  12. * The protocol is line-driven. The controller sends commands terminated by a
  13. * CRLF. Tor sends lines that are either <em>replies</em> to what the
  14. * controller has said, or <em>events</em> that Tor sends to the controller
  15. * asynchronously based on occurrences in the Tor network model.
  16. *
  17. * See the control-spec.txt file in the torspec.git repository for full
  18. * details on protocol.
  19. *
  20. * This module generally has two kinds of entry points: those based on having
  21. * received a command on a controller socket, which are handled in
  22. * connection_control_process_inbuf(), and dispatched to individual functions
  23. * with names like control_handle_COMMANDNAME(); and those based on events
  24. * that occur elsewhere in Tor, which are handled by functions with names like
  25. * control_event_EVENTTYPE().
  26. *
  27. * Controller events are not sent immediately; rather, they are inserted into
  28. * the queued_control_events array, and flushed later from
  29. * flush_queued_events_cb(). Doing this simplifies our callgraph greatly,
  30. * by limiting the number of places in Tor that can call back into the network
  31. * stack.
  32. **/
  33. #define CONTROL_PRIVATE
  34. #include "or.h"
  35. #include "addressmap.h"
  36. #include "bridges.h"
  37. #include "buffers.h"
  38. #include "channel.h"
  39. #include "channeltls.h"
  40. #include "circuitbuild.h"
  41. #include "circuitlist.h"
  42. #include "circuitstats.h"
  43. #include "circuituse.h"
  44. #include "command.h"
  45. #include "compat_libevent.h"
  46. #include "config.h"
  47. #include "confparse.h"
  48. #include "connection.h"
  49. #include "connection_edge.h"
  50. #include "connection_or.h"
  51. #include "control.h"
  52. #include "directory.h"
  53. #include "dirserv.h"
  54. #include "dnsserv.h"
  55. #include "entrynodes.h"
  56. #include "geoip.h"
  57. #include "hibernate.h"
  58. #include "hs_common.h"
  59. #include "main.h"
  60. #include "networkstatus.h"
  61. #include "nodelist.h"
  62. #include "policies.h"
  63. #include "reasons.h"
  64. #include "rendclient.h"
  65. #include "rendcommon.h"
  66. #include "rendservice.h"
  67. #include "rephist.h"
  68. #include "router.h"
  69. #include "routerlist.h"
  70. #include "routerparse.h"
  71. #include "shared_random.h"
  72. #ifndef _WIN32
  73. #include <pwd.h>
  74. #include <sys/resource.h>
  75. #endif
  76. #include <event2/event.h>
  77. #include "crypto_s2k.h"
  78. #include "procmon.h"
  79. /** Yield true iff <b>s</b> is the state of a control_connection_t that has
  80. * finished authentication and is accepting commands. */
  81. #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
  82. /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
  83. * connection is interested in events of type <b>e</b>. We use this
  84. * so that we can decide to skip generating event messages that nobody
  85. * has interest in without having to walk over the global connection
  86. * list to find out.
  87. **/
  88. typedef uint64_t event_mask_t;
  89. /** An event mask of all the events that any controller is interested in
  90. * receiving. */
  91. static event_mask_t global_event_mask = 0;
  92. /** True iff we have disabled log messages from being sent to the controller */
  93. static int disable_log_messages = 0;
  94. /** Macro: true if any control connection is interested in events of type
  95. * <b>e</b>. */
  96. #define EVENT_IS_INTERESTING(e) \
  97. (!! (global_event_mask & EVENT_MASK_(e)))
  98. /** If we're using cookie-type authentication, how long should our cookies be?
  99. */
  100. #define AUTHENTICATION_COOKIE_LEN 32
  101. /** If true, we've set authentication_cookie to a secret code and
  102. * stored it to disk. */
  103. static int authentication_cookie_is_set = 0;
  104. /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
  105. * and which we're using to authenticate controllers. (If the controller can
  106. * read it off disk, it has permission to connect.) */
  107. static uint8_t *authentication_cookie = NULL;
  108. #define SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT \
  109. "Tor safe cookie authentication server-to-controller hash"
  110. #define SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT \
  111. "Tor safe cookie authentication controller-to-server hash"
  112. #define SAFECOOKIE_SERVER_NONCE_LEN DIGEST256_LEN
  113. /** The list of onion services that have been added via ADD_ONION that do not
  114. * belong to any particular control connection.
  115. */
  116. static smartlist_t *detached_onion_services = NULL;
  117. /** A sufficiently large size to record the last bootstrap phase string. */
  118. #define BOOTSTRAP_MSG_LEN 1024
  119. /** What was the last bootstrap phase message we sent? We keep track
  120. * of this so we can respond to getinfo status/bootstrap-phase queries. */
  121. static char last_sent_bootstrap_message[BOOTSTRAP_MSG_LEN];
  122. static void connection_printf_to_buf(control_connection_t *conn,
  123. const char *format, ...)
  124. CHECK_PRINTF(2,3);
  125. static void send_control_event_impl(uint16_t event,
  126. const char *format, va_list ap)
  127. CHECK_PRINTF(2,0);
  128. static int control_event_status(int type, int severity, const char *format,
  129. va_list args)
  130. CHECK_PRINTF(3,0);
  131. static void send_control_done(control_connection_t *conn);
  132. static void send_control_event(uint16_t event,
  133. const char *format, ...)
  134. CHECK_PRINTF(2,3);
  135. static int handle_control_setconf(control_connection_t *conn, uint32_t len,
  136. char *body);
  137. static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
  138. char *body);
  139. static int handle_control_getconf(control_connection_t *conn, uint32_t len,
  140. const char *body);
  141. static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
  142. const char *body);
  143. static int handle_control_setevents(control_connection_t *conn, uint32_t len,
  144. const char *body);
  145. static int handle_control_authenticate(control_connection_t *conn,
  146. uint32_t len,
  147. const char *body);
  148. static int handle_control_signal(control_connection_t *conn, uint32_t len,
  149. const char *body);
  150. static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  151. const char *body);
  152. static char *list_getinfo_options(void);
  153. static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
  154. const char *body);
  155. static int handle_control_extendcircuit(control_connection_t *conn,
  156. uint32_t len,
  157. const char *body);
  158. static int handle_control_setcircuitpurpose(control_connection_t *conn,
  159. uint32_t len, const char *body);
  160. static int handle_control_attachstream(control_connection_t *conn,
  161. uint32_t len,
  162. const char *body);
  163. static int handle_control_postdescriptor(control_connection_t *conn,
  164. uint32_t len,
  165. const char *body);
  166. static int handle_control_redirectstream(control_connection_t *conn,
  167. uint32_t len,
  168. const char *body);
  169. static int handle_control_closestream(control_connection_t *conn, uint32_t len,
  170. const char *body);
  171. static int handle_control_closecircuit(control_connection_t *conn,
  172. uint32_t len,
  173. const char *body);
  174. static int handle_control_resolve(control_connection_t *conn, uint32_t len,
  175. const char *body);
  176. static int handle_control_usefeature(control_connection_t *conn,
  177. uint32_t len,
  178. const char *body);
  179. static int handle_control_hsfetch(control_connection_t *conn, uint32_t len,
  180. const char *body);
  181. static int handle_control_hspost(control_connection_t *conn, uint32_t len,
  182. const char *body);
  183. static int handle_control_add_onion(control_connection_t *conn, uint32_t len,
  184. const char *body);
  185. static int handle_control_del_onion(control_connection_t *conn, uint32_t len,
  186. const char *body);
  187. static int write_stream_target_to_buf(entry_connection_t *conn, char *buf,
  188. size_t len);
  189. static void orconn_target_get_name(char *buf, size_t len,
  190. or_connection_t *conn);
  191. static int get_cached_network_liveness(void);
  192. static void set_cached_network_liveness(int liveness);
  193. static void flush_queued_events_cb(evutil_socket_t fd, short what, void *arg);
  194. static char * download_status_to_string(const download_status_t *dl);
  195. /** Given a control event code for a message event, return the corresponding
  196. * log severity. */
  197. static inline int
  198. event_to_log_severity(int event)
  199. {
  200. switch (event) {
  201. case EVENT_DEBUG_MSG: return LOG_DEBUG;
  202. case EVENT_INFO_MSG: return LOG_INFO;
  203. case EVENT_NOTICE_MSG: return LOG_NOTICE;
  204. case EVENT_WARN_MSG: return LOG_WARN;
  205. case EVENT_ERR_MSG: return LOG_ERR;
  206. default: return -1;
  207. }
  208. }
  209. /** Given a log severity, return the corresponding control event code. */
  210. static inline int
  211. log_severity_to_event(int severity)
  212. {
  213. switch (severity) {
  214. case LOG_DEBUG: return EVENT_DEBUG_MSG;
  215. case LOG_INFO: return EVENT_INFO_MSG;
  216. case LOG_NOTICE: return EVENT_NOTICE_MSG;
  217. case LOG_WARN: return EVENT_WARN_MSG;
  218. case LOG_ERR: return EVENT_ERR_MSG;
  219. default: return -1;
  220. }
  221. }
  222. /** Helper: clear bandwidth counters of all origin circuits. */
  223. static void
  224. clear_circ_bw_fields(void)
  225. {
  226. origin_circuit_t *ocirc;
  227. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  228. if (!CIRCUIT_IS_ORIGIN(circ))
  229. continue;
  230. ocirc = TO_ORIGIN_CIRCUIT(circ);
  231. ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
  232. }
  233. SMARTLIST_FOREACH_END(circ);
  234. }
  235. /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
  236. * connection's event_mask field. */
  237. void
  238. control_update_global_event_mask(void)
  239. {
  240. smartlist_t *conns = get_connection_array();
  241. event_mask_t old_mask, new_mask;
  242. old_mask = global_event_mask;
  243. global_event_mask = 0;
  244. SMARTLIST_FOREACH(conns, connection_t *, _conn,
  245. {
  246. if (_conn->type == CONN_TYPE_CONTROL &&
  247. STATE_IS_OPEN(_conn->state)) {
  248. control_connection_t *conn = TO_CONTROL_CONN(_conn);
  249. global_event_mask |= conn->event_mask;
  250. }
  251. });
  252. new_mask = global_event_mask;
  253. /* Handle the aftermath. Set up the log callback to tell us only what
  254. * we want to hear...*/
  255. control_adjust_event_log_severity();
  256. /* ...then, if we've started logging stream or circ bw, clear the
  257. * appropriate fields. */
  258. if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
  259. (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
  260. SMARTLIST_FOREACH(conns, connection_t *, conn,
  261. {
  262. if (conn->type == CONN_TYPE_AP) {
  263. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  264. edge_conn->n_written = edge_conn->n_read = 0;
  265. }
  266. });
  267. }
  268. if (! (old_mask & EVENT_CIRC_BANDWIDTH_USED) &&
  269. (new_mask & EVENT_CIRC_BANDWIDTH_USED)) {
  270. clear_circ_bw_fields();
  271. }
  272. }
  273. /** Adjust the log severities that result in control_event_logmsg being called
  274. * to match the severity of log messages that any controllers are interested
  275. * in. */
  276. void
  277. control_adjust_event_log_severity(void)
  278. {
  279. int i;
  280. int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
  281. for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
  282. if (EVENT_IS_INTERESTING(i)) {
  283. min_log_event = i;
  284. break;
  285. }
  286. }
  287. for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
  288. if (EVENT_IS_INTERESTING(i)) {
  289. max_log_event = i;
  290. break;
  291. }
  292. }
  293. if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
  294. if (min_log_event > EVENT_NOTICE_MSG)
  295. min_log_event = EVENT_NOTICE_MSG;
  296. if (max_log_event < EVENT_ERR_MSG)
  297. max_log_event = EVENT_ERR_MSG;
  298. }
  299. if (min_log_event <= max_log_event)
  300. change_callback_log_severity(event_to_log_severity(min_log_event),
  301. event_to_log_severity(max_log_event),
  302. control_event_logmsg);
  303. else
  304. change_callback_log_severity(LOG_ERR, LOG_ERR,
  305. control_event_logmsg);
  306. }
  307. /** Return true iff the event with code <b>c</b> is being sent to any current
  308. * control connection. This is useful if the amount of work needed to prepare
  309. * to call the appropriate control_event_...() function is high.
  310. */
  311. int
  312. control_event_is_interesting(int event)
  313. {
  314. return EVENT_IS_INTERESTING(event);
  315. }
  316. /** Append a NUL-terminated string <b>s</b> to the end of
  317. * <b>conn</b>-\>outbuf.
  318. */
  319. static inline void
  320. connection_write_str_to_buf(const char *s, control_connection_t *conn)
  321. {
  322. size_t len = strlen(s);
  323. connection_write_to_buf(s, len, TO_CONN(conn));
  324. }
  325. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  326. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
  327. * contents of <b>data</b> into *<b>out</b>, adding a period before any period
  328. * that appears at the start of a line, and adding a period-CRLF line at
  329. * the end. Replace all LF characters sequences with CRLF. Return the number
  330. * of bytes in *<b>out</b>.
  331. */
  332. STATIC size_t
  333. write_escaped_data(const char *data, size_t len, char **out)
  334. {
  335. size_t sz_out = len+8;
  336. char *outp;
  337. const char *start = data, *end;
  338. int i;
  339. int start_of_line;
  340. for (i=0; i<(int)len; ++i) {
  341. if (data[i]== '\n')
  342. sz_out += 2; /* Maybe add a CR; maybe add a dot. */
  343. }
  344. *out = outp = tor_malloc(sz_out+1);
  345. end = data+len;
  346. start_of_line = 1;
  347. while (data < end) {
  348. if (*data == '\n') {
  349. if (data > start && data[-1] != '\r')
  350. *outp++ = '\r';
  351. start_of_line = 1;
  352. } else if (*data == '.') {
  353. if (start_of_line) {
  354. start_of_line = 0;
  355. *outp++ = '.';
  356. }
  357. } else {
  358. start_of_line = 0;
  359. }
  360. *outp++ = *data++;
  361. }
  362. if (outp < *out+2 || fast_memcmp(outp-2, "\r\n", 2)) {
  363. *outp++ = '\r';
  364. *outp++ = '\n';
  365. }
  366. *outp++ = '.';
  367. *outp++ = '\r';
  368. *outp++ = '\n';
  369. *outp = '\0'; /* NUL-terminate just in case. */
  370. tor_assert((outp - *out) <= (int)sz_out);
  371. return outp - *out;
  372. }
  373. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  374. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  375. * the contents of <b>data</b> into *<b>out</b>, removing any period
  376. * that appears at the start of a line, and replacing all CRLF sequences
  377. * with LF. Return the number of
  378. * bytes in *<b>out</b>. */
  379. STATIC size_t
  380. read_escaped_data(const char *data, size_t len, char **out)
  381. {
  382. char *outp;
  383. const char *next;
  384. const char *end;
  385. *out = outp = tor_malloc(len+1);
  386. end = data+len;
  387. while (data < end) {
  388. /* we're at the start of a line. */
  389. if (*data == '.')
  390. ++data;
  391. next = memchr(data, '\n', end-data);
  392. if (next) {
  393. size_t n_to_copy = next-data;
  394. /* Don't copy a CR that precedes this LF. */
  395. if (n_to_copy && *(next-1) == '\r')
  396. --n_to_copy;
  397. memcpy(outp, data, n_to_copy);
  398. outp += n_to_copy;
  399. data = next+1; /* This will point at the start of the next line,
  400. * or the end of the string, or a period. */
  401. } else {
  402. memcpy(outp, data, end-data);
  403. outp += (end-data);
  404. *outp = '\0';
  405. return outp - *out;
  406. }
  407. *outp++ = '\n';
  408. }
  409. *outp = '\0';
  410. return outp - *out;
  411. }
  412. /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
  413. * double-quoted string with escaped characters, return the length of that
  414. * string (as encoded, including quotes). Otherwise return -1. */
  415. static inline int
  416. get_escaped_string_length(const char *start, size_t in_len_max,
  417. int *chars_out)
  418. {
  419. const char *cp, *end;
  420. int chars = 0;
  421. if (*start != '\"')
  422. return -1;
  423. cp = start+1;
  424. end = start+in_len_max;
  425. /* Calculate length. */
  426. while (1) {
  427. if (cp >= end) {
  428. return -1; /* Too long. */
  429. } else if (*cp == '\\') {
  430. if (++cp == end)
  431. return -1; /* Can't escape EOS. */
  432. ++cp;
  433. ++chars;
  434. } else if (*cp == '\"') {
  435. break;
  436. } else {
  437. ++cp;
  438. ++chars;
  439. }
  440. }
  441. if (chars_out)
  442. *chars_out = chars;
  443. return (int)(cp - start+1);
  444. }
  445. /** As decode_escaped_string, but does not decode the string: copies the
  446. * entire thing, including quotation marks. */
  447. static const char *
  448. extract_escaped_string(const char *start, size_t in_len_max,
  449. char **out, size_t *out_len)
  450. {
  451. int length = get_escaped_string_length(start, in_len_max, NULL);
  452. if (length<0)
  453. return NULL;
  454. *out_len = length;
  455. *out = tor_strndup(start, *out_len);
  456. return start+length;
  457. }
  458. /** Given a pointer to a string starting at <b>start</b> containing
  459. * <b>in_len_max</b> characters, decode a string beginning with one double
  460. * quote, containing any number of non-quote characters or characters escaped
  461. * with a backslash, and ending with a final double quote. Place the resulting
  462. * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
  463. * store its length in <b>out_len</b>. On success, return a pointer to the
  464. * character immediately following the escaped string. On failure, return
  465. * NULL. */
  466. static const char *
  467. decode_escaped_string(const char *start, size_t in_len_max,
  468. char **out, size_t *out_len)
  469. {
  470. const char *cp, *end;
  471. char *outp;
  472. int len, n_chars = 0;
  473. len = get_escaped_string_length(start, in_len_max, &n_chars);
  474. if (len<0)
  475. return NULL;
  476. end = start+len-1; /* Index of last quote. */
  477. tor_assert(*end == '\"');
  478. outp = *out = tor_malloc(len+1);
  479. *out_len = n_chars;
  480. cp = start+1;
  481. while (cp < end) {
  482. if (*cp == '\\')
  483. ++cp;
  484. *outp++ = *cp++;
  485. }
  486. *outp = '\0';
  487. tor_assert((outp - *out) == (int)*out_len);
  488. return end+1;
  489. }
  490. /** Acts like sprintf, but writes its formatted string to the end of
  491. * <b>conn</b>-\>outbuf. */
  492. static void
  493. connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
  494. {
  495. va_list ap;
  496. char *buf = NULL;
  497. int len;
  498. va_start(ap,format);
  499. len = tor_vasprintf(&buf, format, ap);
  500. va_end(ap);
  501. if (len < 0) {
  502. log_err(LD_BUG, "Unable to format string for controller.");
  503. tor_assert(0);
  504. }
  505. connection_write_to_buf(buf, (size_t)len, TO_CONN(conn));
  506. tor_free(buf);
  507. }
  508. /** Write all of the open control ports to ControlPortWriteToFile */
  509. void
  510. control_ports_write_to_file(void)
  511. {
  512. smartlist_t *lines;
  513. char *joined = NULL;
  514. const or_options_t *options = get_options();
  515. if (!options->ControlPortWriteToFile)
  516. return;
  517. lines = smartlist_new();
  518. SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t *, conn) {
  519. if (conn->type != CONN_TYPE_CONTROL_LISTENER || conn->marked_for_close)
  520. continue;
  521. #ifdef AF_UNIX
  522. if (conn->socket_family == AF_UNIX) {
  523. smartlist_add_asprintf(lines, "UNIX_PORT=%s\n", conn->address);
  524. continue;
  525. }
  526. #endif
  527. smartlist_add_asprintf(lines, "PORT=%s:%d\n", conn->address, conn->port);
  528. } SMARTLIST_FOREACH_END(conn);
  529. joined = smartlist_join_strings(lines, "", 0, NULL);
  530. if (write_str_to_file(options->ControlPortWriteToFile, joined, 0) < 0) {
  531. log_warn(LD_CONTROL, "Writing %s failed: %s",
  532. options->ControlPortWriteToFile, strerror(errno));
  533. }
  534. #ifndef _WIN32
  535. if (options->ControlPortFileGroupReadable) {
  536. if (chmod(options->ControlPortWriteToFile, 0640)) {
  537. log_warn(LD_FS,"Unable to make %s group-readable.",
  538. options->ControlPortWriteToFile);
  539. }
  540. }
  541. #endif
  542. tor_free(joined);
  543. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  544. smartlist_free(lines);
  545. }
  546. /** Send a "DONE" message down the control connection <b>conn</b>. */
  547. static void
  548. send_control_done(control_connection_t *conn)
  549. {
  550. connection_write_str_to_buf("250 OK\r\n", conn);
  551. }
  552. /** Represents an event that's queued to be sent to one or more
  553. * controllers. */
  554. typedef struct queued_event_s {
  555. uint16_t event;
  556. char *msg;
  557. } queued_event_t;
  558. /** Pointer to int. If this is greater than 0, we don't allow new events to be
  559. * queued. */
  560. static tor_threadlocal_t block_event_queue_flag;
  561. /** Holds a smartlist of queued_event_t objects that may need to be sent
  562. * to one or more controllers */
  563. static smartlist_t *queued_control_events = NULL;
  564. /** True if the flush_queued_events_event is pending. */
  565. static int flush_queued_event_pending = 0;
  566. /** Lock to protect the above fields. */
  567. static tor_mutex_t *queued_control_events_lock = NULL;
  568. /** An event that should fire in order to flush the contents of
  569. * queued_control_events. */
  570. static struct event *flush_queued_events_event = NULL;
  571. void
  572. control_initialize_event_queue(void)
  573. {
  574. if (queued_control_events == NULL) {
  575. queued_control_events = smartlist_new();
  576. }
  577. if (flush_queued_events_event == NULL) {
  578. struct event_base *b = tor_libevent_get_base();
  579. if (b) {
  580. flush_queued_events_event = tor_event_new(b,
  581. -1, 0, flush_queued_events_cb,
  582. NULL);
  583. tor_assert(flush_queued_events_event);
  584. }
  585. }
  586. if (queued_control_events_lock == NULL) {
  587. queued_control_events_lock = tor_mutex_new();
  588. tor_threadlocal_init(&block_event_queue_flag);
  589. }
  590. }
  591. static int *
  592. get_block_event_queue(void)
  593. {
  594. int *val = tor_threadlocal_get(&block_event_queue_flag);
  595. if (PREDICT_UNLIKELY(val == NULL)) {
  596. val = tor_malloc_zero(sizeof(int));
  597. tor_threadlocal_set(&block_event_queue_flag, val);
  598. }
  599. return val;
  600. }
  601. /** Helper: inserts an event on the list of events queued to be sent to
  602. * one or more controllers, and schedules the events to be flushed if needed.
  603. *
  604. * This function takes ownership of <b>msg</b>, and may free it.
  605. *
  606. * We queue these events rather than send them immediately in order to break
  607. * the dependency in our callgraph from code that generates events for the
  608. * controller, and the network layer at large. Otherwise, nearly every
  609. * interesting part of Tor would potentially call every other interesting part
  610. * of Tor.
  611. */
  612. MOCK_IMPL(STATIC void,
  613. queue_control_event_string,(uint16_t event, char *msg))
  614. {
  615. /* This is redundant with checks done elsewhere, but it's a last-ditch
  616. * attempt to avoid queueing something we shouldn't have to queue. */
  617. if (PREDICT_UNLIKELY( ! EVENT_IS_INTERESTING(event) )) {
  618. tor_free(msg);
  619. return;
  620. }
  621. int *block_event_queue = get_block_event_queue();
  622. if (*block_event_queue) {
  623. tor_free(msg);
  624. return;
  625. }
  626. queued_event_t *ev = tor_malloc(sizeof(*ev));
  627. ev->event = event;
  628. ev->msg = msg;
  629. /* No queueing an event while queueing an event */
  630. ++*block_event_queue;
  631. tor_mutex_acquire(queued_control_events_lock);
  632. tor_assert(queued_control_events);
  633. smartlist_add(queued_control_events, ev);
  634. int activate_event = 0;
  635. if (! flush_queued_event_pending && in_main_thread()) {
  636. activate_event = 1;
  637. flush_queued_event_pending = 1;
  638. }
  639. tor_mutex_release(queued_control_events_lock);
  640. --*block_event_queue;
  641. /* We just put an event on the queue; mark the queue to be
  642. * flushed. We only do this from the main thread for now; otherwise,
  643. * we'd need to incur locking overhead in Libevent or use a socket.
  644. */
  645. if (activate_event) {
  646. tor_assert(flush_queued_events_event);
  647. event_active(flush_queued_events_event, EV_READ, 1);
  648. }
  649. }
  650. /** Release all storage held by <b>ev</b>. */
  651. static void
  652. queued_event_free(queued_event_t *ev)
  653. {
  654. if (ev == NULL)
  655. return;
  656. tor_free(ev->msg);
  657. tor_free(ev);
  658. }
  659. /** Send every queued event to every controller that's interested in it,
  660. * and remove the events from the queue. If <b>force</b> is true,
  661. * then make all controllers send their data out immediately, since we
  662. * may be about to shut down. */
  663. static void
  664. queued_events_flush_all(int force)
  665. {
  666. if (PREDICT_UNLIKELY(queued_control_events == NULL)) {
  667. return;
  668. }
  669. smartlist_t *all_conns = get_connection_array();
  670. smartlist_t *controllers = smartlist_new();
  671. smartlist_t *queued_events;
  672. int *block_event_queue = get_block_event_queue();
  673. ++*block_event_queue;
  674. tor_mutex_acquire(queued_control_events_lock);
  675. /* No queueing an event while flushing events. */
  676. flush_queued_event_pending = 0;
  677. queued_events = queued_control_events;
  678. queued_control_events = smartlist_new();
  679. tor_mutex_release(queued_control_events_lock);
  680. /* Gather all the controllers that will care... */
  681. SMARTLIST_FOREACH_BEGIN(all_conns, connection_t *, conn) {
  682. if (conn->type == CONN_TYPE_CONTROL &&
  683. !conn->marked_for_close &&
  684. conn->state == CONTROL_CONN_STATE_OPEN) {
  685. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  686. smartlist_add(controllers, control_conn);
  687. }
  688. } SMARTLIST_FOREACH_END(conn);
  689. SMARTLIST_FOREACH_BEGIN(queued_events, queued_event_t *, ev) {
  690. const event_mask_t bit = ((event_mask_t)1) << ev->event;
  691. const size_t msg_len = strlen(ev->msg);
  692. SMARTLIST_FOREACH_BEGIN(controllers, control_connection_t *,
  693. control_conn) {
  694. if (control_conn->event_mask & bit) {
  695. connection_write_to_buf(ev->msg, msg_len, TO_CONN(control_conn));
  696. }
  697. } SMARTLIST_FOREACH_END(control_conn);
  698. queued_event_free(ev);
  699. } SMARTLIST_FOREACH_END(ev);
  700. if (force) {
  701. SMARTLIST_FOREACH_BEGIN(controllers, control_connection_t *,
  702. control_conn) {
  703. connection_flush(TO_CONN(control_conn));
  704. } SMARTLIST_FOREACH_END(control_conn);
  705. }
  706. smartlist_free(queued_events);
  707. smartlist_free(controllers);
  708. --*block_event_queue;
  709. }
  710. /** Libevent callback: Flushes pending events to controllers that are
  711. * interested in them */
  712. static void
  713. flush_queued_events_cb(evutil_socket_t fd, short what, void *arg)
  714. {
  715. (void) fd;
  716. (void) what;
  717. (void) arg;
  718. queued_events_flush_all(0);
  719. }
  720. /** Send an event to all v1 controllers that are listening for code
  721. * <b>event</b>. The event's body is given by <b>msg</b>.
  722. *
  723. * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
  724. * respect to the EXTENDED_EVENTS feature. */
  725. MOCK_IMPL(STATIC void,
  726. send_control_event_string,(uint16_t event,
  727. const char *msg))
  728. {
  729. tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
  730. queue_control_event_string(event, tor_strdup(msg));
  731. }
  732. /** Helper for send_control_event and control_event_status:
  733. * Send an event to all v1 controllers that are listening for code
  734. * <b>event</b>. The event's body is created by the printf-style format in
  735. * <b>format</b>, and other arguments as provided. */
  736. static void
  737. send_control_event_impl(uint16_t event,
  738. const char *format, va_list ap)
  739. {
  740. char *buf = NULL;
  741. int len;
  742. len = tor_vasprintf(&buf, format, ap);
  743. if (len < 0) {
  744. log_warn(LD_BUG, "Unable to format event for controller.");
  745. return;
  746. }
  747. queue_control_event_string(event, buf);
  748. }
  749. /** Send an event to all v1 controllers that are listening for code
  750. * <b>event</b>. The event's body is created by the printf-style format in
  751. * <b>format</b>, and other arguments as provided. */
  752. static void
  753. send_control_event(uint16_t event,
  754. const char *format, ...)
  755. {
  756. va_list ap;
  757. va_start(ap, format);
  758. send_control_event_impl(event, format, ap);
  759. va_end(ap);
  760. }
  761. /** Given a text circuit <b>id</b>, return the corresponding circuit. */
  762. static origin_circuit_t *
  763. get_circ(const char *id)
  764. {
  765. uint32_t n_id;
  766. int ok;
  767. n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
  768. if (!ok)
  769. return NULL;
  770. return circuit_get_by_global_id(n_id);
  771. }
  772. /** Given a text stream <b>id</b>, return the corresponding AP connection. */
  773. static entry_connection_t *
  774. get_stream(const char *id)
  775. {
  776. uint64_t n_id;
  777. int ok;
  778. connection_t *conn;
  779. n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
  780. if (!ok)
  781. return NULL;
  782. conn = connection_get_by_global_id(n_id);
  783. if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
  784. return NULL;
  785. return TO_ENTRY_CONN(conn);
  786. }
  787. /** Helper for setconf and resetconf. Acts like setconf, except
  788. * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
  789. * contents of body.
  790. */
  791. static int
  792. control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
  793. int use_defaults)
  794. {
  795. setopt_err_t opt_err;
  796. config_line_t *lines=NULL;
  797. char *start = body;
  798. char *errstring = NULL;
  799. const unsigned flags =
  800. CAL_CLEAR_FIRST | (use_defaults ? CAL_USE_DEFAULTS : 0);
  801. char *config;
  802. smartlist_t *entries = smartlist_new();
  803. /* We have a string, "body", of the format '(key(=val|="val")?)' entries
  804. * separated by space. break it into a list of configuration entries. */
  805. while (*body) {
  806. char *eq = body;
  807. char *key;
  808. char *entry;
  809. while (!TOR_ISSPACE(*eq) && *eq != '=')
  810. ++eq;
  811. key = tor_strndup(body, eq-body);
  812. body = eq+1;
  813. if (*eq == '=') {
  814. char *val=NULL;
  815. size_t val_len=0;
  816. if (*body != '\"') {
  817. char *val_start = body;
  818. while (!TOR_ISSPACE(*body))
  819. body++;
  820. val = tor_strndup(val_start, body-val_start);
  821. val_len = strlen(val);
  822. } else {
  823. body = (char*)extract_escaped_string(body, (len - (body-start)),
  824. &val, &val_len);
  825. if (!body) {
  826. connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
  827. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  828. smartlist_free(entries);
  829. tor_free(key);
  830. return 0;
  831. }
  832. }
  833. tor_asprintf(&entry, "%s %s", key, val);
  834. tor_free(key);
  835. tor_free(val);
  836. } else {
  837. entry = key;
  838. }
  839. smartlist_add(entries, entry);
  840. while (TOR_ISSPACE(*body))
  841. ++body;
  842. }
  843. smartlist_add_strdup(entries, "");
  844. config = smartlist_join_strings(entries, "\n", 0, NULL);
  845. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  846. smartlist_free(entries);
  847. if (config_get_lines(config, &lines, 0) < 0) {
  848. log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
  849. connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
  850. conn);
  851. tor_free(config);
  852. return 0;
  853. }
  854. tor_free(config);
  855. opt_err = options_trial_assign(lines, flags, &errstring);
  856. {
  857. const char *msg;
  858. switch (opt_err) {
  859. case SETOPT_ERR_MISC:
  860. msg = "552 Unrecognized option";
  861. break;
  862. case SETOPT_ERR_PARSE:
  863. msg = "513 Unacceptable option value";
  864. break;
  865. case SETOPT_ERR_TRANSITION:
  866. msg = "553 Transition not allowed";
  867. break;
  868. case SETOPT_ERR_SETTING:
  869. default:
  870. msg = "553 Unable to set option";
  871. break;
  872. case SETOPT_OK:
  873. config_free_lines(lines);
  874. send_control_done(conn);
  875. return 0;
  876. }
  877. log_warn(LD_CONTROL,
  878. "Controller gave us config lines that didn't validate: %s",
  879. errstring);
  880. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  881. config_free_lines(lines);
  882. tor_free(errstring);
  883. return 0;
  884. }
  885. }
  886. /** Called when we receive a SETCONF message: parse the body and try
  887. * to update our configuration. Reply with a DONE or ERROR message.
  888. * Modifies the contents of body.*/
  889. static int
  890. handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
  891. {
  892. return control_setconf_helper(conn, len, body, 0);
  893. }
  894. /** Called when we receive a RESETCONF message: parse the body and try
  895. * to update our configuration. Reply with a DONE or ERROR message.
  896. * Modifies the contents of body. */
  897. static int
  898. handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
  899. {
  900. return control_setconf_helper(conn, len, body, 1);
  901. }
  902. /** Called when we receive a GETCONF message. Parse the request, and
  903. * reply with a CONFVALUE or an ERROR message */
  904. static int
  905. handle_control_getconf(control_connection_t *conn, uint32_t body_len,
  906. const char *body)
  907. {
  908. smartlist_t *questions = smartlist_new();
  909. smartlist_t *answers = smartlist_new();
  910. smartlist_t *unrecognized = smartlist_new();
  911. char *msg = NULL;
  912. size_t msg_len;
  913. const or_options_t *options = get_options();
  914. int i, len;
  915. (void) body_len; /* body is NUL-terminated; so we can ignore len. */
  916. smartlist_split_string(questions, body, " ",
  917. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  918. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  919. if (!option_is_recognized(q)) {
  920. smartlist_add(unrecognized, (char*) q);
  921. } else {
  922. config_line_t *answer = option_get_assignment(options,q);
  923. if (!answer) {
  924. const char *name = option_get_canonical_name(q);
  925. smartlist_add_asprintf(answers, "250-%s\r\n", name);
  926. }
  927. while (answer) {
  928. config_line_t *next;
  929. smartlist_add_asprintf(answers, "250-%s=%s\r\n",
  930. answer->key, answer->value);
  931. next = answer->next;
  932. tor_free(answer->key);
  933. tor_free(answer->value);
  934. tor_free(answer);
  935. answer = next;
  936. }
  937. }
  938. } SMARTLIST_FOREACH_END(q);
  939. if ((len = smartlist_len(unrecognized))) {
  940. for (i=0; i < len-1; ++i)
  941. connection_printf_to_buf(conn,
  942. "552-Unrecognized configuration key \"%s\"\r\n",
  943. (char*)smartlist_get(unrecognized, i));
  944. connection_printf_to_buf(conn,
  945. "552 Unrecognized configuration key \"%s\"\r\n",
  946. (char*)smartlist_get(unrecognized, len-1));
  947. } else if ((len = smartlist_len(answers))) {
  948. char *tmp = smartlist_get(answers, len-1);
  949. tor_assert(strlen(tmp)>4);
  950. tmp[3] = ' ';
  951. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  952. connection_write_to_buf(msg, msg_len, TO_CONN(conn));
  953. } else {
  954. connection_write_str_to_buf("250 OK\r\n", conn);
  955. }
  956. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  957. smartlist_free(answers);
  958. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  959. smartlist_free(questions);
  960. smartlist_free(unrecognized);
  961. tor_free(msg);
  962. return 0;
  963. }
  964. /** Called when we get a +LOADCONF message. */
  965. static int
  966. handle_control_loadconf(control_connection_t *conn, uint32_t len,
  967. const char *body)
  968. {
  969. setopt_err_t retval;
  970. char *errstring = NULL;
  971. const char *msg = NULL;
  972. (void) len;
  973. retval = options_init_from_string(NULL, body, CMD_RUN_TOR, NULL, &errstring);
  974. if (retval != SETOPT_OK)
  975. log_warn(LD_CONTROL,
  976. "Controller gave us config file that didn't validate: %s",
  977. errstring);
  978. switch (retval) {
  979. case SETOPT_ERR_PARSE:
  980. msg = "552 Invalid config file";
  981. break;
  982. case SETOPT_ERR_TRANSITION:
  983. msg = "553 Transition not allowed";
  984. break;
  985. case SETOPT_ERR_SETTING:
  986. msg = "553 Unable to set option";
  987. break;
  988. case SETOPT_ERR_MISC:
  989. default:
  990. msg = "550 Unable to load config";
  991. break;
  992. case SETOPT_OK:
  993. break;
  994. }
  995. if (msg) {
  996. if (errstring)
  997. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  998. else
  999. connection_printf_to_buf(conn, "%s\r\n", msg);
  1000. } else {
  1001. send_control_done(conn);
  1002. }
  1003. tor_free(errstring);
  1004. return 0;
  1005. }
  1006. /** Helper structure: maps event values to their names. */
  1007. struct control_event_t {
  1008. uint16_t event_code;
  1009. const char *event_name;
  1010. };
  1011. /** Table mapping event values to their names. Used to implement SETEVENTS
  1012. * and GETINFO events/names, and to keep they in sync. */
  1013. static const struct control_event_t control_event_table[] = {
  1014. { EVENT_CIRCUIT_STATUS, "CIRC" },
  1015. { EVENT_CIRCUIT_STATUS_MINOR, "CIRC_MINOR" },
  1016. { EVENT_STREAM_STATUS, "STREAM" },
  1017. { EVENT_OR_CONN_STATUS, "ORCONN" },
  1018. { EVENT_BANDWIDTH_USED, "BW" },
  1019. { EVENT_DEBUG_MSG, "DEBUG" },
  1020. { EVENT_INFO_MSG, "INFO" },
  1021. { EVENT_NOTICE_MSG, "NOTICE" },
  1022. { EVENT_WARN_MSG, "WARN" },
  1023. { EVENT_ERR_MSG, "ERR" },
  1024. { EVENT_NEW_DESC, "NEWDESC" },
  1025. { EVENT_ADDRMAP, "ADDRMAP" },
  1026. { EVENT_AUTHDIR_NEWDESCS, "AUTHDIR_NEWDESCS" },
  1027. { EVENT_DESCCHANGED, "DESCCHANGED" },
  1028. { EVENT_NS, "NS" },
  1029. { EVENT_STATUS_GENERAL, "STATUS_GENERAL" },
  1030. { EVENT_STATUS_CLIENT, "STATUS_CLIENT" },
  1031. { EVENT_STATUS_SERVER, "STATUS_SERVER" },
  1032. { EVENT_GUARD, "GUARD" },
  1033. { EVENT_STREAM_BANDWIDTH_USED, "STREAM_BW" },
  1034. { EVENT_CLIENTS_SEEN, "CLIENTS_SEEN" },
  1035. { EVENT_NEWCONSENSUS, "NEWCONSENSUS" },
  1036. { EVENT_BUILDTIMEOUT_SET, "BUILDTIMEOUT_SET" },
  1037. { EVENT_GOT_SIGNAL, "SIGNAL" },
  1038. { EVENT_CONF_CHANGED, "CONF_CHANGED"},
  1039. { EVENT_CONN_BW, "CONN_BW" },
  1040. { EVENT_CELL_STATS, "CELL_STATS" },
  1041. { EVENT_TB_EMPTY, "TB_EMPTY" },
  1042. { EVENT_CIRC_BANDWIDTH_USED, "CIRC_BW" },
  1043. { EVENT_TRANSPORT_LAUNCHED, "TRANSPORT_LAUNCHED" },
  1044. { EVENT_HS_DESC, "HS_DESC" },
  1045. { EVENT_HS_DESC_CONTENT, "HS_DESC_CONTENT" },
  1046. { EVENT_NETWORK_LIVENESS, "NETWORK_LIVENESS" },
  1047. { 0, NULL },
  1048. };
  1049. /** Called when we get a SETEVENTS message: update conn->event_mask,
  1050. * and reply with DONE or ERROR. */
  1051. static int
  1052. handle_control_setevents(control_connection_t *conn, uint32_t len,
  1053. const char *body)
  1054. {
  1055. int event_code;
  1056. event_mask_t event_mask = 0;
  1057. smartlist_t *events = smartlist_new();
  1058. (void) len;
  1059. smartlist_split_string(events, body, " ",
  1060. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1061. SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
  1062. {
  1063. if (!strcasecmp(ev, "EXTENDED")) {
  1064. continue;
  1065. } else {
  1066. int i;
  1067. event_code = -1;
  1068. for (i = 0; control_event_table[i].event_name != NULL; ++i) {
  1069. if (!strcasecmp(ev, control_event_table[i].event_name)) {
  1070. event_code = control_event_table[i].event_code;
  1071. break;
  1072. }
  1073. }
  1074. if (event_code == -1) {
  1075. connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
  1076. ev);
  1077. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  1078. smartlist_free(events);
  1079. return 0;
  1080. }
  1081. }
  1082. event_mask |= (((event_mask_t)1) << event_code);
  1083. }
  1084. SMARTLIST_FOREACH_END(ev);
  1085. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  1086. smartlist_free(events);
  1087. conn->event_mask = event_mask;
  1088. control_update_global_event_mask();
  1089. send_control_done(conn);
  1090. return 0;
  1091. }
  1092. /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
  1093. * Return a smartlist of acceptable passwords (unterminated strings of
  1094. * length S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on
  1095. * failure.
  1096. */
  1097. smartlist_t *
  1098. decode_hashed_passwords(config_line_t *passwords)
  1099. {
  1100. char decoded[64];
  1101. config_line_t *cl;
  1102. smartlist_t *sl = smartlist_new();
  1103. tor_assert(passwords);
  1104. for (cl = passwords; cl; cl = cl->next) {
  1105. const char *hashed = cl->value;
  1106. if (!strcmpstart(hashed, "16:")) {
  1107. if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))
  1108. != S2K_RFC2440_SPECIFIER_LEN + DIGEST_LEN
  1109. || strlen(hashed+3) != (S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN)*2) {
  1110. goto err;
  1111. }
  1112. } else {
  1113. if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
  1114. != S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN) {
  1115. goto err;
  1116. }
  1117. }
  1118. smartlist_add(sl,
  1119. tor_memdup(decoded, S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN));
  1120. }
  1121. return sl;
  1122. err:
  1123. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  1124. smartlist_free(sl);
  1125. return NULL;
  1126. }
  1127. /** Called when we get an AUTHENTICATE message. Check whether the
  1128. * authentication is valid, and if so, update the connection's state to
  1129. * OPEN. Reply with DONE or ERROR.
  1130. */
  1131. static int
  1132. handle_control_authenticate(control_connection_t *conn, uint32_t len,
  1133. const char *body)
  1134. {
  1135. int used_quoted_string = 0;
  1136. const or_options_t *options = get_options();
  1137. const char *errstr = "Unknown error";
  1138. char *password;
  1139. size_t password_len;
  1140. const char *cp;
  1141. int i;
  1142. int bad_cookie=0, bad_password=0;
  1143. smartlist_t *sl = NULL;
  1144. if (!len) {
  1145. password = tor_strdup("");
  1146. password_len = 0;
  1147. } else if (TOR_ISXDIGIT(body[0])) {
  1148. cp = body;
  1149. while (TOR_ISXDIGIT(*cp))
  1150. ++cp;
  1151. i = (int)(cp - body);
  1152. tor_assert(i>0);
  1153. password_len = i/2;
  1154. password = tor_malloc(password_len + 1);
  1155. if (base16_decode(password, password_len+1, body, i)
  1156. != (int) password_len) {
  1157. connection_write_str_to_buf(
  1158. "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
  1159. "password? If so, the standard requires that you put it in "
  1160. "double quotes.\r\n", conn);
  1161. connection_mark_for_close(TO_CONN(conn));
  1162. tor_free(password);
  1163. return 0;
  1164. }
  1165. } else {
  1166. if (!decode_escaped_string(body, len, &password, &password_len)) {
  1167. connection_write_str_to_buf("551 Invalid quoted string. You need "
  1168. "to put the password in double quotes.\r\n", conn);
  1169. connection_mark_for_close(TO_CONN(conn));
  1170. return 0;
  1171. }
  1172. used_quoted_string = 1;
  1173. }
  1174. if (conn->safecookie_client_hash != NULL) {
  1175. /* The controller has chosen safe cookie authentication; the only
  1176. * acceptable authentication value is the controller-to-server
  1177. * response. */
  1178. tor_assert(authentication_cookie_is_set);
  1179. if (password_len != DIGEST256_LEN) {
  1180. log_warn(LD_CONTROL,
  1181. "Got safe cookie authentication response with wrong length "
  1182. "(%d)", (int)password_len);
  1183. errstr = "Wrong length for safe cookie response.";
  1184. goto err;
  1185. }
  1186. if (tor_memneq(conn->safecookie_client_hash, password, DIGEST256_LEN)) {
  1187. log_warn(LD_CONTROL,
  1188. "Got incorrect safe cookie authentication response");
  1189. errstr = "Safe cookie response did not match expected value.";
  1190. goto err;
  1191. }
  1192. tor_free(conn->safecookie_client_hash);
  1193. goto ok;
  1194. }
  1195. if (!options->CookieAuthentication && !options->HashedControlPassword &&
  1196. !options->HashedControlSessionPassword) {
  1197. /* if Tor doesn't demand any stronger authentication, then
  1198. * the controller can get in with anything. */
  1199. goto ok;
  1200. }
  1201. if (options->CookieAuthentication) {
  1202. int also_password = options->HashedControlPassword != NULL ||
  1203. options->HashedControlSessionPassword != NULL;
  1204. if (password_len != AUTHENTICATION_COOKIE_LEN) {
  1205. if (!also_password) {
  1206. log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
  1207. "(%d)", (int)password_len);
  1208. errstr = "Wrong length on authentication cookie.";
  1209. goto err;
  1210. }
  1211. bad_cookie = 1;
  1212. } else if (tor_memneq(authentication_cookie, password, password_len)) {
  1213. if (!also_password) {
  1214. log_warn(LD_CONTROL, "Got mismatched authentication cookie");
  1215. errstr = "Authentication cookie did not match expected value.";
  1216. goto err;
  1217. }
  1218. bad_cookie = 1;
  1219. } else {
  1220. goto ok;
  1221. }
  1222. }
  1223. if (options->HashedControlPassword ||
  1224. options->HashedControlSessionPassword) {
  1225. int bad = 0;
  1226. smartlist_t *sl_tmp;
  1227. char received[DIGEST_LEN];
  1228. int also_cookie = options->CookieAuthentication;
  1229. sl = smartlist_new();
  1230. if (options->HashedControlPassword) {
  1231. sl_tmp = decode_hashed_passwords(options->HashedControlPassword);
  1232. if (!sl_tmp)
  1233. bad = 1;
  1234. else {
  1235. smartlist_add_all(sl, sl_tmp);
  1236. smartlist_free(sl_tmp);
  1237. }
  1238. }
  1239. if (options->HashedControlSessionPassword) {
  1240. sl_tmp = decode_hashed_passwords(options->HashedControlSessionPassword);
  1241. if (!sl_tmp)
  1242. bad = 1;
  1243. else {
  1244. smartlist_add_all(sl, sl_tmp);
  1245. smartlist_free(sl_tmp);
  1246. }
  1247. }
  1248. if (bad) {
  1249. if (!also_cookie) {
  1250. log_warn(LD_BUG,
  1251. "Couldn't decode HashedControlPassword: invalid base16");
  1252. errstr="Couldn't decode HashedControlPassword value in configuration.";
  1253. goto err;
  1254. }
  1255. bad_password = 1;
  1256. SMARTLIST_FOREACH(sl, char *, str, tor_free(str));
  1257. smartlist_free(sl);
  1258. sl = NULL;
  1259. } else {
  1260. SMARTLIST_FOREACH(sl, char *, expected,
  1261. {
  1262. secret_to_key_rfc2440(received,DIGEST_LEN,
  1263. password,password_len,expected);
  1264. if (tor_memeq(expected + S2K_RFC2440_SPECIFIER_LEN,
  1265. received, DIGEST_LEN))
  1266. goto ok;
  1267. });
  1268. SMARTLIST_FOREACH(sl, char *, str, tor_free(str));
  1269. smartlist_free(sl);
  1270. sl = NULL;
  1271. if (used_quoted_string)
  1272. errstr = "Password did not match HashedControlPassword value from "
  1273. "configuration";
  1274. else
  1275. errstr = "Password did not match HashedControlPassword value from "
  1276. "configuration. Maybe you tried a plain text password? "
  1277. "If so, the standard requires that you put it in double quotes.";
  1278. bad_password = 1;
  1279. if (!also_cookie)
  1280. goto err;
  1281. }
  1282. }
  1283. /** We only get here if both kinds of authentication failed. */
  1284. tor_assert(bad_password && bad_cookie);
  1285. log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
  1286. errstr = "Password did not match HashedControlPassword *or* authentication "
  1287. "cookie.";
  1288. err:
  1289. tor_free(password);
  1290. connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n", errstr);
  1291. connection_mark_for_close(TO_CONN(conn));
  1292. if (sl) { /* clean up */
  1293. SMARTLIST_FOREACH(sl, char *, str, tor_free(str));
  1294. smartlist_free(sl);
  1295. }
  1296. return 0;
  1297. ok:
  1298. log_info(LD_CONTROL, "Authenticated control connection ("TOR_SOCKET_T_FORMAT
  1299. ")", conn->base_.s);
  1300. send_control_done(conn);
  1301. conn->base_.state = CONTROL_CONN_STATE_OPEN;
  1302. tor_free(password);
  1303. if (sl) { /* clean up */
  1304. SMARTLIST_FOREACH(sl, char *, str, tor_free(str));
  1305. smartlist_free(sl);
  1306. }
  1307. return 0;
  1308. }
  1309. /** Called when we get a SAVECONF command. Try to flush the current options to
  1310. * disk, and report success or failure. */
  1311. static int
  1312. handle_control_saveconf(control_connection_t *conn, uint32_t len,
  1313. const char *body)
  1314. {
  1315. (void) len;
  1316. (void) body;
  1317. if (options_save_current()<0) {
  1318. connection_write_str_to_buf(
  1319. "551 Unable to write configuration to disk.\r\n", conn);
  1320. } else {
  1321. send_control_done(conn);
  1322. }
  1323. return 0;
  1324. }
  1325. struct signal_t {
  1326. int sig;
  1327. const char *signal_name;
  1328. };
  1329. static const struct signal_t signal_table[] = {
  1330. { SIGHUP, "RELOAD" },
  1331. { SIGHUP, "HUP" },
  1332. { SIGINT, "SHUTDOWN" },
  1333. { SIGUSR1, "DUMP" },
  1334. { SIGUSR1, "USR1" },
  1335. { SIGUSR2, "DEBUG" },
  1336. { SIGUSR2, "USR2" },
  1337. { SIGTERM, "HALT" },
  1338. { SIGTERM, "TERM" },
  1339. { SIGTERM, "INT" },
  1340. { SIGNEWNYM, "NEWNYM" },
  1341. { SIGCLEARDNSCACHE, "CLEARDNSCACHE"},
  1342. { SIGHEARTBEAT, "HEARTBEAT"},
  1343. { 0, NULL },
  1344. };
  1345. /** Called when we get a SIGNAL command. React to the provided signal, and
  1346. * report success or failure. (If the signal results in a shutdown, success
  1347. * may not be reported.) */
  1348. static int
  1349. handle_control_signal(control_connection_t *conn, uint32_t len,
  1350. const char *body)
  1351. {
  1352. int sig = -1;
  1353. int i;
  1354. int n = 0;
  1355. char *s;
  1356. (void) len;
  1357. while (body[n] && ! TOR_ISSPACE(body[n]))
  1358. ++n;
  1359. s = tor_strndup(body, n);
  1360. for (i = 0; signal_table[i].signal_name != NULL; ++i) {
  1361. if (!strcasecmp(s, signal_table[i].signal_name)) {
  1362. sig = signal_table[i].sig;
  1363. break;
  1364. }
  1365. }
  1366. if (sig < 0)
  1367. connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
  1368. s);
  1369. tor_free(s);
  1370. if (sig < 0)
  1371. return 0;
  1372. send_control_done(conn);
  1373. /* Flush the "done" first if the signal might make us shut down. */
  1374. if (sig == SIGTERM || sig == SIGINT)
  1375. connection_flush(TO_CONN(conn));
  1376. activate_signal(sig);
  1377. return 0;
  1378. }
  1379. /** Called when we get a TAKEOWNERSHIP command. Mark this connection
  1380. * as an owning connection, so that we will exit if the connection
  1381. * closes. */
  1382. static int
  1383. handle_control_takeownership(control_connection_t *conn, uint32_t len,
  1384. const char *body)
  1385. {
  1386. (void)len;
  1387. (void)body;
  1388. conn->is_owning_control_connection = 1;
  1389. log_info(LD_CONTROL, "Control connection %d has taken ownership of this "
  1390. "Tor instance.",
  1391. (int)(conn->base_.s));
  1392. send_control_done(conn);
  1393. return 0;
  1394. }
  1395. /** Return true iff <b>addr</b> is unusable as a mapaddress target because of
  1396. * containing funny characters. */
  1397. static int
  1398. address_is_invalid_mapaddress_target(const char *addr)
  1399. {
  1400. if (!strcmpstart(addr, "*."))
  1401. return address_is_invalid_destination(addr+2, 1);
  1402. else
  1403. return address_is_invalid_destination(addr, 1);
  1404. }
  1405. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  1406. * and report success or failure. */
  1407. static int
  1408. handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  1409. const char *body)
  1410. {
  1411. smartlist_t *elts;
  1412. smartlist_t *lines;
  1413. smartlist_t *reply;
  1414. char *r;
  1415. size_t sz;
  1416. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  1417. lines = smartlist_new();
  1418. elts = smartlist_new();
  1419. reply = smartlist_new();
  1420. smartlist_split_string(lines, body, " ",
  1421. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1422. SMARTLIST_FOREACH_BEGIN(lines, char *, line) {
  1423. tor_strlower(line);
  1424. smartlist_split_string(elts, line, "=", 0, 2);
  1425. if (smartlist_len(elts) == 2) {
  1426. const char *from = smartlist_get(elts,0);
  1427. const char *to = smartlist_get(elts,1);
  1428. if (address_is_invalid_mapaddress_target(to)) {
  1429. smartlist_add_asprintf(reply,
  1430. "512-syntax error: invalid address '%s'", to);
  1431. log_warn(LD_CONTROL,
  1432. "Skipping invalid argument '%s' in MapAddress msg", to);
  1433. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0") ||
  1434. !strcmp(from, "::")) {
  1435. const char type =
  1436. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME :
  1437. (!strcmp(from, "0.0.0.0") ? RESOLVED_TYPE_IPV4 : RESOLVED_TYPE_IPV6);
  1438. const char *address = addressmap_register_virtual_address(
  1439. type, tor_strdup(to));
  1440. if (!address) {
  1441. smartlist_add_asprintf(reply,
  1442. "451-resource exhausted: skipping '%s'", line);
  1443. log_warn(LD_CONTROL,
  1444. "Unable to allocate address for '%s' in MapAddress msg",
  1445. safe_str_client(line));
  1446. } else {
  1447. smartlist_add_asprintf(reply, "250-%s=%s", address, to);
  1448. }
  1449. } else {
  1450. const char *msg;
  1451. if (addressmap_register_auto(from, to, 1,
  1452. ADDRMAPSRC_CONTROLLER, &msg) < 0) {
  1453. smartlist_add_asprintf(reply,
  1454. "512-syntax error: invalid address mapping "
  1455. " '%s': %s", line, msg);
  1456. log_warn(LD_CONTROL,
  1457. "Skipping invalid argument '%s' in MapAddress msg: %s",
  1458. line, msg);
  1459. } else {
  1460. smartlist_add_asprintf(reply, "250-%s", line);
  1461. }
  1462. }
  1463. } else {
  1464. smartlist_add_asprintf(reply, "512-syntax error: mapping '%s' is "
  1465. "not of expected form 'foo=bar'.", line);
  1466. log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
  1467. "number of items.",
  1468. safe_str_client(line));
  1469. }
  1470. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1471. smartlist_clear(elts);
  1472. } SMARTLIST_FOREACH_END(line);
  1473. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1474. smartlist_free(lines);
  1475. smartlist_free(elts);
  1476. if (smartlist_len(reply)) {
  1477. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1478. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1479. connection_write_to_buf(r, sz, TO_CONN(conn));
  1480. tor_free(r);
  1481. } else {
  1482. const char *response =
  1483. "512 syntax error: not enough arguments to mapaddress.\r\n";
  1484. connection_write_to_buf(response, strlen(response), TO_CONN(conn));
  1485. }
  1486. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1487. smartlist_free(reply);
  1488. return 0;
  1489. }
  1490. /** Implementation helper for GETINFO: knows the answers for various
  1491. * trivial-to-implement questions. */
  1492. static int
  1493. getinfo_helper_misc(control_connection_t *conn, const char *question,
  1494. char **answer, const char **errmsg)
  1495. {
  1496. (void) conn;
  1497. if (!strcmp(question, "version")) {
  1498. *answer = tor_strdup(get_version());
  1499. } else if (!strcmp(question, "bw-event-cache")) {
  1500. *answer = get_bw_samples();
  1501. } else if (!strcmp(question, "config-file")) {
  1502. const char *a = get_torrc_fname(0);
  1503. if (a)
  1504. *answer = tor_strdup(a);
  1505. } else if (!strcmp(question, "config-defaults-file")) {
  1506. const char *a = get_torrc_fname(1);
  1507. if (a)
  1508. *answer = tor_strdup(a);
  1509. } else if (!strcmp(question, "config-text")) {
  1510. *answer = options_dump(get_options(), OPTIONS_DUMP_MINIMAL);
  1511. } else if (!strcmp(question, "info/names")) {
  1512. *answer = list_getinfo_options();
  1513. } else if (!strcmp(question, "dormant")) {
  1514. int dormant = rep_hist_circbuilding_dormant(time(NULL));
  1515. *answer = tor_strdup(dormant ? "1" : "0");
  1516. } else if (!strcmp(question, "events/names")) {
  1517. int i;
  1518. smartlist_t *event_names = smartlist_new();
  1519. for (i = 0; control_event_table[i].event_name != NULL; ++i) {
  1520. smartlist_add(event_names, (char *)control_event_table[i].event_name);
  1521. }
  1522. *answer = smartlist_join_strings(event_names, " ", 0, NULL);
  1523. smartlist_free(event_names);
  1524. } else if (!strcmp(question, "signal/names")) {
  1525. smartlist_t *signal_names = smartlist_new();
  1526. int j;
  1527. for (j = 0; signal_table[j].signal_name != NULL; ++j) {
  1528. smartlist_add(signal_names, (char*)signal_table[j].signal_name);
  1529. }
  1530. *answer = smartlist_join_strings(signal_names, " ", 0, NULL);
  1531. smartlist_free(signal_names);
  1532. } else if (!strcmp(question, "features/names")) {
  1533. *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
  1534. } else if (!strcmp(question, "address")) {
  1535. uint32_t addr;
  1536. if (router_pick_published_address(get_options(), &addr, 0) < 0) {
  1537. *errmsg = "Address unknown";
  1538. return -1;
  1539. }
  1540. *answer = tor_dup_ip(addr);
  1541. } else if (!strcmp(question, "traffic/read")) {
  1542. tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_read()));
  1543. } else if (!strcmp(question, "traffic/written")) {
  1544. tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_written()));
  1545. } else if (!strcmp(question, "process/pid")) {
  1546. int myPid = -1;
  1547. #ifdef _WIN32
  1548. myPid = _getpid();
  1549. #else
  1550. myPid = getpid();
  1551. #endif
  1552. tor_asprintf(answer, "%d", myPid);
  1553. } else if (!strcmp(question, "process/uid")) {
  1554. #ifdef _WIN32
  1555. *answer = tor_strdup("-1");
  1556. #else
  1557. int myUid = geteuid();
  1558. tor_asprintf(answer, "%d", myUid);
  1559. #endif
  1560. } else if (!strcmp(question, "process/user")) {
  1561. #ifdef _WIN32
  1562. *answer = tor_strdup("");
  1563. #else
  1564. int myUid = geteuid();
  1565. const struct passwd *myPwEntry = tor_getpwuid(myUid);
  1566. if (myPwEntry) {
  1567. *answer = tor_strdup(myPwEntry->pw_name);
  1568. } else {
  1569. *answer = tor_strdup("");
  1570. }
  1571. #endif
  1572. } else if (!strcmp(question, "process/descriptor-limit")) {
  1573. int max_fds = get_max_sockets();
  1574. tor_asprintf(answer, "%d", max_fds);
  1575. } else if (!strcmp(question, "limits/max-mem-in-queues")) {
  1576. tor_asprintf(answer, U64_FORMAT,
  1577. U64_PRINTF_ARG(get_options()->MaxMemInQueues));
  1578. } else if (!strcmp(question, "fingerprint")) {
  1579. crypto_pk_t *server_key;
  1580. if (!server_mode(get_options())) {
  1581. *errmsg = "Not running in server mode";
  1582. return -1;
  1583. }
  1584. server_key = get_server_identity_key();
  1585. *answer = tor_malloc(HEX_DIGEST_LEN+1);
  1586. crypto_pk_get_fingerprint(server_key, *answer, 0);
  1587. }
  1588. return 0;
  1589. }
  1590. /** Awful hack: return a newly allocated string based on a routerinfo and
  1591. * (possibly) an extrainfo, sticking the read-history and write-history from
  1592. * <b>ei</b> into the resulting string. The thing you get back won't
  1593. * necessarily have a valid signature.
  1594. *
  1595. * New code should never use this; it's for backward compatibility.
  1596. *
  1597. * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
  1598. * not be NUL-terminated. */
  1599. static char *
  1600. munge_extrainfo_into_routerinfo(const char *ri_body,
  1601. const signed_descriptor_t *ri,
  1602. const signed_descriptor_t *ei)
  1603. {
  1604. char *out = NULL, *outp;
  1605. int i;
  1606. const char *router_sig;
  1607. const char *ei_body = signed_descriptor_get_body(ei);
  1608. size_t ri_len = ri->signed_descriptor_len;
  1609. size_t ei_len = ei->signed_descriptor_len;
  1610. if (!ei_body)
  1611. goto bail;
  1612. outp = out = tor_malloc(ri_len+ei_len+1);
  1613. if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
  1614. goto bail;
  1615. ++router_sig;
  1616. memcpy(out, ri_body, router_sig-ri_body);
  1617. outp += router_sig-ri_body;
  1618. for (i=0; i < 2; ++i) {
  1619. const char *kwd = i ? "\nwrite-history " : "\nread-history ";
  1620. const char *cp, *eol;
  1621. if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
  1622. continue;
  1623. ++cp;
  1624. if (!(eol = memchr(cp, '\n', ei_len - (cp-ei_body))))
  1625. continue;
  1626. memcpy(outp, cp, eol-cp+1);
  1627. outp += eol-cp+1;
  1628. }
  1629. memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
  1630. *outp++ = '\0';
  1631. tor_assert(outp-out < (int)(ri_len+ei_len+1));
  1632. return out;
  1633. bail:
  1634. tor_free(out);
  1635. return tor_strndup(ri_body, ri->signed_descriptor_len);
  1636. }
  1637. /** Implementation helper for GETINFO: answers requests for information about
  1638. * which ports are bound. */
  1639. static int
  1640. getinfo_helper_listeners(control_connection_t *control_conn,
  1641. const char *question,
  1642. char **answer, const char **errmsg)
  1643. {
  1644. int type;
  1645. smartlist_t *res;
  1646. (void)control_conn;
  1647. (void)errmsg;
  1648. if (!strcmp(question, "net/listeners/or"))
  1649. type = CONN_TYPE_OR_LISTENER;
  1650. else if (!strcmp(question, "net/listeners/dir"))
  1651. type = CONN_TYPE_DIR_LISTENER;
  1652. else if (!strcmp(question, "net/listeners/socks"))
  1653. type = CONN_TYPE_AP_LISTENER;
  1654. else if (!strcmp(question, "net/listeners/trans"))
  1655. type = CONN_TYPE_AP_TRANS_LISTENER;
  1656. else if (!strcmp(question, "net/listeners/natd"))
  1657. type = CONN_TYPE_AP_NATD_LISTENER;
  1658. else if (!strcmp(question, "net/listeners/dns"))
  1659. type = CONN_TYPE_AP_DNS_LISTENER;
  1660. else if (!strcmp(question, "net/listeners/control"))
  1661. type = CONN_TYPE_CONTROL_LISTENER;
  1662. else
  1663. return 0; /* unknown key */
  1664. res = smartlist_new();
  1665. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  1666. struct sockaddr_storage ss;
  1667. socklen_t ss_len = sizeof(ss);
  1668. if (conn->type != type || conn->marked_for_close || !SOCKET_OK(conn->s))
  1669. continue;
  1670. if (getsockname(conn->s, (struct sockaddr *)&ss, &ss_len) < 0) {
  1671. smartlist_add_asprintf(res, "%s:%d", conn->address, (int)conn->port);
  1672. } else {
  1673. char *tmp = tor_sockaddr_to_str((struct sockaddr *)&ss);
  1674. smartlist_add(res, esc_for_log(tmp));
  1675. tor_free(tmp);
  1676. }
  1677. } SMARTLIST_FOREACH_END(conn);
  1678. *answer = smartlist_join_strings(res, " ", 0, NULL);
  1679. SMARTLIST_FOREACH(res, char *, cp, tor_free(cp));
  1680. smartlist_free(res);
  1681. return 0;
  1682. }
  1683. /** Implementation helper for GETINFO: knows the answers for questions about
  1684. * directory information. */
  1685. STATIC int
  1686. getinfo_helper_dir(control_connection_t *control_conn,
  1687. const char *question, char **answer,
  1688. const char **errmsg)
  1689. {
  1690. (void) control_conn;
  1691. if (!strcmpstart(question, "desc/id/")) {
  1692. const routerinfo_t *ri = NULL;
  1693. const node_t *node = node_get_by_hex_id(question+strlen("desc/id/"));
  1694. if (node)
  1695. ri = node->ri;
  1696. if (ri) {
  1697. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1698. if (body)
  1699. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1700. }
  1701. } else if (!strcmpstart(question, "desc/name/")) {
  1702. const routerinfo_t *ri = NULL;
  1703. /* XXX Setting 'warn_if_unnamed' here is a bit silly -- the
  1704. * warning goes to the user, not to the controller. */
  1705. const node_t *node =
  1706. node_get_by_nickname(question+strlen("desc/name/"), 1);
  1707. if (node)
  1708. ri = node->ri;
  1709. if (ri) {
  1710. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1711. if (body)
  1712. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1713. }
  1714. } else if (!strcmp(question, "desc/all-recent")) {
  1715. routerlist_t *routerlist = router_get_routerlist();
  1716. smartlist_t *sl = smartlist_new();
  1717. if (routerlist && routerlist->routers) {
  1718. SMARTLIST_FOREACH(routerlist->routers, const routerinfo_t *, ri,
  1719. {
  1720. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1721. if (body)
  1722. smartlist_add(sl,
  1723. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1724. });
  1725. }
  1726. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1727. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1728. smartlist_free(sl);
  1729. } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
  1730. /* XXXX Remove this once Torstat asks for extrainfos. */
  1731. routerlist_t *routerlist = router_get_routerlist();
  1732. smartlist_t *sl = smartlist_new();
  1733. if (routerlist && routerlist->routers) {
  1734. SMARTLIST_FOREACH_BEGIN(routerlist->routers, const routerinfo_t *, ri) {
  1735. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1736. signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
  1737. ri->cache_info.extra_info_digest);
  1738. if (ei && body) {
  1739. smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
  1740. &ri->cache_info, ei));
  1741. } else if (body) {
  1742. smartlist_add(sl,
  1743. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1744. }
  1745. } SMARTLIST_FOREACH_END(ri);
  1746. }
  1747. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1748. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1749. smartlist_free(sl);
  1750. } else if (!strcmpstart(question, "hs/client/desc/id/")) {
  1751. rend_cache_entry_t *e = NULL;
  1752. question += strlen("hs/client/desc/id/");
  1753. if (strlen(question) != REND_SERVICE_ID_LEN_BASE32) {
  1754. *errmsg = "Invalid address";
  1755. return -1;
  1756. }
  1757. if (!rend_cache_lookup_entry(question, -1, &e)) {
  1758. /* Descriptor found in cache */
  1759. *answer = tor_strdup(e->desc);
  1760. } else {
  1761. *errmsg = "Not found in cache";
  1762. return -1;
  1763. }
  1764. } else if (!strcmpstart(question, "hs/service/desc/id/")) {
  1765. rend_cache_entry_t *e = NULL;
  1766. question += strlen("hs/service/desc/id/");
  1767. if (strlen(question) != REND_SERVICE_ID_LEN_BASE32) {
  1768. *errmsg = "Invalid address";
  1769. return -1;
  1770. }
  1771. if (!rend_cache_lookup_v2_desc_as_service(question, &e)) {
  1772. /* Descriptor found in cache */
  1773. *answer = tor_strdup(e->desc);
  1774. } else {
  1775. *errmsg = "Not found in cache";
  1776. return -1;
  1777. }
  1778. } else if (!strcmpstart(question, "md/id/")) {
  1779. const node_t *node = node_get_by_hex_id(question+strlen("md/id/"));
  1780. const microdesc_t *md = NULL;
  1781. if (node) md = node->md;
  1782. if (md && md->body) {
  1783. *answer = tor_strndup(md->body, md->bodylen);
  1784. }
  1785. } else if (!strcmpstart(question, "md/name/")) {
  1786. /* XXX Setting 'warn_if_unnamed' here is a bit silly -- the
  1787. * warning goes to the user, not to the controller. */
  1788. const node_t *node = node_get_by_nickname(question+strlen("md/name/"), 1);
  1789. /* XXXX duplicated code */
  1790. const microdesc_t *md = NULL;
  1791. if (node) md = node->md;
  1792. if (md && md->body) {
  1793. *answer = tor_strndup(md->body, md->bodylen);
  1794. }
  1795. } else if (!strcmpstart(question, "desc-annotations/id/")) {
  1796. const routerinfo_t *ri = NULL;
  1797. const node_t *node =
  1798. node_get_by_hex_id(question+strlen("desc-annotations/id/"));
  1799. if (node)
  1800. ri = node->ri;
  1801. if (ri) {
  1802. const char *annotations =
  1803. signed_descriptor_get_annotations(&ri->cache_info);
  1804. if (annotations)
  1805. *answer = tor_strndup(annotations,
  1806. ri->cache_info.annotations_len);
  1807. }
  1808. } else if (!strcmpstart(question, "dir/server/")) {
  1809. size_t answer_len = 0;
  1810. char *url = NULL;
  1811. smartlist_t *descs = smartlist_new();
  1812. const char *msg;
  1813. int res;
  1814. char *cp;
  1815. tor_asprintf(&url, "/tor/%s", question+4);
  1816. res = dirserv_get_routerdescs(descs, url, &msg);
  1817. if (res) {
  1818. log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
  1819. smartlist_free(descs);
  1820. tor_free(url);
  1821. *errmsg = msg;
  1822. return -1;
  1823. }
  1824. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1825. answer_len += sd->signed_descriptor_len);
  1826. cp = *answer = tor_malloc(answer_len+1);
  1827. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1828. {
  1829. memcpy(cp, signed_descriptor_get_body(sd),
  1830. sd->signed_descriptor_len);
  1831. cp += sd->signed_descriptor_len;
  1832. });
  1833. *cp = '\0';
  1834. tor_free(url);
  1835. smartlist_free(descs);
  1836. } else if (!strcmpstart(question, "dir/status/")) {
  1837. *answer = tor_strdup("");
  1838. } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
  1839. if (we_want_to_fetch_flavor(get_options(), FLAV_NS)) {
  1840. const cached_dir_t *consensus = dirserv_get_consensus("ns");
  1841. if (consensus)
  1842. *answer = tor_strdup(consensus->dir);
  1843. }
  1844. if (!*answer) { /* try loading it from disk */
  1845. char *filename = get_datadir_fname("cached-consensus");
  1846. *answer = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  1847. tor_free(filename);
  1848. if (!*answer) { /* generate an error */
  1849. *errmsg = "Could not open cached consensus. "
  1850. "Make sure FetchUselessDescriptors is set to 1.";
  1851. return -1;
  1852. }
  1853. }
  1854. } else if (!strcmp(question, "network-status")) { /* v1 */
  1855. static int network_status_warned = 0;
  1856. if (!network_status_warned) {
  1857. log_warn(LD_CONTROL, "GETINFO network-status is deprecated; it will "
  1858. "go away in a future version of Tor.");
  1859. network_status_warned = 1;
  1860. }
  1861. routerlist_t *routerlist = router_get_routerlist();
  1862. if (!routerlist || !routerlist->routers ||
  1863. list_server_status_v1(routerlist->routers, answer, 1) < 0) {
  1864. return -1;
  1865. }
  1866. } else if (!strcmpstart(question, "extra-info/digest/")) {
  1867. question += strlen("extra-info/digest/");
  1868. if (strlen(question) == HEX_DIGEST_LEN) {
  1869. char d[DIGEST_LEN];
  1870. signed_descriptor_t *sd = NULL;
  1871. if (base16_decode(d, sizeof(d), question, strlen(question))
  1872. == sizeof(d)) {
  1873. /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
  1874. * but I don't want to risk affecting other parts of the code,
  1875. * especially since the rules for using our own extrainfo (including
  1876. * when it might be freed) are different from those for using one
  1877. * we have downloaded. */
  1878. if (router_extrainfo_digest_is_me(d))
  1879. sd = &(router_get_my_extrainfo()->cache_info);
  1880. else
  1881. sd = extrainfo_get_by_descriptor_digest(d);
  1882. }
  1883. if (sd) {
  1884. const char *body = signed_descriptor_get_body(sd);
  1885. if (body)
  1886. *answer = tor_strndup(body, sd->signed_descriptor_len);
  1887. }
  1888. }
  1889. }
  1890. return 0;
  1891. }
  1892. /** Given a smartlist of 20-byte digests, return a newly allocated string
  1893. * containing each of those digests in order, formatted in HEX, and terminated
  1894. * with a newline. */
  1895. static char *
  1896. digest_list_to_string(const smartlist_t *sl)
  1897. {
  1898. int len;
  1899. char *result, *s;
  1900. /* Allow for newlines, and a \0 at the end */
  1901. len = smartlist_len(sl) * (HEX_DIGEST_LEN + 1) + 1;
  1902. result = tor_malloc_zero(len);
  1903. s = result;
  1904. SMARTLIST_FOREACH_BEGIN(sl, const char *, digest) {
  1905. base16_encode(s, HEX_DIGEST_LEN + 1, digest, DIGEST_LEN);
  1906. s[HEX_DIGEST_LEN] = '\n';
  1907. s += HEX_DIGEST_LEN + 1;
  1908. } SMARTLIST_FOREACH_END(digest);
  1909. *s = '\0';
  1910. return result;
  1911. }
  1912. /** Turn a download_status_t into a human-readable description in a newly
  1913. * allocated string. The format is specified in control-spec.txt, under
  1914. * the documentation for "GETINFO download/..." . */
  1915. static char *
  1916. download_status_to_string(const download_status_t *dl)
  1917. {
  1918. char *rv = NULL, *tmp;
  1919. char tbuf[ISO_TIME_LEN+1];
  1920. const char *schedule_str, *want_authority_str;
  1921. const char *increment_on_str, *backoff_str;
  1922. if (dl) {
  1923. /* Get some substrings of the eventual output ready */
  1924. format_iso_time(tbuf, dl->next_attempt_at);
  1925. switch (dl->schedule) {
  1926. case DL_SCHED_GENERIC:
  1927. schedule_str = "DL_SCHED_GENERIC";
  1928. break;
  1929. case DL_SCHED_CONSENSUS:
  1930. schedule_str = "DL_SCHED_CONSENSUS";
  1931. break;
  1932. case DL_SCHED_BRIDGE:
  1933. schedule_str = "DL_SCHED_BRIDGE";
  1934. break;
  1935. default:
  1936. schedule_str = "unknown";
  1937. break;
  1938. }
  1939. switch (dl->want_authority) {
  1940. case DL_WANT_ANY_DIRSERVER:
  1941. want_authority_str = "DL_WANT_ANY_DIRSERVER";
  1942. break;
  1943. case DL_WANT_AUTHORITY:
  1944. want_authority_str = "DL_WANT_AUTHORITY";
  1945. break;
  1946. default:
  1947. want_authority_str = "unknown";
  1948. break;
  1949. }
  1950. switch (dl->increment_on) {
  1951. case DL_SCHED_INCREMENT_FAILURE:
  1952. increment_on_str = "DL_SCHED_INCREMENT_FAILURE";
  1953. break;
  1954. case DL_SCHED_INCREMENT_ATTEMPT:
  1955. increment_on_str = "DL_SCHED_INCREMENT_ATTEMPT";
  1956. break;
  1957. default:
  1958. increment_on_str = "unknown";
  1959. break;
  1960. }
  1961. switch (dl->backoff) {
  1962. case DL_SCHED_DETERMINISTIC:
  1963. backoff_str = "DL_SCHED_DETERMINISTIC";
  1964. break;
  1965. case DL_SCHED_RANDOM_EXPONENTIAL:
  1966. backoff_str = "DL_SCHED_RANDOM_EXPONENTIAL";
  1967. break;
  1968. default:
  1969. backoff_str = "unknown";
  1970. break;
  1971. }
  1972. /* Now assemble them */
  1973. tor_asprintf(&tmp,
  1974. "next-attempt-at %s\n"
  1975. "n-download-failures %u\n"
  1976. "n-download-attempts %u\n"
  1977. "schedule %s\n"
  1978. "want-authority %s\n"
  1979. "increment-on %s\n"
  1980. "backoff %s\n",
  1981. tbuf,
  1982. dl->n_download_failures,
  1983. dl->n_download_attempts,
  1984. schedule_str,
  1985. want_authority_str,
  1986. increment_on_str,
  1987. backoff_str);
  1988. if (dl->backoff == DL_SCHED_RANDOM_EXPONENTIAL) {
  1989. /* Additional fields become relevant in random-exponential mode */
  1990. tor_asprintf(&rv,
  1991. "%s"
  1992. "last-backoff-position %u\n"
  1993. "last-delay-used %d\n",
  1994. tmp,
  1995. dl->last_backoff_position,
  1996. dl->last_delay_used);
  1997. tor_free(tmp);
  1998. } else {
  1999. /* That was it */
  2000. rv = tmp;
  2001. }
  2002. }
  2003. return rv;
  2004. }
  2005. /** Handle the consensus download cases for getinfo_helper_downloads() */
  2006. STATIC void
  2007. getinfo_helper_downloads_networkstatus(const char *flavor,
  2008. download_status_t **dl_to_emit,
  2009. const char **errmsg)
  2010. {
  2011. /*
  2012. * We get the one for the current bootstrapped status by default, or
  2013. * take an extra /bootstrap or /running suffix
  2014. */
  2015. if (strcmp(flavor, "ns") == 0) {
  2016. *dl_to_emit = networkstatus_get_dl_status_by_flavor(FLAV_NS);
  2017. } else if (strcmp(flavor, "ns/bootstrap") == 0) {
  2018. *dl_to_emit = networkstatus_get_dl_status_by_flavor_bootstrap(FLAV_NS);
  2019. } else if (strcmp(flavor, "ns/running") == 0 ) {
  2020. *dl_to_emit = networkstatus_get_dl_status_by_flavor_running(FLAV_NS);
  2021. } else if (strcmp(flavor, "microdesc") == 0) {
  2022. *dl_to_emit = networkstatus_get_dl_status_by_flavor(FLAV_MICRODESC);
  2023. } else if (strcmp(flavor, "microdesc/bootstrap") == 0) {
  2024. *dl_to_emit =
  2025. networkstatus_get_dl_status_by_flavor_bootstrap(FLAV_MICRODESC);
  2026. } else if (strcmp(flavor, "microdesc/running") == 0) {
  2027. *dl_to_emit =
  2028. networkstatus_get_dl_status_by_flavor_running(FLAV_MICRODESC);
  2029. } else {
  2030. *errmsg = "Unknown flavor";
  2031. }
  2032. }
  2033. /** Handle the cert download cases for getinfo_helper_downloads() */
  2034. STATIC void
  2035. getinfo_helper_downloads_cert(const char *fp_sk_req,
  2036. download_status_t **dl_to_emit,
  2037. smartlist_t **digest_list,
  2038. const char **errmsg)
  2039. {
  2040. const char *sk_req;
  2041. char id_digest[DIGEST_LEN];
  2042. char sk_digest[DIGEST_LEN];
  2043. /*
  2044. * We have to handle four cases; fp_sk_req is the request with
  2045. * a prefix of "downloads/cert/" snipped off.
  2046. *
  2047. * Case 1: fp_sk_req = "fps"
  2048. * - We should emit a digest_list with a list of all the identity
  2049. * fingerprints that can be queried for certificate download status;
  2050. * get it by calling list_authority_ids_with_downloads().
  2051. *
  2052. * Case 2: fp_sk_req = "fp/<fp>" for some fingerprint fp
  2053. * - We want the default certificate for this identity fingerprint's
  2054. * download status; this is the download we get from URLs starting
  2055. * in /fp/ on the directory server. We can get it with
  2056. * id_only_download_status_for_authority_id().
  2057. *
  2058. * Case 3: fp_sk_req = "fp/<fp>/sks" for some fingerprint fp
  2059. * - We want a list of all signing key digests for this identity
  2060. * fingerprint which can be queried for certificate download status.
  2061. * Get it with list_sk_digests_for_authority_id().
  2062. *
  2063. * Case 4: fp_sk_req = "fp/<fp>/<sk>" for some fingerprint fp and
  2064. * signing key digest sk
  2065. * - We want the download status for the certificate for this specific
  2066. * signing key and fingerprint. These correspond to the ones we get
  2067. * from URLs starting in /fp-sk/ on the directory server. Get it with
  2068. * list_sk_digests_for_authority_id().
  2069. */
  2070. if (strcmp(fp_sk_req, "fps") == 0) {
  2071. *digest_list = list_authority_ids_with_downloads();
  2072. if (!(*digest_list)) {
  2073. *errmsg = "Failed to get list of authority identity digests (!)";
  2074. }
  2075. } else if (!strcmpstart(fp_sk_req, "fp/")) {
  2076. fp_sk_req += strlen("fp/");
  2077. /* Okay, look for another / to tell the fp from fp-sk cases */
  2078. sk_req = strchr(fp_sk_req, '/');
  2079. if (sk_req) {
  2080. /* okay, split it here and try to parse <fp> */
  2081. if (base16_decode(id_digest, DIGEST_LEN,
  2082. fp_sk_req, sk_req - fp_sk_req) == DIGEST_LEN) {
  2083. /* Skip past the '/' */
  2084. ++sk_req;
  2085. if (strcmp(sk_req, "sks") == 0) {
  2086. /* We're asking for the list of signing key fingerprints */
  2087. *digest_list = list_sk_digests_for_authority_id(id_digest);
  2088. if (!(*digest_list)) {
  2089. *errmsg = "Failed to get list of signing key digests for this "
  2090. "authority identity digest";
  2091. }
  2092. } else {
  2093. /* We've got a signing key digest */
  2094. if (base16_decode(sk_digest, DIGEST_LEN,
  2095. sk_req, strlen(sk_req)) == DIGEST_LEN) {
  2096. *dl_to_emit =
  2097. download_status_for_authority_id_and_sk(id_digest, sk_digest);
  2098. if (!(*dl_to_emit)) {
  2099. *errmsg = "Failed to get download status for this identity/"
  2100. "signing key digest pair";
  2101. }
  2102. } else {
  2103. *errmsg = "That didn't look like a signing key digest";
  2104. }
  2105. }
  2106. } else {
  2107. *errmsg = "That didn't look like an identity digest";
  2108. }
  2109. } else {
  2110. /* We're either in downloads/certs/fp/<fp>, or we can't parse <fp> */
  2111. if (strlen(fp_sk_req) == HEX_DIGEST_LEN) {
  2112. if (base16_decode(id_digest, DIGEST_LEN,
  2113. fp_sk_req, strlen(fp_sk_req)) == DIGEST_LEN) {
  2114. *dl_to_emit = id_only_download_status_for_authority_id(id_digest);
  2115. if (!(*dl_to_emit)) {
  2116. *errmsg = "Failed to get download status for this authority "
  2117. "identity digest";
  2118. }
  2119. } else {
  2120. *errmsg = "That didn't look like a digest";
  2121. }
  2122. } else {
  2123. *errmsg = "That didn't look like a digest";
  2124. }
  2125. }
  2126. } else {
  2127. *errmsg = "Unknown certificate download status query";
  2128. }
  2129. }
  2130. /** Handle the routerdesc download cases for getinfo_helper_downloads() */
  2131. STATIC void
  2132. getinfo_helper_downloads_desc(const char *desc_req,
  2133. download_status_t **dl_to_emit,
  2134. smartlist_t **digest_list,
  2135. const char **errmsg)
  2136. {
  2137. char desc_digest[DIGEST_LEN];
  2138. /*
  2139. * Two cases to handle here:
  2140. *
  2141. * Case 1: desc_req = "descs"
  2142. * - Emit a list of all router descriptor digests, which we get by
  2143. * calling router_get_descriptor_digests(); this can return NULL
  2144. * if we have no current ns-flavor consensus.
  2145. *
  2146. * Case 2: desc_req = <fp>
  2147. * - Check on the specified fingerprint and emit its download_status_t
  2148. * using router_get_dl_status_by_descriptor_digest().
  2149. */
  2150. if (strcmp(desc_req, "descs") == 0) {
  2151. *digest_list = router_get_descriptor_digests();
  2152. if (!(*digest_list)) {
  2153. *errmsg = "We don't seem to have a networkstatus-flavored consensus";
  2154. }
  2155. /*
  2156. * Microdescs don't use the download_status_t mechanism, so we don't
  2157. * answer queries about their downloads here; see microdesc.c.
  2158. */
  2159. } else if (strlen(desc_req) == HEX_DIGEST_LEN) {
  2160. if (base16_decode(desc_digest, DIGEST_LEN,
  2161. desc_req, strlen(desc_req)) == DIGEST_LEN) {
  2162. /* Okay we got a digest-shaped thing; try asking for it */
  2163. *dl_to_emit = router_get_dl_status_by_descriptor_digest(desc_digest);
  2164. if (!(*dl_to_emit)) {
  2165. *errmsg = "No such descriptor digest found";
  2166. }
  2167. } else {
  2168. *errmsg = "That didn't look like a digest";
  2169. }
  2170. } else {
  2171. *errmsg = "Unknown router descriptor download status query";
  2172. }
  2173. }
  2174. /** Handle the bridge download cases for getinfo_helper_downloads() */
  2175. STATIC void
  2176. getinfo_helper_downloads_bridge(const char *bridge_req,
  2177. download_status_t **dl_to_emit,
  2178. smartlist_t **digest_list,
  2179. const char **errmsg)
  2180. {
  2181. char bridge_digest[DIGEST_LEN];
  2182. /*
  2183. * Two cases to handle here:
  2184. *
  2185. * Case 1: bridge_req = "bridges"
  2186. * - Emit a list of all bridge identity digests, which we get by
  2187. * calling list_bridge_identities(); this can return NULL if we are
  2188. * not using bridges.
  2189. *
  2190. * Case 2: bridge_req = <fp>
  2191. * - Check on the specified fingerprint and emit its download_status_t
  2192. * using get_bridge_dl_status_by_id().
  2193. */
  2194. if (strcmp(bridge_req, "bridges") == 0) {
  2195. *digest_list = list_bridge_identities();
  2196. if (!(*digest_list)) {
  2197. *errmsg = "We don't seem to be using bridges";
  2198. }
  2199. } else if (strlen(bridge_req) == HEX_DIGEST_LEN) {
  2200. if (base16_decode(bridge_digest, DIGEST_LEN,
  2201. bridge_req, strlen(bridge_req)) == DIGEST_LEN) {
  2202. /* Okay we got a digest-shaped thing; try asking for it */
  2203. *dl_to_emit = get_bridge_dl_status_by_id(bridge_digest);
  2204. if (!(*dl_to_emit)) {
  2205. *errmsg = "No such bridge identity digest found";
  2206. }
  2207. } else {
  2208. *errmsg = "That didn't look like a digest";
  2209. }
  2210. } else {
  2211. *errmsg = "Unknown bridge descriptor download status query";
  2212. }
  2213. }
  2214. /** Implementation helper for GETINFO: knows the answers for questions about
  2215. * download status information. */
  2216. STATIC int
  2217. getinfo_helper_downloads(control_connection_t *control_conn,
  2218. const char *question, char **answer,
  2219. const char **errmsg)
  2220. {
  2221. download_status_t *dl_to_emit = NULL;
  2222. smartlist_t *digest_list = NULL;
  2223. /* Assert args are sane */
  2224. tor_assert(control_conn != NULL);
  2225. tor_assert(question != NULL);
  2226. tor_assert(answer != NULL);
  2227. tor_assert(errmsg != NULL);
  2228. /* We check for this later to see if we should supply a default */
  2229. *errmsg = NULL;
  2230. /* Are we after networkstatus downloads? */
  2231. if (!strcmpstart(question, "downloads/networkstatus/")) {
  2232. getinfo_helper_downloads_networkstatus(
  2233. question + strlen("downloads/networkstatus/"),
  2234. &dl_to_emit, errmsg);
  2235. /* Certificates? */
  2236. } else if (!strcmpstart(question, "downloads/cert/")) {
  2237. getinfo_helper_downloads_cert(
  2238. question + strlen("downloads/cert/"),
  2239. &dl_to_emit, &digest_list, errmsg);
  2240. /* Router descriptors? */
  2241. } else if (!strcmpstart(question, "downloads/desc/")) {
  2242. getinfo_helper_downloads_desc(
  2243. question + strlen("downloads/desc/"),
  2244. &dl_to_emit, &digest_list, errmsg);
  2245. /* Bridge descriptors? */
  2246. } else if (!strcmpstart(question, "downloads/bridge/")) {
  2247. getinfo_helper_downloads_bridge(
  2248. question + strlen("downloads/bridge/"),
  2249. &dl_to_emit, &digest_list, errmsg);
  2250. } else {
  2251. *errmsg = "Unknown download status query";
  2252. }
  2253. if (dl_to_emit) {
  2254. *answer = download_status_to_string(dl_to_emit);
  2255. return 0;
  2256. } else if (digest_list) {
  2257. *answer = digest_list_to_string(digest_list);
  2258. SMARTLIST_FOREACH(digest_list, void *, s, tor_free(s));
  2259. smartlist_free(digest_list);
  2260. return 0;
  2261. } else {
  2262. if (!(*errmsg)) {
  2263. *errmsg = "Unknown error";
  2264. }
  2265. return -1;
  2266. }
  2267. }
  2268. /** Allocate and return a description of <b>circ</b>'s current status,
  2269. * including its path (if any). */
  2270. static char *
  2271. circuit_describe_status_for_controller(origin_circuit_t *circ)
  2272. {
  2273. char *rv;
  2274. smartlist_t *descparts = smartlist_new();
  2275. {
  2276. char *vpath = circuit_list_path_for_controller(circ);
  2277. if (*vpath) {
  2278. smartlist_add(descparts, vpath);
  2279. } else {
  2280. tor_free(vpath); /* empty path; don't put an extra space in the result */
  2281. }
  2282. }
  2283. {
  2284. cpath_build_state_t *build_state = circ->build_state;
  2285. smartlist_t *flaglist = smartlist_new();
  2286. char *flaglist_joined;
  2287. if (build_state->onehop_tunnel)
  2288. smartlist_add(flaglist, (void *)"ONEHOP_TUNNEL");
  2289. if (build_state->is_internal)
  2290. smartlist_add(flaglist, (void *)"IS_INTERNAL");
  2291. if (build_state->need_capacity)
  2292. smartlist_add(flaglist, (void *)"NEED_CAPACITY");
  2293. if (build_state->need_uptime)
  2294. smartlist_add(flaglist, (void *)"NEED_UPTIME");
  2295. /* Only emit a BUILD_FLAGS argument if it will have a non-empty value. */
  2296. if (smartlist_len(flaglist)) {
  2297. flaglist_joined = smartlist_join_strings(flaglist, ",", 0, NULL);
  2298. smartlist_add_asprintf(descparts, "BUILD_FLAGS=%s", flaglist_joined);
  2299. tor_free(flaglist_joined);
  2300. }
  2301. smartlist_free(flaglist);
  2302. }
  2303. smartlist_add_asprintf(descparts, "PURPOSE=%s",
  2304. circuit_purpose_to_controller_string(circ->base_.purpose));
  2305. {
  2306. const char *hs_state =
  2307. circuit_purpose_to_controller_hs_state_string(circ->base_.purpose);
  2308. if (hs_state != NULL) {
  2309. smartlist_add_asprintf(descparts, "HS_STATE=%s", hs_state);
  2310. }
  2311. }
  2312. if (circ->rend_data != NULL) {
  2313. smartlist_add_asprintf(descparts, "REND_QUERY=%s",
  2314. rend_data_get_address(circ->rend_data));
  2315. }
  2316. {
  2317. char tbuf[ISO_TIME_USEC_LEN+1];
  2318. format_iso_time_nospace_usec(tbuf, &circ->base_.timestamp_created);
  2319. smartlist_add_asprintf(descparts, "TIME_CREATED=%s", tbuf);
  2320. }
  2321. // Show username and/or password if available.
  2322. if (circ->socks_username_len > 0) {
  2323. char* socks_username_escaped = esc_for_log_len(circ->socks_username,
  2324. (size_t) circ->socks_username_len);
  2325. smartlist_add_asprintf(descparts, "SOCKS_USERNAME=%s",
  2326. socks_username_escaped);
  2327. tor_free(socks_username_escaped);
  2328. }
  2329. if (circ->socks_password_len > 0) {
  2330. char* socks_password_escaped = esc_for_log_len(circ->socks_password,
  2331. (size_t) circ->socks_password_len);
  2332. smartlist_add_asprintf(descparts, "SOCKS_PASSWORD=%s",
  2333. socks_password_escaped);
  2334. tor_free(socks_password_escaped);
  2335. }
  2336. rv = smartlist_join_strings(descparts, " ", 0, NULL);
  2337. SMARTLIST_FOREACH(descparts, char *, cp, tor_free(cp));
  2338. smartlist_free(descparts);
  2339. return rv;
  2340. }
  2341. /** Implementation helper for GETINFO: knows how to generate summaries of the
  2342. * current states of things we send events about. */
  2343. static int
  2344. getinfo_helper_events(control_connection_t *control_conn,
  2345. const char *question, char **answer,
  2346. const char **errmsg)
  2347. {
  2348. const or_options_t *options = get_options();
  2349. (void) control_conn;
  2350. if (!strcmp(question, "circuit-status")) {
  2351. smartlist_t *status = smartlist_new();
  2352. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ_) {
  2353. origin_circuit_t *circ;
  2354. char *circdesc;
  2355. const char *state;
  2356. if (! CIRCUIT_IS_ORIGIN(circ_) || circ_->marked_for_close)
  2357. continue;
  2358. circ = TO_ORIGIN_CIRCUIT(circ_);
  2359. if (circ->base_.state == CIRCUIT_STATE_OPEN)
  2360. state = "BUILT";
  2361. else if (circ->base_.state == CIRCUIT_STATE_GUARD_WAIT)
  2362. state = "GUARD_WAIT";
  2363. else if (circ->cpath)
  2364. state = "EXTENDED";
  2365. else
  2366. state = "LAUNCHED";
  2367. circdesc = circuit_describe_status_for_controller(circ);
  2368. smartlist_add_asprintf(status, "%lu %s%s%s",
  2369. (unsigned long)circ->global_identifier,
  2370. state, *circdesc ? " " : "", circdesc);
  2371. tor_free(circdesc);
  2372. }
  2373. SMARTLIST_FOREACH_END(circ_);
  2374. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  2375. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  2376. smartlist_free(status);
  2377. } else if (!strcmp(question, "stream-status")) {
  2378. smartlist_t *conns = get_connection_array();
  2379. smartlist_t *status = smartlist_new();
  2380. char buf[256];
  2381. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  2382. const char *state;
  2383. entry_connection_t *conn;
  2384. circuit_t *circ;
  2385. origin_circuit_t *origin_circ = NULL;
  2386. if (base_conn->type != CONN_TYPE_AP ||
  2387. base_conn->marked_for_close ||
  2388. base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
  2389. base_conn->state == AP_CONN_STATE_NATD_WAIT)
  2390. continue;
  2391. conn = TO_ENTRY_CONN(base_conn);
  2392. switch (base_conn->state)
  2393. {
  2394. case AP_CONN_STATE_CONTROLLER_WAIT:
  2395. case AP_CONN_STATE_CIRCUIT_WAIT:
  2396. if (conn->socks_request &&
  2397. SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  2398. state = "NEWRESOLVE";
  2399. else
  2400. state = "NEW";
  2401. break;
  2402. case AP_CONN_STATE_RENDDESC_WAIT:
  2403. case AP_CONN_STATE_CONNECT_WAIT:
  2404. state = "SENTCONNECT"; break;
  2405. case AP_CONN_STATE_RESOLVE_WAIT:
  2406. state = "SENTRESOLVE"; break;
  2407. case AP_CONN_STATE_OPEN:
  2408. state = "SUCCEEDED"; break;
  2409. default:
  2410. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  2411. base_conn->state);
  2412. continue;
  2413. }
  2414. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  2415. if (circ && CIRCUIT_IS_ORIGIN(circ))
  2416. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2417. write_stream_target_to_buf(conn, buf, sizeof(buf));
  2418. smartlist_add_asprintf(status, "%lu %s %lu %s",
  2419. (unsigned long) base_conn->global_identifier,state,
  2420. origin_circ?
  2421. (unsigned long)origin_circ->global_identifier : 0ul,
  2422. buf);
  2423. } SMARTLIST_FOREACH_END(base_conn);
  2424. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  2425. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  2426. smartlist_free(status);
  2427. } else if (!strcmp(question, "orconn-status")) {
  2428. smartlist_t *conns = get_connection_array();
  2429. smartlist_t *status = smartlist_new();
  2430. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  2431. const char *state;
  2432. char name[128];
  2433. or_connection_t *conn;
  2434. if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
  2435. continue;
  2436. conn = TO_OR_CONN(base_conn);
  2437. if (conn->base_.state == OR_CONN_STATE_OPEN)
  2438. state = "CONNECTED";
  2439. else if (conn->nickname)
  2440. state = "LAUNCHED";
  2441. else
  2442. state = "NEW";
  2443. orconn_target_get_name(name, sizeof(name), conn);
  2444. smartlist_add_asprintf(status, "%s %s", name, state);
  2445. } SMARTLIST_FOREACH_END(base_conn);
  2446. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  2447. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  2448. smartlist_free(status);
  2449. } else if (!strcmpstart(question, "address-mappings/")) {
  2450. time_t min_e, max_e;
  2451. smartlist_t *mappings;
  2452. question += strlen("address-mappings/");
  2453. if (!strcmp(question, "all")) {
  2454. min_e = 0; max_e = TIME_MAX;
  2455. } else if (!strcmp(question, "cache")) {
  2456. min_e = 2; max_e = TIME_MAX;
  2457. } else if (!strcmp(question, "config")) {
  2458. min_e = 0; max_e = 0;
  2459. } else if (!strcmp(question, "control")) {
  2460. min_e = 1; max_e = 1;
  2461. } else {
  2462. return 0;
  2463. }
  2464. mappings = smartlist_new();
  2465. addressmap_get_mappings(mappings, min_e, max_e, 1);
  2466. *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
  2467. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  2468. smartlist_free(mappings);
  2469. } else if (!strcmpstart(question, "status/")) {
  2470. /* Note that status/ is not a catch-all for events; there's only supposed
  2471. * to be a status GETINFO if there's a corresponding STATUS event. */
  2472. if (!strcmp(question, "status/circuit-established")) {
  2473. *answer = tor_strdup(have_completed_a_circuit() ? "1" : "0");
  2474. } else if (!strcmp(question, "status/enough-dir-info")) {
  2475. *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
  2476. } else if (!strcmp(question, "status/good-server-descriptor") ||
  2477. !strcmp(question, "status/accepted-server-descriptor")) {
  2478. /* They're equivalent for now, until we can figure out how to make
  2479. * good-server-descriptor be what we want. See comment in
  2480. * control-spec.txt. */
  2481. *answer = tor_strdup(directories_have_accepted_server_descriptor()
  2482. ? "1" : "0");
  2483. } else if (!strcmp(question, "status/reachability-succeeded/or")) {
  2484. *answer = tor_strdup(check_whether_orport_reachable(options) ?
  2485. "1" : "0");
  2486. } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
  2487. *answer = tor_strdup(check_whether_dirport_reachable(options) ?
  2488. "1" : "0");
  2489. } else if (!strcmp(question, "status/reachability-succeeded")) {
  2490. tor_asprintf(answer, "OR=%d DIR=%d",
  2491. check_whether_orport_reachable(options) ? 1 : 0,
  2492. check_whether_dirport_reachable(options) ? 1 : 0);
  2493. } else if (!strcmp(question, "status/bootstrap-phase")) {
  2494. *answer = tor_strdup(last_sent_bootstrap_message);
  2495. } else if (!strcmpstart(question, "status/version/")) {
  2496. int is_server = server_mode(options);
  2497. networkstatus_t *c = networkstatus_get_latest_consensus();
  2498. version_status_t status;
  2499. const char *recommended;
  2500. if (c) {
  2501. recommended = is_server ? c->server_versions : c->client_versions;
  2502. status = tor_version_is_obsolete(VERSION, recommended);
  2503. } else {
  2504. recommended = "?";
  2505. status = VS_UNKNOWN;
  2506. }
  2507. if (!strcmp(question, "status/version/recommended")) {
  2508. *answer = tor_strdup(recommended);
  2509. return 0;
  2510. }
  2511. if (!strcmp(question, "status/version/current")) {
  2512. switch (status)
  2513. {
  2514. case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
  2515. case VS_OLD: *answer = tor_strdup("obsolete"); break;
  2516. case VS_NEW: *answer = tor_strdup("new"); break;
  2517. case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
  2518. case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
  2519. case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
  2520. case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
  2521. default: tor_fragile_assert();
  2522. }
  2523. } else if (!strcmp(question, "status/version/num-versioning") ||
  2524. !strcmp(question, "status/version/num-concurring")) {
  2525. tor_asprintf(answer, "%d", get_n_authorities(V3_DIRINFO));
  2526. log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
  2527. "information", question);
  2528. }
  2529. } else if (!strcmp(question, "status/clients-seen")) {
  2530. char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
  2531. if (!bridge_stats) {
  2532. *errmsg = "No bridge-client stats available";
  2533. return -1;
  2534. }
  2535. *answer = bridge_stats;
  2536. } else if (!strcmp(question, "status/fresh-relay-descs")) {
  2537. if (!server_mode(options)) {
  2538. *errmsg = "Only relays have descriptors";
  2539. return -1;
  2540. }
  2541. routerinfo_t *r;
  2542. extrainfo_t *e;
  2543. if (router_build_fresh_descriptor(&r, &e) < 0) {
  2544. *errmsg = "Error generating descriptor";
  2545. return -1;
  2546. }
  2547. size_t size = r->cache_info.signed_descriptor_len + 1;
  2548. if (e) {
  2549. size += e->cache_info.signed_descriptor_len + 1;
  2550. }
  2551. tor_assert(r->cache_info.signed_descriptor_len);
  2552. char *descs = tor_malloc(size);
  2553. char *cp = descs;
  2554. memcpy(cp, signed_descriptor_get_body(&r->cache_info),
  2555. r->cache_info.signed_descriptor_len);
  2556. cp += r->cache_info.signed_descriptor_len - 1;
  2557. if (e) {
  2558. if (cp[0] == '\0') {
  2559. cp[0] = '\n';
  2560. } else if (cp[0] != '\n') {
  2561. cp[1] = '\n';
  2562. cp++;
  2563. }
  2564. memcpy(cp, signed_descriptor_get_body(&e->cache_info),
  2565. e->cache_info.signed_descriptor_len);
  2566. cp += e->cache_info.signed_descriptor_len - 1;
  2567. }
  2568. if (cp[0] == '\n') {
  2569. cp[0] = '\0';
  2570. } else if (cp[0] != '\0') {
  2571. cp[1] = '\0';
  2572. }
  2573. *answer = descs;
  2574. routerinfo_free(r);
  2575. extrainfo_free(e);
  2576. } else {
  2577. return 0;
  2578. }
  2579. }
  2580. return 0;
  2581. }
  2582. /** Implementation helper for GETINFO: knows how to enumerate hidden services
  2583. * created via the control port. */
  2584. STATIC int
  2585. getinfo_helper_onions(control_connection_t *control_conn,
  2586. const char *question, char **answer,
  2587. const char **errmsg)
  2588. {
  2589. smartlist_t *onion_list = NULL;
  2590. (void) errmsg; /* no errors from this method */
  2591. if (control_conn && !strcmp(question, "onions/current")) {
  2592. onion_list = control_conn->ephemeral_onion_services;
  2593. } else if (!strcmp(question, "onions/detached")) {
  2594. onion_list = detached_onion_services;
  2595. } else {
  2596. return 0;
  2597. }
  2598. if (!onion_list || smartlist_len(onion_list) == 0) {
  2599. if (answer) {
  2600. *answer = tor_strdup("");
  2601. }
  2602. } else {
  2603. if (answer) {
  2604. *answer = smartlist_join_strings(onion_list, "\r\n", 0, NULL);
  2605. }
  2606. }
  2607. return 0;
  2608. }
  2609. /** Implementation helper for GETINFO: answers queries about network
  2610. * liveness. */
  2611. static int
  2612. getinfo_helper_liveness(control_connection_t *control_conn,
  2613. const char *question, char **answer,
  2614. const char **errmsg)
  2615. {
  2616. (void)control_conn;
  2617. (void)errmsg;
  2618. if (strcmp(question, "network-liveness") == 0) {
  2619. if (get_cached_network_liveness()) {
  2620. *answer = tor_strdup("up");
  2621. } else {
  2622. *answer = tor_strdup("down");
  2623. }
  2624. }
  2625. return 0;
  2626. }
  2627. /** Implementation helper for GETINFO: answers queries about shared random
  2628. * value. */
  2629. static int
  2630. getinfo_helper_sr(control_connection_t *control_conn,
  2631. const char *question, char **answer,
  2632. const char **errmsg)
  2633. {
  2634. (void) control_conn;
  2635. (void) errmsg;
  2636. if (!strcmp(question, "sr/current")) {
  2637. *answer = sr_get_current_for_control();
  2638. } else if (!strcmp(question, "sr/previous")) {
  2639. *answer = sr_get_previous_for_control();
  2640. }
  2641. /* Else statement here is unrecognized key so do nothing. */
  2642. return 0;
  2643. }
  2644. /** Callback function for GETINFO: on a given control connection, try to
  2645. * answer the question <b>q</b> and store the newly-allocated answer in
  2646. * *<b>a</b>. If an internal error occurs, return -1 and optionally set
  2647. * *<b>error_out</b> to point to an error message to be delivered to the
  2648. * controller. On success, _or if the key is not recognized_, return 0. Do not
  2649. * set <b>a</b> if the key is not recognized.
  2650. */
  2651. typedef int (*getinfo_helper_t)(control_connection_t *,
  2652. const char *q, char **a,
  2653. const char **error_out);
  2654. /** A single item for the GETINFO question-to-answer-function table. */
  2655. typedef struct getinfo_item_t {
  2656. const char *varname; /**< The value (or prefix) of the question. */
  2657. getinfo_helper_t fn; /**< The function that knows the answer: NULL if
  2658. * this entry is documentation-only. */
  2659. const char *desc; /**< Description of the variable. */
  2660. int is_prefix; /** Must varname match exactly, or must it be a prefix? */
  2661. } getinfo_item_t;
  2662. #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
  2663. #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
  2664. #define DOC(name, desc) { name, NULL, desc, 0 }
  2665. /** Table mapping questions accepted by GETINFO to the functions that know how
  2666. * to answer them. */
  2667. static const getinfo_item_t getinfo_items[] = {
  2668. ITEM("version", misc, "The current version of Tor."),
  2669. ITEM("bw-event-cache", misc, "Cached BW events for a short interval."),
  2670. ITEM("config-file", misc, "Current location of the \"torrc\" file."),
  2671. ITEM("config-defaults-file", misc, "Current location of the defaults file."),
  2672. ITEM("config-text", misc,
  2673. "Return the string that would be written by a saveconf command."),
  2674. ITEM("accounting/bytes", accounting,
  2675. "Number of bytes read/written so far in the accounting interval."),
  2676. ITEM("accounting/bytes-left", accounting,
  2677. "Number of bytes left to write/read so far in the accounting interval."),
  2678. ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
  2679. ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
  2680. ITEM("accounting/interval-start", accounting,
  2681. "Time when the accounting period starts."),
  2682. ITEM("accounting/interval-end", accounting,
  2683. "Time when the accounting period ends."),
  2684. ITEM("accounting/interval-wake", accounting,
  2685. "Time to wake up in this accounting period."),
  2686. ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
  2687. ITEM("entry-guards", entry_guards,
  2688. "Which nodes are we using as entry guards?"),
  2689. ITEM("fingerprint", misc, NULL),
  2690. PREFIX("config/", config, "Current configuration values."),
  2691. DOC("config/names",
  2692. "List of configuration options, types, and documentation."),
  2693. DOC("config/defaults",
  2694. "List of default values for configuration options. "
  2695. "See also config/names"),
  2696. PREFIX("downloads/networkstatus/", downloads,
  2697. "Download statuses for networkstatus objects"),
  2698. DOC("downloads/networkstatus/ns",
  2699. "Download status for current-mode networkstatus download"),
  2700. DOC("downloads/networkstatus/ns/bootstrap",
  2701. "Download status for bootstrap-time networkstatus download"),
  2702. DOC("downloads/networkstatus/ns/running",
  2703. "Download status for run-time networkstatus download"),
  2704. DOC("downloads/networkstatus/microdesc",
  2705. "Download status for current-mode microdesc download"),
  2706. DOC("downloads/networkstatus/microdesc/bootstrap",
  2707. "Download status for bootstrap-time microdesc download"),
  2708. DOC("downloads/networkstatus/microdesc/running",
  2709. "Download status for run-time microdesc download"),
  2710. PREFIX("downloads/cert/", downloads,
  2711. "Download statuses for certificates, by id fingerprint and "
  2712. "signing key"),
  2713. DOC("downloads/cert/fps",
  2714. "List of authority fingerprints for which any download statuses "
  2715. "exist"),
  2716. DOC("downloads/cert/fp/<fp>",
  2717. "Download status for <fp> with the default signing key; corresponds "
  2718. "to /fp/ URLs on directory server."),
  2719. DOC("downloads/cert/fp/<fp>/sks",
  2720. "List of signing keys for which specific download statuses are "
  2721. "available for this id fingerprint"),
  2722. DOC("downloads/cert/fp/<fp>/<sk>",
  2723. "Download status for <fp> with signing key <sk>; corresponds "
  2724. "to /fp-sk/ URLs on directory server."),
  2725. PREFIX("downloads/desc/", downloads,
  2726. "Download statuses for router descriptors, by descriptor digest"),
  2727. DOC("downloads/desc/descs",
  2728. "Return a list of known router descriptor digests"),
  2729. DOC("downloads/desc/<desc>",
  2730. "Return a download status for a given descriptor digest"),
  2731. PREFIX("downloads/bridge/", downloads,
  2732. "Download statuses for bridge descriptors, by bridge identity "
  2733. "digest"),
  2734. DOC("downloads/bridge/bridges",
  2735. "Return a list of configured bridge identity digests with download "
  2736. "statuses"),
  2737. DOC("downloads/bridge/<desc>",
  2738. "Return a download status for a given bridge identity digest"),
  2739. ITEM("info/names", misc,
  2740. "List of GETINFO options, types, and documentation."),
  2741. ITEM("events/names", misc,
  2742. "Events that the controller can ask for with SETEVENTS."),
  2743. ITEM("signal/names", misc, "Signal names recognized by the SIGNAL command"),
  2744. ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
  2745. PREFIX("desc/id/", dir, "Router descriptors by ID."),
  2746. PREFIX("desc/name/", dir, "Router descriptors by nickname."),
  2747. ITEM("desc/all-recent", dir,
  2748. "All non-expired, non-superseded router descriptors."),
  2749. ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
  2750. PREFIX("md/id/", dir, "Microdescriptors by ID"),
  2751. PREFIX("md/name/", dir, "Microdescriptors by name"),
  2752. PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
  2753. PREFIX("hs/client/desc/id", dir,
  2754. "Hidden Service descriptor in client's cache by onion."),
  2755. PREFIX("hs/service/desc/id/", dir,
  2756. "Hidden Service descriptor in services's cache by onion."),
  2757. PREFIX("net/listeners/", listeners, "Bound addresses by type"),
  2758. ITEM("ns/all", networkstatus,
  2759. "Brief summary of router status (v2 directory format)"),
  2760. PREFIX("ns/id/", networkstatus,
  2761. "Brief summary of router status by ID (v2 directory format)."),
  2762. PREFIX("ns/name/", networkstatus,
  2763. "Brief summary of router status by nickname (v2 directory format)."),
  2764. PREFIX("ns/purpose/", networkstatus,
  2765. "Brief summary of router status by purpose (v2 directory format)."),
  2766. PREFIX("consensus/", networkstatus,
  2767. "Information about and from the ns consensus."),
  2768. ITEM("network-status", dir,
  2769. "Brief summary of router status (v1 directory format)"),
  2770. ITEM("network-liveness", liveness,
  2771. "Current opinion on whether the network is live"),
  2772. ITEM("circuit-status", events, "List of current circuits originating here."),
  2773. ITEM("stream-status", events,"List of current streams."),
  2774. ITEM("orconn-status", events, "A list of current OR connections."),
  2775. ITEM("dormant", misc,
  2776. "Is Tor dormant (not building circuits because it's idle)?"),
  2777. PREFIX("address-mappings/", events, NULL),
  2778. DOC("address-mappings/all", "Current address mappings."),
  2779. DOC("address-mappings/cache", "Current cached DNS replies."),
  2780. DOC("address-mappings/config",
  2781. "Current address mappings from configuration."),
  2782. DOC("address-mappings/control", "Current address mappings from controller."),
  2783. PREFIX("status/", events, NULL),
  2784. DOC("status/circuit-established",
  2785. "Whether we think client functionality is working."),
  2786. DOC("status/enough-dir-info",
  2787. "Whether we have enough up-to-date directory information to build "
  2788. "circuits."),
  2789. DOC("status/bootstrap-phase",
  2790. "The last bootstrap phase status event that Tor sent."),
  2791. DOC("status/clients-seen",
  2792. "Breakdown of client countries seen by a bridge."),
  2793. DOC("status/fresh-relay-descs",
  2794. "A fresh relay/ei descriptor pair for Tor's current state. Not stored."),
  2795. DOC("status/version/recommended", "List of currently recommended versions."),
  2796. DOC("status/version/current", "Status of the current version."),
  2797. DOC("status/version/num-versioning", "Number of versioning authorities."),
  2798. DOC("status/version/num-concurring",
  2799. "Number of versioning authorities agreeing on the status of the "
  2800. "current version"),
  2801. ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
  2802. ITEM("traffic/read", misc,"Bytes read since the process was started."),
  2803. ITEM("traffic/written", misc,
  2804. "Bytes written since the process was started."),
  2805. ITEM("process/pid", misc, "Process id belonging to the main tor process."),
  2806. ITEM("process/uid", misc, "User id running the tor process."),
  2807. ITEM("process/user", misc,
  2808. "Username under which the tor process is running."),
  2809. ITEM("process/descriptor-limit", misc, "File descriptor limit."),
  2810. ITEM("limits/max-mem-in-queues", misc, "Actual limit on memory in queues"),
  2811. PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
  2812. PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
  2813. PREFIX("dir/status/", dir,
  2814. "v2 networkstatus docs as retrieved from a DirPort."),
  2815. ITEM("dir/status-vote/current/consensus", dir,
  2816. "v3 Networkstatus consensus as retrieved from a DirPort."),
  2817. ITEM("exit-policy/default", policies,
  2818. "The default value appended to the configured exit policy."),
  2819. ITEM("exit-policy/reject-private/default", policies,
  2820. "The default rules appended to the configured exit policy by"
  2821. " ExitPolicyRejectPrivate."),
  2822. ITEM("exit-policy/reject-private/relay", policies,
  2823. "The relay-specific rules appended to the configured exit policy by"
  2824. " ExitPolicyRejectPrivate and/or ExitPolicyRejectLocalInterfaces."),
  2825. ITEM("exit-policy/full", policies, "The entire exit policy of onion router"),
  2826. ITEM("exit-policy/ipv4", policies, "IPv4 parts of exit policy"),
  2827. ITEM("exit-policy/ipv6", policies, "IPv6 parts of exit policy"),
  2828. PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
  2829. ITEM("onions/current", onions,
  2830. "Onion services owned by the current control connection."),
  2831. ITEM("onions/detached", onions,
  2832. "Onion services detached from the control connection."),
  2833. ITEM("sr/current", sr, "Get current shared random value."),
  2834. ITEM("sr/previous", sr, "Get previous shared random value."),
  2835. { NULL, NULL, NULL, 0 }
  2836. };
  2837. /** Allocate and return a list of recognized GETINFO options. */
  2838. static char *
  2839. list_getinfo_options(void)
  2840. {
  2841. int i;
  2842. smartlist_t *lines = smartlist_new();
  2843. char *ans;
  2844. for (i = 0; getinfo_items[i].varname; ++i) {
  2845. if (!getinfo_items[i].desc)
  2846. continue;
  2847. smartlist_add_asprintf(lines, "%s%s -- %s\n",
  2848. getinfo_items[i].varname,
  2849. getinfo_items[i].is_prefix ? "*" : "",
  2850. getinfo_items[i].desc);
  2851. }
  2852. smartlist_sort_strings(lines);
  2853. ans = smartlist_join_strings(lines, "", 0, NULL);
  2854. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  2855. smartlist_free(lines);
  2856. return ans;
  2857. }
  2858. /** Lookup the 'getinfo' entry <b>question</b>, and return
  2859. * the answer in <b>*answer</b> (or NULL if key not recognized).
  2860. * Return 0 if success or unrecognized, or -1 if recognized but
  2861. * internal error. */
  2862. static int
  2863. handle_getinfo_helper(control_connection_t *control_conn,
  2864. const char *question, char **answer,
  2865. const char **err_out)
  2866. {
  2867. int i;
  2868. *answer = NULL; /* unrecognized key by default */
  2869. for (i = 0; getinfo_items[i].varname; ++i) {
  2870. int match;
  2871. if (getinfo_items[i].is_prefix)
  2872. match = !strcmpstart(question, getinfo_items[i].varname);
  2873. else
  2874. match = !strcmp(question, getinfo_items[i].varname);
  2875. if (match) {
  2876. tor_assert(getinfo_items[i].fn);
  2877. return getinfo_items[i].fn(control_conn, question, answer, err_out);
  2878. }
  2879. }
  2880. return 0; /* unrecognized */
  2881. }
  2882. /** Called when we receive a GETINFO command. Try to fetch all requested
  2883. * information, and reply with information or error message. */
  2884. static int
  2885. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  2886. const char *body)
  2887. {
  2888. smartlist_t *questions = smartlist_new();
  2889. smartlist_t *answers = smartlist_new();
  2890. smartlist_t *unrecognized = smartlist_new();
  2891. char *msg = NULL, *ans = NULL;
  2892. int i;
  2893. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2894. smartlist_split_string(questions, body, " ",
  2895. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2896. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  2897. const char *errmsg = NULL;
  2898. if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
  2899. if (!errmsg)
  2900. errmsg = "Internal error";
  2901. connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
  2902. goto done;
  2903. }
  2904. if (!ans) {
  2905. smartlist_add(unrecognized, (char*)q);
  2906. } else {
  2907. smartlist_add_strdup(answers, q);
  2908. smartlist_add(answers, ans);
  2909. }
  2910. } SMARTLIST_FOREACH_END(q);
  2911. if (smartlist_len(unrecognized)) {
  2912. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  2913. connection_printf_to_buf(conn,
  2914. "552-Unrecognized key \"%s\"\r\n",
  2915. (char*)smartlist_get(unrecognized, i));
  2916. connection_printf_to_buf(conn,
  2917. "552 Unrecognized key \"%s\"\r\n",
  2918. (char*)smartlist_get(unrecognized, i));
  2919. goto done;
  2920. }
  2921. for (i = 0; i < smartlist_len(answers); i += 2) {
  2922. char *k = smartlist_get(answers, i);
  2923. char *v = smartlist_get(answers, i+1);
  2924. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  2925. connection_printf_to_buf(conn, "250-%s=", k);
  2926. connection_write_str_to_buf(v, conn);
  2927. connection_write_str_to_buf("\r\n", conn);
  2928. } else {
  2929. char *esc = NULL;
  2930. size_t esc_len;
  2931. esc_len = write_escaped_data(v, strlen(v), &esc);
  2932. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  2933. connection_write_to_buf(esc, esc_len, TO_CONN(conn));
  2934. tor_free(esc);
  2935. }
  2936. }
  2937. connection_write_str_to_buf("250 OK\r\n", conn);
  2938. done:
  2939. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  2940. smartlist_free(answers);
  2941. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  2942. smartlist_free(questions);
  2943. smartlist_free(unrecognized);
  2944. tor_free(msg);
  2945. return 0;
  2946. }
  2947. /** Given a string, convert it to a circuit purpose. */
  2948. static uint8_t
  2949. circuit_purpose_from_string(const char *string)
  2950. {
  2951. if (!strcasecmpstart(string, "purpose="))
  2952. string += strlen("purpose=");
  2953. if (!strcasecmp(string, "general"))
  2954. return CIRCUIT_PURPOSE_C_GENERAL;
  2955. else if (!strcasecmp(string, "controller"))
  2956. return CIRCUIT_PURPOSE_CONTROLLER;
  2957. else
  2958. return CIRCUIT_PURPOSE_UNKNOWN;
  2959. }
  2960. /** Return a newly allocated smartlist containing the arguments to the command
  2961. * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
  2962. * or if <b>max_args</b> is nonnegative and there are more than
  2963. * <b>max_args</b> arguments, send a 512 error to the controller, using
  2964. * <b>command</b> as the command name in the error message. */
  2965. static smartlist_t *
  2966. getargs_helper(const char *command, control_connection_t *conn,
  2967. const char *body, int min_args, int max_args)
  2968. {
  2969. smartlist_t *args = smartlist_new();
  2970. smartlist_split_string(args, body, " ",
  2971. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2972. if (smartlist_len(args) < min_args) {
  2973. connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
  2974. goto err;
  2975. } else if (max_args >= 0 && smartlist_len(args) > max_args) {
  2976. connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
  2977. goto err;
  2978. }
  2979. return args;
  2980. err:
  2981. SMARTLIST_FOREACH(args, char *, s, tor_free(s));
  2982. smartlist_free(args);
  2983. return NULL;
  2984. }
  2985. /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
  2986. * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
  2987. * such element exists. */
  2988. static const char *
  2989. find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
  2990. {
  2991. int i;
  2992. for (i = start_at; i < smartlist_len(sl); ++i) {
  2993. const char *elt = smartlist_get(sl, i);
  2994. if (!strcasecmpstart(elt, prefix))
  2995. return elt;
  2996. }
  2997. return NULL;
  2998. }
  2999. /** Helper. Return true iff s is an argument that we should treat as a
  3000. * key-value pair. */
  3001. static int
  3002. is_keyval_pair(const char *s)
  3003. {
  3004. /* An argument is a key-value pair if it has an =, and it isn't of the form
  3005. * $fingeprint=name */
  3006. return strchr(s, '=') && s[0] != '$';
  3007. }
  3008. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  3009. * circuit, and report success or failure. */
  3010. static int
  3011. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  3012. const char *body)
  3013. {
  3014. smartlist_t *router_nicknames=NULL, *nodes=NULL;
  3015. origin_circuit_t *circ = NULL;
  3016. int zero_circ;
  3017. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  3018. smartlist_t *args;
  3019. (void) len;
  3020. router_nicknames = smartlist_new();
  3021. args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
  3022. if (!args)
  3023. goto done;
  3024. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  3025. if (zero_circ) {
  3026. const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
  3027. if (purp) {
  3028. intended_purpose = circuit_purpose_from_string(purp);
  3029. if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  3030. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  3031. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3032. smartlist_free(args);
  3033. goto done;
  3034. }
  3035. }
  3036. if ((smartlist_len(args) == 1) ||
  3037. (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
  3038. // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
  3039. circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
  3040. if (!circ) {
  3041. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  3042. } else {
  3043. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  3044. (unsigned long)circ->global_identifier);
  3045. }
  3046. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3047. smartlist_free(args);
  3048. goto done;
  3049. }
  3050. // "EXTENDCIRCUIT 0 router1,router2" ||
  3051. // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
  3052. }
  3053. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  3054. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  3055. (char*)smartlist_get(args, 0));
  3056. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3057. smartlist_free(args);
  3058. goto done;
  3059. }
  3060. if (smartlist_len(args) < 2) {
  3061. connection_printf_to_buf(conn,
  3062. "512 syntax error: not enough arguments.\r\n");
  3063. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3064. smartlist_free(args);
  3065. goto done;
  3066. }
  3067. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  3068. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3069. smartlist_free(args);
  3070. nodes = smartlist_new();
  3071. SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
  3072. const node_t *node = node_get_by_nickname(n, 1);
  3073. if (!node) {
  3074. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  3075. goto done;
  3076. }
  3077. if (!node_has_descriptor(node)) {
  3078. connection_printf_to_buf(conn, "552 No descriptor for \"%s\"\r\n", n);
  3079. goto done;
  3080. }
  3081. smartlist_add(nodes, (void*)node);
  3082. } SMARTLIST_FOREACH_END(n);
  3083. if (!smartlist_len(nodes)) {
  3084. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  3085. goto done;
  3086. }
  3087. if (zero_circ) {
  3088. /* start a new circuit */
  3089. circ = origin_circuit_init(intended_purpose, 0);
  3090. }
  3091. /* now circ refers to something that is ready to be extended */
  3092. int first_node = zero_circ;
  3093. SMARTLIST_FOREACH(nodes, const node_t *, node,
  3094. {
  3095. extend_info_t *info = extend_info_from_node(node, first_node);
  3096. if (!info) {
  3097. tor_assert_nonfatal(first_node);
  3098. log_warn(LD_CONTROL,
  3099. "controller tried to connect to a node that doesn't have any "
  3100. "addresses that are allowed by the firewall configuration; "
  3101. "circuit marked for closing.");
  3102. circuit_mark_for_close(TO_CIRCUIT(circ), -END_CIRC_REASON_CONNECTFAILED);
  3103. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  3104. goto done;
  3105. }
  3106. circuit_append_new_exit(circ, info);
  3107. extend_info_free(info);
  3108. first_node = 0;
  3109. });
  3110. /* now that we've populated the cpath, start extending */
  3111. if (zero_circ) {
  3112. int err_reason = 0;
  3113. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  3114. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  3115. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  3116. goto done;
  3117. }
  3118. } else {
  3119. if (circ->base_.state == CIRCUIT_STATE_OPEN ||
  3120. circ->base_.state == CIRCUIT_STATE_GUARD_WAIT) {
  3121. int err_reason = 0;
  3122. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  3123. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  3124. log_info(LD_CONTROL,
  3125. "send_next_onion_skin failed; circuit marked for closing.");
  3126. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  3127. connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
  3128. goto done;
  3129. }
  3130. }
  3131. }
  3132. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  3133. (unsigned long)circ->global_identifier);
  3134. if (zero_circ) /* send a 'launched' event, for completeness */
  3135. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  3136. done:
  3137. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  3138. smartlist_free(router_nicknames);
  3139. smartlist_free(nodes);
  3140. return 0;
  3141. }
  3142. /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
  3143. * circuit and it's a valid purpose, change it. */
  3144. static int
  3145. handle_control_setcircuitpurpose(control_connection_t *conn,
  3146. uint32_t len, const char *body)
  3147. {
  3148. origin_circuit_t *circ = NULL;
  3149. uint8_t new_purpose;
  3150. smartlist_t *args;
  3151. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  3152. args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
  3153. if (!args)
  3154. goto done;
  3155. if (!(circ = get_circ(smartlist_get(args,0)))) {
  3156. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  3157. (char*)smartlist_get(args, 0));
  3158. goto done;
  3159. }
  3160. {
  3161. const char *purp = find_element_starting_with(args,1,"PURPOSE=");
  3162. if (!purp) {
  3163. connection_write_str_to_buf("552 No purpose given\r\n", conn);
  3164. goto done;
  3165. }
  3166. new_purpose = circuit_purpose_from_string(purp);
  3167. if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  3168. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  3169. goto done;
  3170. }
  3171. }
  3172. circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
  3173. connection_write_str_to_buf("250 OK\r\n", conn);
  3174. done:
  3175. if (args) {
  3176. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3177. smartlist_free(args);
  3178. }
  3179. return 0;
  3180. }
  3181. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  3182. * stream, and report success or failure. */
  3183. static int
  3184. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  3185. const char *body)
  3186. {
  3187. entry_connection_t *ap_conn = NULL;
  3188. origin_circuit_t *circ = NULL;
  3189. int zero_circ;
  3190. smartlist_t *args;
  3191. crypt_path_t *cpath=NULL;
  3192. int hop=0, hop_line_ok=1;
  3193. (void) len;
  3194. args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
  3195. if (!args)
  3196. return 0;
  3197. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  3198. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  3199. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  3200. (char*)smartlist_get(args, 0));
  3201. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  3202. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  3203. (char*)smartlist_get(args, 1));
  3204. } else if (circ) {
  3205. const char *hopstring = find_element_starting_with(args,2,"HOP=");
  3206. if (hopstring) {
  3207. hopstring += strlen("HOP=");
  3208. hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
  3209. &hop_line_ok, NULL);
  3210. if (!hop_line_ok) { /* broken hop line */
  3211. connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
  3212. }
  3213. }
  3214. }
  3215. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3216. smartlist_free(args);
  3217. if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
  3218. return 0;
  3219. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
  3220. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
  3221. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
  3222. connection_write_str_to_buf(
  3223. "555 Connection is not managed by controller.\r\n",
  3224. conn);
  3225. return 0;
  3226. }
  3227. /* Do we need to detach it first? */
  3228. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
  3229. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  3230. circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
  3231. connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
  3232. /* Un-mark it as ending, since we're going to reuse it. */
  3233. edge_conn->edge_has_sent_end = 0;
  3234. edge_conn->end_reason = 0;
  3235. if (tmpcirc)
  3236. circuit_detach_stream(tmpcirc, edge_conn);
  3237. CONNECTION_AP_EXPECT_NONPENDING(ap_conn);
  3238. TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  3239. }
  3240. if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
  3241. connection_write_str_to_buf(
  3242. "551 Can't attach stream to non-open origin circuit\r\n",
  3243. conn);
  3244. return 0;
  3245. }
  3246. /* Is this a single hop circuit? */
  3247. if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
  3248. const node_t *node = NULL;
  3249. char *exit_digest = NULL;
  3250. if (circ->build_state &&
  3251. circ->build_state->chosen_exit &&
  3252. !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
  3253. exit_digest = circ->build_state->chosen_exit->identity_digest;
  3254. node = node_get_by_id(exit_digest);
  3255. }
  3256. /* Do both the client and relay allow one-hop exit circuits? */
  3257. if (!node ||
  3258. !node_allows_single_hop_exits(node) ||
  3259. !get_options()->AllowSingleHopCircuits) {
  3260. connection_write_str_to_buf(
  3261. "551 Can't attach stream to this one-hop circuit.\r\n", conn);
  3262. return 0;
  3263. }
  3264. tor_assert(exit_digest);
  3265. ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
  3266. }
  3267. if (circ && hop>0) {
  3268. /* find this hop in the circuit, and set cpath */
  3269. cpath = circuit_get_cpath_hop(circ, hop);
  3270. if (!cpath) {
  3271. connection_printf_to_buf(conn,
  3272. "551 Circuit doesn't have %d hops.\r\n", hop);
  3273. return 0;
  3274. }
  3275. }
  3276. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
  3277. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  3278. return 0;
  3279. }
  3280. send_control_done(conn);
  3281. return 0;
  3282. }
  3283. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  3284. * descriptor, and report success or failure. */
  3285. static int
  3286. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  3287. const char *body)
  3288. {
  3289. char *desc;
  3290. const char *msg=NULL;
  3291. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  3292. int cache = 0; /* eventually, we may switch this to 1 */
  3293. const char *cp = memchr(body, '\n', len);
  3294. smartlist_t *args = smartlist_new();
  3295. tor_assert(cp);
  3296. ++cp;
  3297. char *cmdline = tor_memdup_nulterm(body, cp-body);
  3298. smartlist_split_string(args, cmdline, " ",
  3299. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3300. SMARTLIST_FOREACH_BEGIN(args, char *, option) {
  3301. if (!strcasecmpstart(option, "purpose=")) {
  3302. option += strlen("purpose=");
  3303. purpose = router_purpose_from_string(option);
  3304. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  3305. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  3306. option);
  3307. goto done;
  3308. }
  3309. } else if (!strcasecmpstart(option, "cache=")) {
  3310. option += strlen("cache=");
  3311. if (!strcasecmp(option, "no"))
  3312. cache = 0;
  3313. else if (!strcasecmp(option, "yes"))
  3314. cache = 1;
  3315. else {
  3316. connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
  3317. option);
  3318. goto done;
  3319. }
  3320. } else { /* unrecognized argument? */
  3321. connection_printf_to_buf(conn,
  3322. "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
  3323. goto done;
  3324. }
  3325. } SMARTLIST_FOREACH_END(option);
  3326. read_escaped_data(cp, len-(cp-body), &desc);
  3327. switch (router_load_single_router(desc, purpose, cache, &msg)) {
  3328. case -1:
  3329. if (!msg) msg = "Could not parse descriptor";
  3330. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  3331. break;
  3332. case 0:
  3333. if (!msg) msg = "Descriptor not added";
  3334. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  3335. break;
  3336. case 1:
  3337. send_control_done(conn);
  3338. break;
  3339. }
  3340. tor_free(desc);
  3341. done:
  3342. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  3343. smartlist_free(args);
  3344. tor_free(cmdline);
  3345. return 0;
  3346. }
  3347. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  3348. * address of the named AP stream, and report success or failure. */
  3349. static int
  3350. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  3351. const char *body)
  3352. {
  3353. entry_connection_t *ap_conn = NULL;
  3354. char *new_addr = NULL;
  3355. uint16_t new_port = 0;
  3356. smartlist_t *args;
  3357. (void) len;
  3358. args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
  3359. if (!args)
  3360. return 0;
  3361. if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  3362. || !ap_conn->socks_request) {
  3363. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  3364. (char*)smartlist_get(args, 0));
  3365. } else {
  3366. int ok = 1;
  3367. if (smartlist_len(args) > 2) { /* they included a port too */
  3368. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  3369. 10, 1, 65535, &ok, NULL);
  3370. }
  3371. if (!ok) {
  3372. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  3373. (char*)smartlist_get(args, 2));
  3374. } else {
  3375. new_addr = tor_strdup(smartlist_get(args, 1));
  3376. }
  3377. }
  3378. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3379. smartlist_free(args);
  3380. if (!new_addr)
  3381. return 0;
  3382. strlcpy(ap_conn->socks_request->address, new_addr,
  3383. sizeof(ap_conn->socks_request->address));
  3384. if (new_port)
  3385. ap_conn->socks_request->port = new_port;
  3386. tor_free(new_addr);
  3387. send_control_done(conn);
  3388. return 0;
  3389. }
  3390. /** Called when we get a CLOSESTREAM command; try to close the named stream
  3391. * and report success or failure. */
  3392. static int
  3393. handle_control_closestream(control_connection_t *conn, uint32_t len,
  3394. const char *body)
  3395. {
  3396. entry_connection_t *ap_conn=NULL;
  3397. uint8_t reason=0;
  3398. smartlist_t *args;
  3399. int ok;
  3400. (void) len;
  3401. args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
  3402. if (!args)
  3403. return 0;
  3404. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  3405. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  3406. (char*)smartlist_get(args, 0));
  3407. else {
  3408. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  3409. &ok, NULL);
  3410. if (!ok) {
  3411. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  3412. (char*)smartlist_get(args, 1));
  3413. ap_conn = NULL;
  3414. }
  3415. }
  3416. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3417. smartlist_free(args);
  3418. if (!ap_conn)
  3419. return 0;
  3420. connection_mark_unattached_ap(ap_conn, reason);
  3421. send_control_done(conn);
  3422. return 0;
  3423. }
  3424. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  3425. * and report success or failure. */
  3426. static int
  3427. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  3428. const char *body)
  3429. {
  3430. origin_circuit_t *circ = NULL;
  3431. int safe = 0;
  3432. smartlist_t *args;
  3433. (void) len;
  3434. args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
  3435. if (!args)
  3436. return 0;
  3437. if (!(circ=get_circ(smartlist_get(args, 0))))
  3438. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  3439. (char*)smartlist_get(args, 0));
  3440. else {
  3441. int i;
  3442. for (i=1; i < smartlist_len(args); ++i) {
  3443. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  3444. safe = 1;
  3445. else
  3446. log_info(LD_CONTROL, "Skipping unknown option %s",
  3447. (char*)smartlist_get(args,i));
  3448. }
  3449. }
  3450. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3451. smartlist_free(args);
  3452. if (!circ)
  3453. return 0;
  3454. if (!safe || !circ->p_streams) {
  3455. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
  3456. }
  3457. send_control_done(conn);
  3458. return 0;
  3459. }
  3460. /** Called when we get a RESOLVE command: start trying to resolve
  3461. * the listed addresses. */
  3462. static int
  3463. handle_control_resolve(control_connection_t *conn, uint32_t len,
  3464. const char *body)
  3465. {
  3466. smartlist_t *args, *failed;
  3467. int is_reverse = 0;
  3468. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3469. if (!(conn->event_mask & (((event_mask_t)1)<<EVENT_ADDRMAP))) {
  3470. log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
  3471. "isn't listening for ADDRMAP events. It probably won't see "
  3472. "the answer.");
  3473. }
  3474. args = smartlist_new();
  3475. smartlist_split_string(args, body, " ",
  3476. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3477. {
  3478. const char *modearg = find_element_starting_with(args, 0, "mode=");
  3479. if (modearg && !strcasecmp(modearg, "mode=reverse"))
  3480. is_reverse = 1;
  3481. }
  3482. failed = smartlist_new();
  3483. SMARTLIST_FOREACH(args, const char *, arg, {
  3484. if (!is_keyval_pair(arg)) {
  3485. if (dnsserv_launch_request(arg, is_reverse, conn)<0)
  3486. smartlist_add(failed, (char*)arg);
  3487. }
  3488. });
  3489. send_control_done(conn);
  3490. SMARTLIST_FOREACH(failed, const char *, arg, {
  3491. control_event_address_mapped(arg, arg, time(NULL),
  3492. "internal", 0);
  3493. });
  3494. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3495. smartlist_free(args);
  3496. smartlist_free(failed);
  3497. return 0;
  3498. }
  3499. /** Called when we get a PROTOCOLINFO command: send back a reply. */
  3500. static int
  3501. handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
  3502. const char *body)
  3503. {
  3504. const char *bad_arg = NULL;
  3505. smartlist_t *args;
  3506. (void)len;
  3507. conn->have_sent_protocolinfo = 1;
  3508. args = smartlist_new();
  3509. smartlist_split_string(args, body, " ",
  3510. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3511. SMARTLIST_FOREACH(args, const char *, arg, {
  3512. int ok;
  3513. tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
  3514. if (!ok) {
  3515. bad_arg = arg;
  3516. break;
  3517. }
  3518. });
  3519. if (bad_arg) {
  3520. connection_printf_to_buf(conn, "513 No such version %s\r\n",
  3521. escaped(bad_arg));
  3522. /* Don't tolerate bad arguments when not authenticated. */
  3523. if (!STATE_IS_OPEN(TO_CONN(conn)->state))
  3524. connection_mark_for_close(TO_CONN(conn));
  3525. goto done;
  3526. } else {
  3527. const or_options_t *options = get_options();
  3528. int cookies = options->CookieAuthentication;
  3529. char *cfile = get_controller_cookie_file_name();
  3530. char *abs_cfile;
  3531. char *esc_cfile;
  3532. char *methods;
  3533. abs_cfile = make_path_absolute(cfile);
  3534. esc_cfile = esc_for_log(abs_cfile);
  3535. {
  3536. int passwd = (options->HashedControlPassword != NULL ||
  3537. options->HashedControlSessionPassword != NULL);
  3538. smartlist_t *mlist = smartlist_new();
  3539. if (cookies) {
  3540. smartlist_add(mlist, (char*)"COOKIE");
  3541. smartlist_add(mlist, (char*)"SAFECOOKIE");
  3542. }
  3543. if (passwd)
  3544. smartlist_add(mlist, (char*)"HASHEDPASSWORD");
  3545. if (!cookies && !passwd)
  3546. smartlist_add(mlist, (char*)"NULL");
  3547. methods = smartlist_join_strings(mlist, ",", 0, NULL);
  3548. smartlist_free(mlist);
  3549. }
  3550. connection_printf_to_buf(conn,
  3551. "250-PROTOCOLINFO 1\r\n"
  3552. "250-AUTH METHODS=%s%s%s\r\n"
  3553. "250-VERSION Tor=%s\r\n"
  3554. "250 OK\r\n",
  3555. methods,
  3556. cookies?" COOKIEFILE=":"",
  3557. cookies?esc_cfile:"",
  3558. escaped(VERSION));
  3559. tor_free(methods);
  3560. tor_free(cfile);
  3561. tor_free(abs_cfile);
  3562. tor_free(esc_cfile);
  3563. }
  3564. done:
  3565. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3566. smartlist_free(args);
  3567. return 0;
  3568. }
  3569. /** Called when we get an AUTHCHALLENGE command. */
  3570. static int
  3571. handle_control_authchallenge(control_connection_t *conn, uint32_t len,
  3572. const char *body)
  3573. {
  3574. const char *cp = body;
  3575. char *client_nonce;
  3576. size_t client_nonce_len;
  3577. char server_hash[DIGEST256_LEN];
  3578. char server_hash_encoded[HEX_DIGEST256_LEN+1];
  3579. char server_nonce[SAFECOOKIE_SERVER_NONCE_LEN];
  3580. char server_nonce_encoded[(2*SAFECOOKIE_SERVER_NONCE_LEN) + 1];
  3581. cp += strspn(cp, " \t\n\r");
  3582. if (!strcasecmpstart(cp, "SAFECOOKIE")) {
  3583. cp += strlen("SAFECOOKIE");
  3584. } else {
  3585. connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
  3586. "authentication\r\n", conn);
  3587. connection_mark_for_close(TO_CONN(conn));
  3588. return -1;
  3589. }
  3590. if (!authentication_cookie_is_set) {
  3591. connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
  3592. conn);
  3593. connection_mark_for_close(TO_CONN(conn));
  3594. return -1;
  3595. }
  3596. cp += strspn(cp, " \t\n\r");
  3597. if (*cp == '"') {
  3598. const char *newcp =
  3599. decode_escaped_string(cp, len - (cp - body),
  3600. &client_nonce, &client_nonce_len);
  3601. if (newcp == NULL) {
  3602. connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
  3603. conn);
  3604. connection_mark_for_close(TO_CONN(conn));
  3605. return -1;
  3606. }
  3607. cp = newcp;
  3608. } else {
  3609. size_t client_nonce_encoded_len = strspn(cp, "0123456789ABCDEFabcdef");
  3610. client_nonce_len = client_nonce_encoded_len / 2;
  3611. client_nonce = tor_malloc_zero(client_nonce_len);
  3612. if (base16_decode(client_nonce, client_nonce_len,
  3613. cp, client_nonce_encoded_len)
  3614. != (int) client_nonce_len) {
  3615. connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
  3616. conn);
  3617. connection_mark_for_close(TO_CONN(conn));
  3618. tor_free(client_nonce);
  3619. return -1;
  3620. }
  3621. cp += client_nonce_encoded_len;
  3622. }
  3623. cp += strspn(cp, " \t\n\r");
  3624. if (*cp != '\0' ||
  3625. cp != body + len) {
  3626. connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
  3627. conn);
  3628. connection_mark_for_close(TO_CONN(conn));
  3629. tor_free(client_nonce);
  3630. return -1;
  3631. }
  3632. crypto_rand(server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
  3633. /* Now compute and send the server-to-controller response, and the
  3634. * server's nonce. */
  3635. tor_assert(authentication_cookie != NULL);
  3636. {
  3637. size_t tmp_len = (AUTHENTICATION_COOKIE_LEN +
  3638. client_nonce_len +
  3639. SAFECOOKIE_SERVER_NONCE_LEN);
  3640. char *tmp = tor_malloc_zero(tmp_len);
  3641. char *client_hash = tor_malloc_zero(DIGEST256_LEN);
  3642. memcpy(tmp, authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  3643. memcpy(tmp + AUTHENTICATION_COOKIE_LEN, client_nonce, client_nonce_len);
  3644. memcpy(tmp + AUTHENTICATION_COOKIE_LEN + client_nonce_len,
  3645. server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
  3646. crypto_hmac_sha256(server_hash,
  3647. SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT,
  3648. strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT),
  3649. tmp,
  3650. tmp_len);
  3651. crypto_hmac_sha256(client_hash,
  3652. SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT,
  3653. strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT),
  3654. tmp,
  3655. tmp_len);
  3656. conn->safecookie_client_hash = client_hash;
  3657. tor_free(tmp);
  3658. }
  3659. base16_encode(server_hash_encoded, sizeof(server_hash_encoded),
  3660. server_hash, sizeof(server_hash));
  3661. base16_encode(server_nonce_encoded, sizeof(server_nonce_encoded),
  3662. server_nonce, sizeof(server_nonce));
  3663. connection_printf_to_buf(conn,
  3664. "250 AUTHCHALLENGE SERVERHASH=%s "
  3665. "SERVERNONCE=%s\r\n",
  3666. server_hash_encoded,
  3667. server_nonce_encoded);
  3668. tor_free(client_nonce);
  3669. return 0;
  3670. }
  3671. /** Called when we get a USEFEATURE command: parse the feature list, and
  3672. * set up the control_connection's options properly. */
  3673. static int
  3674. handle_control_usefeature(control_connection_t *conn,
  3675. uint32_t len,
  3676. const char *body)
  3677. {
  3678. smartlist_t *args;
  3679. int bad = 0;
  3680. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3681. args = smartlist_new();
  3682. smartlist_split_string(args, body, " ",
  3683. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3684. SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
  3685. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  3686. ;
  3687. else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
  3688. ;
  3689. else {
  3690. connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
  3691. arg);
  3692. bad = 1;
  3693. break;
  3694. }
  3695. } SMARTLIST_FOREACH_END(arg);
  3696. if (!bad) {
  3697. send_control_done(conn);
  3698. }
  3699. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3700. smartlist_free(args);
  3701. return 0;
  3702. }
  3703. /** Implementation for the DROPGUARDS command. */
  3704. static int
  3705. handle_control_dropguards(control_connection_t *conn,
  3706. uint32_t len,
  3707. const char *body)
  3708. {
  3709. smartlist_t *args;
  3710. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3711. args = smartlist_new();
  3712. smartlist_split_string(args, body, " ",
  3713. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3714. static int have_warned = 0;
  3715. if (! have_warned) {
  3716. log_warn(LD_CONTROL, "DROPGUARDS is dangerous; make sure you understand "
  3717. "the risks before using it. It may be removed in a future "
  3718. "version of Tor.");
  3719. have_warned = 1;
  3720. }
  3721. if (smartlist_len(args)) {
  3722. connection_printf_to_buf(conn, "512 Too many arguments to DROPGUARDS\r\n");
  3723. } else {
  3724. remove_all_entry_guards();
  3725. send_control_done(conn);
  3726. }
  3727. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3728. smartlist_free(args);
  3729. return 0;
  3730. }
  3731. /** Implementation for the HSFETCH command. */
  3732. static int
  3733. handle_control_hsfetch(control_connection_t *conn, uint32_t len,
  3734. const char *body)
  3735. {
  3736. int i;
  3737. char digest[DIGEST_LEN], *hsaddress = NULL, *arg1 = NULL, *desc_id = NULL;
  3738. smartlist_t *args = NULL, *hsdirs = NULL;
  3739. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3740. static const char *hsfetch_command = "HSFETCH";
  3741. static const char *v2_str = "v2-";
  3742. const size_t v2_str_len = strlen(v2_str);
  3743. rend_data_t *rend_query = NULL;
  3744. /* Make sure we have at least one argument, the HSAddress. */
  3745. args = getargs_helper(hsfetch_command, conn, body, 1, -1);
  3746. if (!args) {
  3747. goto exit;
  3748. }
  3749. /* Extract the first argument (either HSAddress or DescID). */
  3750. arg1 = smartlist_get(args, 0);
  3751. /* Test if it's an HS address without the .onion part. */
  3752. if (rend_valid_service_id(arg1)) {
  3753. hsaddress = arg1;
  3754. } else if (strcmpstart(arg1, v2_str) == 0 &&
  3755. rend_valid_descriptor_id(arg1 + v2_str_len) &&
  3756. base32_decode(digest, sizeof(digest), arg1 + v2_str_len,
  3757. REND_DESC_ID_V2_LEN_BASE32) == 0) {
  3758. /* We have a well formed version 2 descriptor ID. Keep the decoded value
  3759. * of the id. */
  3760. desc_id = digest;
  3761. } else {
  3762. connection_printf_to_buf(conn, "513 Invalid argument \"%s\"\r\n",
  3763. arg1);
  3764. goto done;
  3765. }
  3766. static const char *opt_server = "SERVER=";
  3767. /* Skip first argument because it's the HSAddress or DescID. */
  3768. for (i = 1; i < smartlist_len(args); ++i) {
  3769. const char *arg = smartlist_get(args, i);
  3770. const node_t *node;
  3771. if (!strcasecmpstart(arg, opt_server)) {
  3772. const char *server;
  3773. server = arg + strlen(opt_server);
  3774. node = node_get_by_hex_id(server);
  3775. if (!node) {
  3776. connection_printf_to_buf(conn, "552 Server \"%s\" not found\r\n",
  3777. server);
  3778. goto done;
  3779. }
  3780. if (!hsdirs) {
  3781. /* Stores routerstatus_t object for each specified server. */
  3782. hsdirs = smartlist_new();
  3783. }
  3784. /* Valid server, add it to our local list. */
  3785. smartlist_add(hsdirs, node->rs);
  3786. } else {
  3787. connection_printf_to_buf(conn, "513 Unexpected argument \"%s\"\r\n",
  3788. arg);
  3789. goto done;
  3790. }
  3791. }
  3792. rend_query = rend_data_client_create(hsaddress, desc_id, NULL,
  3793. REND_NO_AUTH);
  3794. if (rend_query == NULL) {
  3795. connection_printf_to_buf(conn, "551 Error creating the HS query\r\n");
  3796. goto done;
  3797. }
  3798. /* Using a descriptor ID, we force the user to provide at least one
  3799. * hsdir server using the SERVER= option. */
  3800. if (desc_id && (!hsdirs || !smartlist_len(hsdirs))) {
  3801. connection_printf_to_buf(conn, "512 %s option is required\r\n",
  3802. opt_server);
  3803. goto done;
  3804. }
  3805. /* We are about to trigger HSDir fetch so send the OK now because after
  3806. * that 650 event(s) are possible so better to have the 250 OK before them
  3807. * to avoid out of order replies. */
  3808. send_control_done(conn);
  3809. /* Trigger the fetch using the built rend query and possibly a list of HS
  3810. * directory to use. This function ignores the client cache thus this will
  3811. * always send a fetch command. */
  3812. rend_client_fetch_v2_desc(rend_query, hsdirs);
  3813. done:
  3814. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3815. smartlist_free(args);
  3816. /* Contains data pointer that we don't own thus no cleanup. */
  3817. smartlist_free(hsdirs);
  3818. rend_data_free(rend_query);
  3819. exit:
  3820. return 0;
  3821. }
  3822. /** Implementation for the HSPOST command. */
  3823. static int
  3824. handle_control_hspost(control_connection_t *conn,
  3825. uint32_t len,
  3826. const char *body)
  3827. {
  3828. static const char *opt_server = "SERVER=";
  3829. smartlist_t *args = smartlist_new();
  3830. smartlist_t *hs_dirs = NULL;
  3831. const char *encoded_desc = body;
  3832. size_t encoded_desc_len = len;
  3833. char *cp = memchr(body, '\n', len);
  3834. char *argline = tor_strndup(body, cp-body);
  3835. /* If any SERVER= options were specified, try parse the options line */
  3836. if (!strcasecmpstart(argline, opt_server)) {
  3837. /* encoded_desc begins after a newline character */
  3838. cp = cp + 1;
  3839. encoded_desc = cp;
  3840. encoded_desc_len = len-(cp-body);
  3841. smartlist_split_string(args, argline, " ",
  3842. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3843. SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
  3844. if (!strcasecmpstart(arg, opt_server)) {
  3845. const char *server = arg + strlen(opt_server);
  3846. const node_t *node = node_get_by_hex_id(server);
  3847. if (!node || !node->rs) {
  3848. connection_printf_to_buf(conn, "552 Server \"%s\" not found\r\n",
  3849. server);
  3850. goto done;
  3851. }
  3852. if (!node->rs->is_hs_dir) {
  3853. connection_printf_to_buf(conn, "552 Server \"%s\" is not a HSDir"
  3854. "\r\n", server);
  3855. goto done;
  3856. }
  3857. /* Valid server, add it to our local list. */
  3858. if (!hs_dirs)
  3859. hs_dirs = smartlist_new();
  3860. smartlist_add(hs_dirs, node->rs);
  3861. } else {
  3862. connection_printf_to_buf(conn, "512 Unexpected argument \"%s\"\r\n",
  3863. arg);
  3864. goto done;
  3865. }
  3866. } SMARTLIST_FOREACH_END(arg);
  3867. }
  3868. /* Read the dot encoded descriptor, and parse it. */
  3869. rend_encoded_v2_service_descriptor_t *desc =
  3870. tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
  3871. read_escaped_data(encoded_desc, encoded_desc_len, &desc->desc_str);
  3872. rend_service_descriptor_t *parsed = NULL;
  3873. char *intro_content = NULL;
  3874. size_t intro_size;
  3875. size_t encoded_size;
  3876. const char *next_desc;
  3877. if (!rend_parse_v2_service_descriptor(&parsed, desc->desc_id, &intro_content,
  3878. &intro_size, &encoded_size,
  3879. &next_desc, desc->desc_str, 1)) {
  3880. /* Post the descriptor. */
  3881. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  3882. if (!rend_get_service_id(parsed->pk, serviceid)) {
  3883. smartlist_t *descs = smartlist_new();
  3884. smartlist_add(descs, desc);
  3885. /* We are about to trigger HS descriptor upload so send the OK now
  3886. * because after that 650 event(s) are possible so better to have the
  3887. * 250 OK before them to avoid out of order replies. */
  3888. send_control_done(conn);
  3889. /* Trigger the descriptor upload */
  3890. directory_post_to_hs_dir(parsed, descs, hs_dirs, serviceid, 0);
  3891. smartlist_free(descs);
  3892. }
  3893. rend_service_descriptor_free(parsed);
  3894. } else {
  3895. connection_printf_to_buf(conn, "554 Invalid descriptor\r\n");
  3896. }
  3897. tor_free(intro_content);
  3898. rend_encoded_v2_service_descriptor_free(desc);
  3899. done:
  3900. tor_free(argline);
  3901. smartlist_free(hs_dirs); /* Contents belong to the rend service code. */
  3902. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  3903. smartlist_free(args);
  3904. return 0;
  3905. }
  3906. /** Called when we get a ADD_ONION command; parse the body, and set up
  3907. * the new ephemeral Onion Service. */
  3908. static int
  3909. handle_control_add_onion(control_connection_t *conn,
  3910. uint32_t len,
  3911. const char *body)
  3912. {
  3913. smartlist_t *args;
  3914. size_t arg_len;
  3915. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3916. args = getargs_helper("ADD_ONION", conn, body, 2, -1);
  3917. if (!args)
  3918. return 0;
  3919. arg_len = smartlist_len(args);
  3920. /* Parse all of the arguments that do not involve handling cryptographic
  3921. * material first, since there's no reason to touch that at all if any of
  3922. * the other arguments are malformed.
  3923. */
  3924. smartlist_t *port_cfgs = smartlist_new();
  3925. smartlist_t *auth_clients = NULL;
  3926. smartlist_t *auth_created_clients = NULL;
  3927. int discard_pk = 0;
  3928. int detach = 0;
  3929. int max_streams = 0;
  3930. int max_streams_close_circuit = 0;
  3931. rend_auth_type_t auth_type = REND_NO_AUTH;
  3932. /* Default to adding an anonymous hidden service if no flag is given */
  3933. int non_anonymous = 0;
  3934. for (size_t i = 1; i < arg_len; i++) {
  3935. static const char *port_prefix = "Port=";
  3936. static const char *flags_prefix = "Flags=";
  3937. static const char *max_s_prefix = "MaxStreams=";
  3938. static const char *auth_prefix = "ClientAuth=";
  3939. const char *arg = smartlist_get(args, i);
  3940. if (!strcasecmpstart(arg, port_prefix)) {
  3941. /* "Port=VIRTPORT[,TARGET]". */
  3942. const char *port_str = arg + strlen(port_prefix);
  3943. rend_service_port_config_t *cfg =
  3944. rend_service_parse_port_config(port_str, ",", NULL);
  3945. if (!cfg) {
  3946. connection_printf_to_buf(conn, "512 Invalid VIRTPORT/TARGET\r\n");
  3947. goto out;
  3948. }
  3949. smartlist_add(port_cfgs, cfg);
  3950. } else if (!strcasecmpstart(arg, max_s_prefix)) {
  3951. /* "MaxStreams=[0..65535]". */
  3952. const char *max_s_str = arg + strlen(max_s_prefix);
  3953. int ok = 0;
  3954. max_streams = (int)tor_parse_long(max_s_str, 10, 0, 65535, &ok, NULL);
  3955. if (!ok) {
  3956. connection_printf_to_buf(conn, "512 Invalid MaxStreams\r\n");
  3957. goto out;
  3958. }
  3959. } else if (!strcasecmpstart(arg, flags_prefix)) {
  3960. /* "Flags=Flag[,Flag]", where Flag can be:
  3961. * * 'DiscardPK' - If tor generates the keypair, do not include it in
  3962. * the response.
  3963. * * 'Detach' - Do not tie this onion service to any particular control
  3964. * connection.
  3965. * * 'MaxStreamsCloseCircuit' - Close the circuit if MaxStreams is
  3966. * exceeded.
  3967. * * 'BasicAuth' - Client authorization using the 'basic' method.
  3968. * * 'NonAnonymous' - Add a non-anonymous Single Onion Service. If this
  3969. * flag is present, tor must be in non-anonymous
  3970. * hidden service mode. If this flag is absent,
  3971. * tor must be in anonymous hidden service mode.
  3972. */
  3973. static const char *discard_flag = "DiscardPK";
  3974. static const char *detach_flag = "Detach";
  3975. static const char *max_s_close_flag = "MaxStreamsCloseCircuit";
  3976. static const char *basicauth_flag = "BasicAuth";
  3977. static const char *non_anonymous_flag = "NonAnonymous";
  3978. smartlist_t *flags = smartlist_new();
  3979. int bad = 0;
  3980. smartlist_split_string(flags, arg + strlen(flags_prefix), ",",
  3981. SPLIT_IGNORE_BLANK, 0);
  3982. if (smartlist_len(flags) < 1) {
  3983. connection_printf_to_buf(conn, "512 Invalid 'Flags' argument\r\n");
  3984. bad = 1;
  3985. }
  3986. SMARTLIST_FOREACH_BEGIN(flags, const char *, flag)
  3987. {
  3988. if (!strcasecmp(flag, discard_flag)) {
  3989. discard_pk = 1;
  3990. } else if (!strcasecmp(flag, detach_flag)) {
  3991. detach = 1;
  3992. } else if (!strcasecmp(flag, max_s_close_flag)) {
  3993. max_streams_close_circuit = 1;
  3994. } else if (!strcasecmp(flag, basicauth_flag)) {
  3995. auth_type = REND_BASIC_AUTH;
  3996. } else if (!strcasecmp(flag, non_anonymous_flag)) {
  3997. non_anonymous = 1;
  3998. } else {
  3999. connection_printf_to_buf(conn,
  4000. "512 Invalid 'Flags' argument: %s\r\n",
  4001. escaped(flag));
  4002. bad = 1;
  4003. break;
  4004. }
  4005. } SMARTLIST_FOREACH_END(flag);
  4006. SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
  4007. smartlist_free(flags);
  4008. if (bad)
  4009. goto out;
  4010. } else if (!strcasecmpstart(arg, auth_prefix)) {
  4011. char *err_msg = NULL;
  4012. int created = 0;
  4013. rend_authorized_client_t *client =
  4014. add_onion_helper_clientauth(arg + strlen(auth_prefix),
  4015. &created, &err_msg);
  4016. if (!client) {
  4017. if (err_msg) {
  4018. connection_write_str_to_buf(err_msg, conn);
  4019. tor_free(err_msg);
  4020. }
  4021. goto out;
  4022. }
  4023. if (auth_clients != NULL) {
  4024. int bad = 0;
  4025. SMARTLIST_FOREACH_BEGIN(auth_clients, rend_authorized_client_t *, ac) {
  4026. if (strcmp(ac->client_name, client->client_name) == 0) {
  4027. bad = 1;
  4028. break;
  4029. }
  4030. } SMARTLIST_FOREACH_END(ac);
  4031. if (bad) {
  4032. connection_printf_to_buf(conn,
  4033. "512 Duplicate name in ClientAuth\r\n");
  4034. rend_authorized_client_free(client);
  4035. goto out;
  4036. }
  4037. } else {
  4038. auth_clients = smartlist_new();
  4039. auth_created_clients = smartlist_new();
  4040. }
  4041. smartlist_add(auth_clients, client);
  4042. if (created) {
  4043. smartlist_add(auth_created_clients, client);
  4044. }
  4045. } else {
  4046. connection_printf_to_buf(conn, "513 Invalid argument\r\n");
  4047. goto out;
  4048. }
  4049. }
  4050. if (smartlist_len(port_cfgs) == 0) {
  4051. connection_printf_to_buf(conn, "512 Missing 'Port' argument\r\n");
  4052. goto out;
  4053. } else if (auth_type == REND_NO_AUTH && auth_clients != NULL) {
  4054. connection_printf_to_buf(conn, "512 No auth type specified\r\n");
  4055. goto out;
  4056. } else if (auth_type != REND_NO_AUTH && auth_clients == NULL) {
  4057. connection_printf_to_buf(conn, "512 No auth clients specified\r\n");
  4058. goto out;
  4059. } else if ((auth_type == REND_BASIC_AUTH &&
  4060. smartlist_len(auth_clients) > 512) ||
  4061. (auth_type == REND_STEALTH_AUTH &&
  4062. smartlist_len(auth_clients) > 16)) {
  4063. connection_printf_to_buf(conn, "512 Too many auth clients\r\n");
  4064. goto out;
  4065. } else if (non_anonymous != rend_service_non_anonymous_mode_enabled(
  4066. get_options())) {
  4067. /* If we failed, and the non-anonymous flag is set, Tor must be in
  4068. * anonymous hidden service mode.
  4069. * The error message changes based on the current Tor config:
  4070. * 512 Tor is in anonymous hidden service mode
  4071. * 512 Tor is in non-anonymous hidden service mode
  4072. * (I've deliberately written them out in full here to aid searchability.)
  4073. */
  4074. connection_printf_to_buf(conn, "512 Tor is in %sanonymous hidden service "
  4075. "mode\r\n",
  4076. non_anonymous ? "" : "non-");
  4077. goto out;
  4078. }
  4079. /* Parse the "keytype:keyblob" argument. */
  4080. crypto_pk_t *pk = NULL;
  4081. const char *key_new_alg = NULL;
  4082. char *key_new_blob = NULL;
  4083. char *err_msg = NULL;
  4084. pk = add_onion_helper_keyarg(smartlist_get(args, 0), discard_pk,
  4085. &key_new_alg, &key_new_blob,
  4086. &err_msg);
  4087. if (!pk) {
  4088. if (err_msg) {
  4089. connection_write_str_to_buf(err_msg, conn);
  4090. tor_free(err_msg);
  4091. }
  4092. goto out;
  4093. }
  4094. tor_assert(!err_msg);
  4095. /* Create the HS, using private key pk, client authentication auth_type,
  4096. * the list of auth_clients, and port config port_cfg.
  4097. * rend_service_add_ephemeral() will take ownership of pk and port_cfg,
  4098. * regardless of success/failure.
  4099. */
  4100. char *service_id = NULL;
  4101. int ret = rend_service_add_ephemeral(pk, port_cfgs, max_streams,
  4102. max_streams_close_circuit,
  4103. auth_type, auth_clients,
  4104. &service_id);
  4105. port_cfgs = NULL; /* port_cfgs is now owned by the rendservice code. */
  4106. auth_clients = NULL; /* so is auth_clients */
  4107. switch (ret) {
  4108. case RSAE_OKAY:
  4109. {
  4110. if (detach) {
  4111. if (!detached_onion_services)
  4112. detached_onion_services = smartlist_new();
  4113. smartlist_add(detached_onion_services, service_id);
  4114. } else {
  4115. if (!conn->ephemeral_onion_services)
  4116. conn->ephemeral_onion_services = smartlist_new();
  4117. smartlist_add(conn->ephemeral_onion_services, service_id);
  4118. }
  4119. tor_assert(service_id);
  4120. connection_printf_to_buf(conn, "250-ServiceID=%s\r\n", service_id);
  4121. if (key_new_alg) {
  4122. tor_assert(key_new_blob);
  4123. connection_printf_to_buf(conn, "250-PrivateKey=%s:%s\r\n",
  4124. key_new_alg, key_new_blob);
  4125. }
  4126. if (auth_created_clients) {
  4127. SMARTLIST_FOREACH(auth_created_clients, rend_authorized_client_t *, ac, {
  4128. char *encoded = rend_auth_encode_cookie(ac->descriptor_cookie,
  4129. auth_type);
  4130. tor_assert(encoded);
  4131. connection_printf_to_buf(conn, "250-ClientAuth=%s:%s\r\n",
  4132. ac->client_name, encoded);
  4133. memwipe(encoded, 0, strlen(encoded));
  4134. tor_free(encoded);
  4135. });
  4136. }
  4137. connection_printf_to_buf(conn, "250 OK\r\n");
  4138. break;
  4139. }
  4140. case RSAE_BADPRIVKEY:
  4141. connection_printf_to_buf(conn, "551 Failed to generate onion address\r\n");
  4142. break;
  4143. case RSAE_ADDREXISTS:
  4144. connection_printf_to_buf(conn, "550 Onion address collision\r\n");
  4145. break;
  4146. case RSAE_BADVIRTPORT:
  4147. connection_printf_to_buf(conn, "512 Invalid VIRTPORT/TARGET\r\n");
  4148. break;
  4149. case RSAE_BADAUTH:
  4150. connection_printf_to_buf(conn, "512 Invalid client authorization\r\n");
  4151. break;
  4152. case RSAE_INTERNAL: /* FALLSTHROUGH */
  4153. default:
  4154. connection_printf_to_buf(conn, "551 Failed to add Onion Service\r\n");
  4155. }
  4156. if (key_new_blob) {
  4157. memwipe(key_new_blob, 0, strlen(key_new_blob));
  4158. tor_free(key_new_blob);
  4159. }
  4160. out:
  4161. if (port_cfgs) {
  4162. SMARTLIST_FOREACH(port_cfgs, rend_service_port_config_t*, p,
  4163. rend_service_port_config_free(p));
  4164. smartlist_free(port_cfgs);
  4165. }
  4166. if (auth_clients) {
  4167. SMARTLIST_FOREACH(auth_clients, rend_authorized_client_t *, ac,
  4168. rend_authorized_client_free(ac));
  4169. smartlist_free(auth_clients);
  4170. }
  4171. if (auth_created_clients) {
  4172. // Do not free entries; they are the same as auth_clients
  4173. smartlist_free(auth_created_clients);
  4174. }
  4175. SMARTLIST_FOREACH(args, char *, cp, {
  4176. memwipe(cp, 0, strlen(cp));
  4177. tor_free(cp);
  4178. });
  4179. smartlist_free(args);
  4180. return 0;
  4181. }
  4182. /** Helper function to handle parsing the KeyType:KeyBlob argument to the
  4183. * ADD_ONION command. Return a new crypto_pk_t and if a new key was generated
  4184. * and the private key not discarded, the algorithm and serialized private key,
  4185. * or NULL and an optional control protocol error message on failure. The
  4186. * caller is responsible for freeing the returned key_new_blob and err_msg.
  4187. *
  4188. * Note: The error messages returned are deliberately vague to avoid echoing
  4189. * key material.
  4190. */
  4191. STATIC crypto_pk_t *
  4192. add_onion_helper_keyarg(const char *arg, int discard_pk,
  4193. const char **key_new_alg_out, char **key_new_blob_out,
  4194. char **err_msg_out)
  4195. {
  4196. smartlist_t *key_args = smartlist_new();
  4197. crypto_pk_t *pk = NULL;
  4198. const char *key_new_alg = NULL;
  4199. char *key_new_blob = NULL;
  4200. char *err_msg = NULL;
  4201. int ok = 0;
  4202. smartlist_split_string(key_args, arg, ":", SPLIT_IGNORE_BLANK, 0);
  4203. if (smartlist_len(key_args) != 2) {
  4204. err_msg = tor_strdup("512 Invalid key type/blob\r\n");
  4205. goto err;
  4206. }
  4207. /* The format is "KeyType:KeyBlob". */
  4208. static const char *key_type_new = "NEW";
  4209. static const char *key_type_best = "BEST";
  4210. static const char *key_type_rsa1024 = "RSA1024";
  4211. const char *key_type = smartlist_get(key_args, 0);
  4212. const char *key_blob = smartlist_get(key_args, 1);
  4213. if (!strcasecmp(key_type_rsa1024, key_type)) {
  4214. /* "RSA:<Base64 Blob>" - Loading a pre-existing RSA1024 key. */
  4215. pk = crypto_pk_base64_decode(key_blob, strlen(key_blob));
  4216. if (!pk) {
  4217. err_msg = tor_strdup("512 Failed to decode RSA key\r\n");
  4218. goto err;
  4219. }
  4220. if (crypto_pk_num_bits(pk) != PK_BYTES*8) {
  4221. err_msg = tor_strdup("512 Invalid RSA key size\r\n");
  4222. goto err;
  4223. }
  4224. } else if (!strcasecmp(key_type_new, key_type)) {
  4225. /* "NEW:<Algorithm>" - Generating a new key, blob as algorithm. */
  4226. if (!strcasecmp(key_type_rsa1024, key_blob) ||
  4227. !strcasecmp(key_type_best, key_blob)) {
  4228. /* "RSA1024", RSA 1024 bit, also currently "BEST" by default. */
  4229. pk = crypto_pk_new();
  4230. if (crypto_pk_generate_key(pk)) {
  4231. tor_asprintf(&err_msg, "551 Failed to generate %s key\r\n",
  4232. key_type_rsa1024);
  4233. goto err;
  4234. }
  4235. if (!discard_pk) {
  4236. if (crypto_pk_base64_encode(pk, &key_new_blob)) {
  4237. tor_asprintf(&err_msg, "551 Failed to encode %s key\r\n",
  4238. key_type_rsa1024);
  4239. goto err;
  4240. }
  4241. key_new_alg = key_type_rsa1024;
  4242. }
  4243. } else {
  4244. err_msg = tor_strdup("513 Invalid key type\r\n");
  4245. goto err;
  4246. }
  4247. } else {
  4248. err_msg = tor_strdup("513 Invalid key type\r\n");
  4249. goto err;
  4250. }
  4251. /* Succeded in loading or generating a private key. */
  4252. tor_assert(pk);
  4253. ok = 1;
  4254. err:
  4255. SMARTLIST_FOREACH(key_args, char *, cp, {
  4256. memwipe(cp, 0, strlen(cp));
  4257. tor_free(cp);
  4258. });
  4259. smartlist_free(key_args);
  4260. if (!ok) {
  4261. crypto_pk_free(pk);
  4262. pk = NULL;
  4263. }
  4264. if (err_msg_out) {
  4265. *err_msg_out = err_msg;
  4266. } else {
  4267. tor_free(err_msg);
  4268. }
  4269. *key_new_alg_out = key_new_alg;
  4270. *key_new_blob_out = key_new_blob;
  4271. return pk;
  4272. }
  4273. /** Helper function to handle parsing a ClientAuth argument to the
  4274. * ADD_ONION command. Return a new rend_authorized_client_t, or NULL
  4275. * and an optional control protocol error message on failure. The
  4276. * caller is responsible for freeing the returned auth_client and err_msg.
  4277. *
  4278. * If 'created' is specified, it will be set to 1 when a new cookie has
  4279. * been generated.
  4280. */
  4281. STATIC rend_authorized_client_t *
  4282. add_onion_helper_clientauth(const char *arg, int *created, char **err_msg)
  4283. {
  4284. int ok = 0;
  4285. tor_assert(arg);
  4286. tor_assert(created);
  4287. tor_assert(err_msg);
  4288. *err_msg = NULL;
  4289. smartlist_t *auth_args = smartlist_new();
  4290. rend_authorized_client_t *client =
  4291. tor_malloc_zero(sizeof(rend_authorized_client_t));
  4292. smartlist_split_string(auth_args, arg, ":", 0, 0);
  4293. if (smartlist_len(auth_args) < 1 || smartlist_len(auth_args) > 2) {
  4294. *err_msg = tor_strdup("512 Invalid ClientAuth syntax\r\n");
  4295. goto err;
  4296. }
  4297. client->client_name = tor_strdup(smartlist_get(auth_args, 0));
  4298. if (smartlist_len(auth_args) == 2) {
  4299. char *decode_err_msg = NULL;
  4300. if (rend_auth_decode_cookie(smartlist_get(auth_args, 1),
  4301. client->descriptor_cookie,
  4302. NULL, &decode_err_msg) < 0) {
  4303. tor_assert(decode_err_msg);
  4304. tor_asprintf(err_msg, "512 %s\r\n", decode_err_msg);
  4305. tor_free(decode_err_msg);
  4306. goto err;
  4307. }
  4308. *created = 0;
  4309. } else {
  4310. crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
  4311. *created = 1;
  4312. }
  4313. if (!rend_valid_client_name(client->client_name)) {
  4314. *err_msg = tor_strdup("512 Invalid name in ClientAuth\r\n");
  4315. goto err;
  4316. }
  4317. ok = 1;
  4318. err:
  4319. SMARTLIST_FOREACH(auth_args, char *, item, tor_free(item));
  4320. smartlist_free(auth_args);
  4321. if (!ok) {
  4322. rend_authorized_client_free(client);
  4323. client = NULL;
  4324. }
  4325. return client;
  4326. }
  4327. /** Called when we get a DEL_ONION command; parse the body, and remove
  4328. * the existing ephemeral Onion Service. */
  4329. static int
  4330. handle_control_del_onion(control_connection_t *conn,
  4331. uint32_t len,
  4332. const char *body)
  4333. {
  4334. smartlist_t *args;
  4335. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  4336. args = getargs_helper("DEL_ONION", conn, body, 1, 1);
  4337. if (!args)
  4338. return 0;
  4339. const char *service_id = smartlist_get(args, 0);
  4340. if (!rend_valid_service_id(service_id)) {
  4341. connection_printf_to_buf(conn, "512 Malformed Onion Service id\r\n");
  4342. goto out;
  4343. }
  4344. /* Determine if the onion service belongs to this particular control
  4345. * connection, or if it is in the global list of detached services. If it
  4346. * is in neither, either the service ID is invalid in some way, or it
  4347. * explicitly belongs to a different control connection, and an error
  4348. * should be returned.
  4349. */
  4350. smartlist_t *services[2] = {
  4351. conn->ephemeral_onion_services,
  4352. detached_onion_services
  4353. };
  4354. smartlist_t *onion_services = NULL;
  4355. int idx = -1;
  4356. for (size_t i = 0; i < ARRAY_LENGTH(services); i++) {
  4357. idx = smartlist_string_pos(services[i], service_id);
  4358. if (idx != -1) {
  4359. onion_services = services[i];
  4360. break;
  4361. }
  4362. }
  4363. if (onion_services == NULL) {
  4364. connection_printf_to_buf(conn, "552 Unknown Onion Service id\r\n");
  4365. } else {
  4366. int ret = rend_service_del_ephemeral(service_id);
  4367. if (ret) {
  4368. /* This should *NEVER* fail, since the service is on either the
  4369. * per-control connection list, or the global one.
  4370. */
  4371. log_warn(LD_BUG, "Failed to remove Onion Service %s.",
  4372. escaped(service_id));
  4373. tor_fragile_assert();
  4374. }
  4375. /* Remove/scrub the service_id from the appropriate list. */
  4376. char *cp = smartlist_get(onion_services, idx);
  4377. smartlist_del(onion_services, idx);
  4378. memwipe(cp, 0, strlen(cp));
  4379. tor_free(cp);
  4380. send_control_done(conn);
  4381. }
  4382. out:
  4383. SMARTLIST_FOREACH(args, char *, cp, {
  4384. memwipe(cp, 0, strlen(cp));
  4385. tor_free(cp);
  4386. });
  4387. smartlist_free(args);
  4388. return 0;
  4389. }
  4390. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  4391. int
  4392. connection_control_finished_flushing(control_connection_t *conn)
  4393. {
  4394. tor_assert(conn);
  4395. return 0;
  4396. }
  4397. /** Called when <b>conn</b> has gotten its socket closed. */
  4398. int
  4399. connection_control_reached_eof(control_connection_t *conn)
  4400. {
  4401. tor_assert(conn);
  4402. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  4403. connection_mark_for_close(TO_CONN(conn));
  4404. return 0;
  4405. }
  4406. /** Shut down this Tor instance in the same way that SIGINT would, but
  4407. * with a log message appropriate for the loss of an owning controller. */
  4408. static void
  4409. lost_owning_controller(const char *owner_type, const char *loss_manner)
  4410. {
  4411. log_notice(LD_CONTROL, "Owning controller %s has %s -- exiting now.",
  4412. owner_type, loss_manner);
  4413. activate_signal(SIGTERM);
  4414. }
  4415. /** Called when <b>conn</b> is being freed. */
  4416. void
  4417. connection_control_closed(control_connection_t *conn)
  4418. {
  4419. tor_assert(conn);
  4420. conn->event_mask = 0;
  4421. control_update_global_event_mask();
  4422. /* Close all ephemeral Onion Services if any.
  4423. * The list and it's contents are scrubbed/freed in connection_free_.
  4424. */
  4425. if (conn->ephemeral_onion_services) {
  4426. SMARTLIST_FOREACH(conn->ephemeral_onion_services, char *, cp, {
  4427. rend_service_del_ephemeral(cp);
  4428. });
  4429. }
  4430. if (conn->is_owning_control_connection) {
  4431. lost_owning_controller("connection", "closed");
  4432. }
  4433. }
  4434. /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
  4435. * stage of the protocol. */
  4436. static int
  4437. is_valid_initial_command(control_connection_t *conn, const char *cmd)
  4438. {
  4439. if (conn->base_.state == CONTROL_CONN_STATE_OPEN)
  4440. return 1;
  4441. if (!strcasecmp(cmd, "PROTOCOLINFO"))
  4442. return (!conn->have_sent_protocolinfo &&
  4443. conn->safecookie_client_hash == NULL);
  4444. if (!strcasecmp(cmd, "AUTHCHALLENGE"))
  4445. return (conn->safecookie_client_hash == NULL);
  4446. if (!strcasecmp(cmd, "AUTHENTICATE") ||
  4447. !strcasecmp(cmd, "QUIT"))
  4448. return 1;
  4449. return 0;
  4450. }
  4451. /** Do not accept any control command of more than 1MB in length. Anything
  4452. * that needs to be anywhere near this long probably means that one of our
  4453. * interfaces is broken. */
  4454. #define MAX_COMMAND_LINE_LENGTH (1024*1024)
  4455. /** Wrapper around peek_buf_has_control0 command: presents the same
  4456. * interface as that underlying functions, but takes a connection_t intead of
  4457. * a buf_t.
  4458. */
  4459. static int
  4460. peek_connection_has_control0_command(connection_t *conn)
  4461. {
  4462. return peek_buf_has_control0_command(conn->inbuf);
  4463. }
  4464. /** Called when data has arrived on a v1 control connection: Try to fetch
  4465. * commands from conn->inbuf, and execute them.
  4466. */
  4467. int
  4468. connection_control_process_inbuf(control_connection_t *conn)
  4469. {
  4470. size_t data_len;
  4471. uint32_t cmd_data_len;
  4472. int cmd_len;
  4473. char *args;
  4474. tor_assert(conn);
  4475. tor_assert(conn->base_.state == CONTROL_CONN_STATE_OPEN ||
  4476. conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH);
  4477. if (!conn->incoming_cmd) {
  4478. conn->incoming_cmd = tor_malloc(1024);
  4479. conn->incoming_cmd_len = 1024;
  4480. conn->incoming_cmd_cur_len = 0;
  4481. }
  4482. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  4483. peek_connection_has_control0_command(TO_CONN(conn))) {
  4484. /* Detect v0 commands and send a "no more v0" message. */
  4485. size_t body_len;
  4486. char buf[128];
  4487. set_uint16(buf+2, htons(0x0000)); /* type == error */
  4488. set_uint16(buf+4, htons(0x0001)); /* code == internal error */
  4489. strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
  4490. "and later; upgrade your controller.",
  4491. sizeof(buf)-6);
  4492. body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
  4493. set_uint16(buf+0, htons(body_len));
  4494. connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
  4495. connection_mark_and_flush(TO_CONN(conn));
  4496. return 0;
  4497. }
  4498. again:
  4499. while (1) {
  4500. size_t last_idx;
  4501. int r;
  4502. /* First, fetch a line. */
  4503. do {
  4504. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  4505. r = connection_fetch_from_buf_line(TO_CONN(conn),
  4506. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  4507. &data_len);
  4508. if (r == 0)
  4509. /* Line not all here yet. Wait. */
  4510. return 0;
  4511. else if (r == -1) {
  4512. if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
  4513. connection_write_str_to_buf("500 Line too long.\r\n", conn);
  4514. connection_stop_reading(TO_CONN(conn));
  4515. connection_mark_and_flush(TO_CONN(conn));
  4516. }
  4517. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  4518. conn->incoming_cmd_len *= 2;
  4519. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  4520. conn->incoming_cmd_len);
  4521. }
  4522. } while (r != 1);
  4523. tor_assert(data_len);
  4524. last_idx = conn->incoming_cmd_cur_len;
  4525. conn->incoming_cmd_cur_len += (int)data_len;
  4526. /* We have appended a line to incoming_cmd. Is the command done? */
  4527. if (last_idx == 0 && *conn->incoming_cmd != '+')
  4528. /* One line command, didn't start with '+'. */
  4529. break;
  4530. /* XXXX this code duplication is kind of dumb. */
  4531. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  4532. tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  4533. /* Just appended ".\r\n"; we're done. Remove it. */
  4534. conn->incoming_cmd[last_idx] = '\0';
  4535. conn->incoming_cmd_cur_len -= 3;
  4536. break;
  4537. } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
  4538. tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
  4539. /* Just appended ".\n"; we're done. Remove it. */
  4540. conn->incoming_cmd[last_idx] = '\0';
  4541. conn->incoming_cmd_cur_len -= 2;
  4542. break;
  4543. }
  4544. /* Otherwise, read another line. */
  4545. }
  4546. data_len = conn->incoming_cmd_cur_len;
  4547. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  4548. * recognize it.
  4549. */
  4550. cmd_len = 0;
  4551. while ((size_t)cmd_len < data_len
  4552. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  4553. ++cmd_len;
  4554. conn->incoming_cmd[cmd_len]='\0';
  4555. args = conn->incoming_cmd+cmd_len+1;
  4556. tor_assert(data_len>(size_t)cmd_len);
  4557. data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
  4558. while (TOR_ISSPACE(*args)) {
  4559. ++args;
  4560. --data_len;
  4561. }
  4562. /* If the connection is already closing, ignore further commands */
  4563. if (TO_CONN(conn)->marked_for_close) {
  4564. return 0;
  4565. }
  4566. /* Otherwise, Quit is always valid. */
  4567. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  4568. connection_write_str_to_buf("250 closing connection\r\n", conn);
  4569. connection_mark_and_flush(TO_CONN(conn));
  4570. return 0;
  4571. }
  4572. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  4573. !is_valid_initial_command(conn, conn->incoming_cmd)) {
  4574. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  4575. connection_mark_for_close(TO_CONN(conn));
  4576. return 0;
  4577. }
  4578. if (data_len >= UINT32_MAX) {
  4579. connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
  4580. connection_mark_for_close(TO_CONN(conn));
  4581. return 0;
  4582. }
  4583. /* XXXX Why is this not implemented as a table like the GETINFO
  4584. * items are? Even handling the plus signs at the beginnings of
  4585. * commands wouldn't be very hard with proper macros. */
  4586. cmd_data_len = (uint32_t)data_len;
  4587. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  4588. if (handle_control_setconf(conn, cmd_data_len, args))
  4589. return -1;
  4590. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  4591. if (handle_control_resetconf(conn, cmd_data_len, args))
  4592. return -1;
  4593. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  4594. if (handle_control_getconf(conn, cmd_data_len, args))
  4595. return -1;
  4596. } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
  4597. if (handle_control_loadconf(conn, cmd_data_len, args))
  4598. return -1;
  4599. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  4600. if (handle_control_setevents(conn, cmd_data_len, args))
  4601. return -1;
  4602. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  4603. if (handle_control_authenticate(conn, cmd_data_len, args))
  4604. return -1;
  4605. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  4606. if (handle_control_saveconf(conn, cmd_data_len, args))
  4607. return -1;
  4608. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  4609. if (handle_control_signal(conn, cmd_data_len, args))
  4610. return -1;
  4611. } else if (!strcasecmp(conn->incoming_cmd, "TAKEOWNERSHIP")) {
  4612. if (handle_control_takeownership(conn, cmd_data_len, args))
  4613. return -1;
  4614. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  4615. if (handle_control_mapaddress(conn, cmd_data_len, args))
  4616. return -1;
  4617. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  4618. if (handle_control_getinfo(conn, cmd_data_len, args))
  4619. return -1;
  4620. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  4621. if (handle_control_extendcircuit(conn, cmd_data_len, args))
  4622. return -1;
  4623. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  4624. if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
  4625. return -1;
  4626. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  4627. connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
  4628. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  4629. if (handle_control_attachstream(conn, cmd_data_len, args))
  4630. return -1;
  4631. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  4632. if (handle_control_postdescriptor(conn, cmd_data_len, args))
  4633. return -1;
  4634. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  4635. if (handle_control_redirectstream(conn, cmd_data_len, args))
  4636. return -1;
  4637. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  4638. if (handle_control_closestream(conn, cmd_data_len, args))
  4639. return -1;
  4640. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  4641. if (handle_control_closecircuit(conn, cmd_data_len, args))
  4642. return -1;
  4643. } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
  4644. if (handle_control_usefeature(conn, cmd_data_len, args))
  4645. return -1;
  4646. } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
  4647. if (handle_control_resolve(conn, cmd_data_len, args))
  4648. return -1;
  4649. } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
  4650. if (handle_control_protocolinfo(conn, cmd_data_len, args))
  4651. return -1;
  4652. } else if (!strcasecmp(conn->incoming_cmd, "AUTHCHALLENGE")) {
  4653. if (handle_control_authchallenge(conn, cmd_data_len, args))
  4654. return -1;
  4655. } else if (!strcasecmp(conn->incoming_cmd, "DROPGUARDS")) {
  4656. if (handle_control_dropguards(conn, cmd_data_len, args))
  4657. return -1;
  4658. } else if (!strcasecmp(conn->incoming_cmd, "HSFETCH")) {
  4659. if (handle_control_hsfetch(conn, cmd_data_len, args))
  4660. return -1;
  4661. } else if (!strcasecmp(conn->incoming_cmd, "+HSPOST")) {
  4662. if (handle_control_hspost(conn, cmd_data_len, args))
  4663. return -1;
  4664. } else if (!strcasecmp(conn->incoming_cmd, "ADD_ONION")) {
  4665. int ret = handle_control_add_onion(conn, cmd_data_len, args);
  4666. memwipe(args, 0, cmd_data_len); /* Scrub the private key. */
  4667. if (ret)
  4668. return -1;
  4669. } else if (!strcasecmp(conn->incoming_cmd, "DEL_ONION")) {
  4670. int ret = handle_control_del_onion(conn, cmd_data_len, args);
  4671. memwipe(args, 0, cmd_data_len); /* Scrub the service id/pk. */
  4672. if (ret)
  4673. return -1;
  4674. } else {
  4675. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  4676. conn->incoming_cmd);
  4677. }
  4678. conn->incoming_cmd_cur_len = 0;
  4679. goto again;
  4680. }
  4681. /** Something major has happened to circuit <b>circ</b>: tell any
  4682. * interested control connections. */
  4683. int
  4684. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
  4685. int reason_code)
  4686. {
  4687. const char *status;
  4688. char reasons[64] = "";
  4689. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  4690. return 0;
  4691. tor_assert(circ);
  4692. switch (tp)
  4693. {
  4694. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  4695. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  4696. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  4697. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  4698. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  4699. default:
  4700. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  4701. tor_fragile_assert();
  4702. return 0;
  4703. }
  4704. if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
  4705. const char *reason_str = circuit_end_reason_to_control_string(reason_code);
  4706. char unk_reason_buf[16];
  4707. if (!reason_str) {
  4708. tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
  4709. reason_str = unk_reason_buf;
  4710. }
  4711. if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
  4712. tor_snprintf(reasons, sizeof(reasons),
  4713. " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
  4714. } else {
  4715. tor_snprintf(reasons, sizeof(reasons),
  4716. " REASON=%s", reason_str);
  4717. }
  4718. }
  4719. {
  4720. char *circdesc = circuit_describe_status_for_controller(circ);
  4721. const char *sp = strlen(circdesc) ? " " : "";
  4722. send_control_event(EVENT_CIRCUIT_STATUS,
  4723. "650 CIRC %lu %s%s%s%s\r\n",
  4724. (unsigned long)circ->global_identifier,
  4725. status, sp,
  4726. circdesc,
  4727. reasons);
  4728. tor_free(circdesc);
  4729. }
  4730. return 0;
  4731. }
  4732. /** Something minor has happened to circuit <b>circ</b>: tell any
  4733. * interested control connections. */
  4734. static int
  4735. control_event_circuit_status_minor(origin_circuit_t *circ,
  4736. circuit_status_minor_event_t e,
  4737. int purpose, const struct timeval *tv)
  4738. {
  4739. const char *event_desc;
  4740. char event_tail[160] = "";
  4741. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
  4742. return 0;
  4743. tor_assert(circ);
  4744. switch (e)
  4745. {
  4746. case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
  4747. event_desc = "PURPOSE_CHANGED";
  4748. {
  4749. /* event_tail can currently be up to 68 chars long */
  4750. const char *hs_state_str =
  4751. circuit_purpose_to_controller_hs_state_string(purpose);
  4752. tor_snprintf(event_tail, sizeof(event_tail),
  4753. " OLD_PURPOSE=%s%s%s",
  4754. circuit_purpose_to_controller_string(purpose),
  4755. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  4756. (hs_state_str != NULL) ? hs_state_str : "");
  4757. }
  4758. break;
  4759. case CIRC_MINOR_EVENT_CANNIBALIZED:
  4760. event_desc = "CANNIBALIZED";
  4761. {
  4762. /* event_tail can currently be up to 130 chars long */
  4763. const char *hs_state_str =
  4764. circuit_purpose_to_controller_hs_state_string(purpose);
  4765. const struct timeval *old_timestamp_began = tv;
  4766. char tbuf[ISO_TIME_USEC_LEN+1];
  4767. format_iso_time_nospace_usec(tbuf, old_timestamp_began);
  4768. tor_snprintf(event_tail, sizeof(event_tail),
  4769. " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
  4770. circuit_purpose_to_controller_string(purpose),
  4771. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  4772. (hs_state_str != NULL) ? hs_state_str : "",
  4773. tbuf);
  4774. }
  4775. break;
  4776. default:
  4777. log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
  4778. tor_fragile_assert();
  4779. return 0;
  4780. }
  4781. {
  4782. char *circdesc = circuit_describe_status_for_controller(circ);
  4783. const char *sp = strlen(circdesc) ? " " : "";
  4784. send_control_event(EVENT_CIRCUIT_STATUS_MINOR,
  4785. "650 CIRC_MINOR %lu %s%s%s%s\r\n",
  4786. (unsigned long)circ->global_identifier,
  4787. event_desc, sp,
  4788. circdesc,
  4789. event_tail);
  4790. tor_free(circdesc);
  4791. }
  4792. return 0;
  4793. }
  4794. /**
  4795. * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
  4796. * interested controllers.
  4797. */
  4798. int
  4799. control_event_circuit_purpose_changed(origin_circuit_t *circ,
  4800. int old_purpose)
  4801. {
  4802. return control_event_circuit_status_minor(circ,
  4803. CIRC_MINOR_EVENT_PURPOSE_CHANGED,
  4804. old_purpose,
  4805. NULL);
  4806. }
  4807. /**
  4808. * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
  4809. * created-time from <b>old_tv_created</b>: tell any interested controllers.
  4810. */
  4811. int
  4812. control_event_circuit_cannibalized(origin_circuit_t *circ,
  4813. int old_purpose,
  4814. const struct timeval *old_tv_created)
  4815. {
  4816. return control_event_circuit_status_minor(circ,
  4817. CIRC_MINOR_EVENT_CANNIBALIZED,
  4818. old_purpose,
  4819. old_tv_created);
  4820. }
  4821. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  4822. * <b>buf</b>, determine the address:port combination requested on
  4823. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  4824. * failure. */
  4825. static int
  4826. write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
  4827. {
  4828. char buf2[256];
  4829. if (conn->chosen_exit_name)
  4830. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  4831. return -1;
  4832. if (!conn->socks_request)
  4833. return -1;
  4834. if (tor_snprintf(buf, len, "%s%s%s:%d",
  4835. conn->socks_request->address,
  4836. conn->chosen_exit_name ? buf2 : "",
  4837. !conn->chosen_exit_name && connection_edge_is_rendezvous_stream(
  4838. ENTRY_TO_EDGE_CONN(conn)) ? ".onion" : "",
  4839. conn->socks_request->port)<0)
  4840. return -1;
  4841. return 0;
  4842. }
  4843. /** Something has happened to the stream associated with AP connection
  4844. * <b>conn</b>: tell any interested control connections. */
  4845. int
  4846. control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
  4847. int reason_code)
  4848. {
  4849. char reason_buf[64];
  4850. char addrport_buf[64];
  4851. const char *status;
  4852. circuit_t *circ;
  4853. origin_circuit_t *origin_circ = NULL;
  4854. char buf[256];
  4855. const char *purpose = "";
  4856. tor_assert(conn->socks_request);
  4857. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  4858. return 0;
  4859. if (tp == STREAM_EVENT_CLOSED &&
  4860. (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
  4861. return 0;
  4862. write_stream_target_to_buf(conn, buf, sizeof(buf));
  4863. reason_buf[0] = '\0';
  4864. switch (tp)
  4865. {
  4866. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  4867. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  4868. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  4869. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  4870. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  4871. case STREAM_EVENT_NEW: status = "NEW"; break;
  4872. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  4873. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  4874. case STREAM_EVENT_REMAP: status = "REMAP"; break;
  4875. default:
  4876. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  4877. return 0;
  4878. }
  4879. if (reason_code && (tp == STREAM_EVENT_FAILED ||
  4880. tp == STREAM_EVENT_CLOSED ||
  4881. tp == STREAM_EVENT_FAILED_RETRIABLE)) {
  4882. const char *reason_str = stream_end_reason_to_control_string(reason_code);
  4883. char *r = NULL;
  4884. if (!reason_str) {
  4885. tor_asprintf(&r, " UNKNOWN_%d", reason_code);
  4886. reason_str = r;
  4887. }
  4888. if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
  4889. tor_snprintf(reason_buf, sizeof(reason_buf),
  4890. " REASON=END REMOTE_REASON=%s", reason_str);
  4891. else
  4892. tor_snprintf(reason_buf, sizeof(reason_buf),
  4893. " REASON=%s", reason_str);
  4894. tor_free(r);
  4895. } else if (reason_code && tp == STREAM_EVENT_REMAP) {
  4896. switch (reason_code) {
  4897. case REMAP_STREAM_SOURCE_CACHE:
  4898. strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
  4899. break;
  4900. case REMAP_STREAM_SOURCE_EXIT:
  4901. strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
  4902. break;
  4903. default:
  4904. tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
  4905. reason_code);
  4906. /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
  4907. break;
  4908. }
  4909. }
  4910. if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
  4911. /*
  4912. * When the control conn is an AF_UNIX socket and we have no address,
  4913. * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
  4914. * dnsserv.c.
  4915. */
  4916. if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
  4917. tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
  4918. ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
  4919. } else {
  4920. /*
  4921. * else leave it blank so control on AF_UNIX doesn't need to make
  4922. * something up.
  4923. */
  4924. addrport_buf[0] = '\0';
  4925. }
  4926. } else {
  4927. addrport_buf[0] = '\0';
  4928. }
  4929. if (tp == STREAM_EVENT_NEW_RESOLVE) {
  4930. purpose = " PURPOSE=DNS_REQUEST";
  4931. } else if (tp == STREAM_EVENT_NEW) {
  4932. if (conn->use_begindir) {
  4933. connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
  4934. int linked_dir_purpose = -1;
  4935. if (linked && linked->type == CONN_TYPE_DIR)
  4936. linked_dir_purpose = linked->purpose;
  4937. if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
  4938. purpose = " PURPOSE=DIR_UPLOAD";
  4939. else
  4940. purpose = " PURPOSE=DIR_FETCH";
  4941. } else
  4942. purpose = " PURPOSE=USER";
  4943. }
  4944. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  4945. if (circ && CIRCUIT_IS_ORIGIN(circ))
  4946. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  4947. send_control_event(EVENT_STREAM_STATUS,
  4948. "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
  4949. U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
  4950. status,
  4951. origin_circ?
  4952. (unsigned long)origin_circ->global_identifier : 0ul,
  4953. buf, reason_buf, addrport_buf, purpose);
  4954. /* XXX need to specify its intended exit, etc? */
  4955. return 0;
  4956. }
  4957. /** Figure out the best name for the target router of an OR connection
  4958. * <b>conn</b>, and write it into the <b>len</b>-character buffer
  4959. * <b>name</b>. */
  4960. static void
  4961. orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
  4962. {
  4963. const node_t *node = node_get_by_id(conn->identity_digest);
  4964. if (node) {
  4965. tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
  4966. node_get_verbose_nickname(node, name);
  4967. } else if (! tor_digest_is_zero(conn->identity_digest)) {
  4968. name[0] = '$';
  4969. base16_encode(name+1, len-1, conn->identity_digest,
  4970. DIGEST_LEN);
  4971. } else {
  4972. tor_snprintf(name, len, "%s:%d",
  4973. conn->base_.address, conn->base_.port);
  4974. }
  4975. }
  4976. /** Called when the status of an OR connection <b>conn</b> changes: tell any
  4977. * interested control connections. <b>tp</b> is the new status for the
  4978. * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
  4979. * may be the reason why.
  4980. */
  4981. int
  4982. control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
  4983. int reason)
  4984. {
  4985. int ncircs = 0;
  4986. const char *status;
  4987. char name[128];
  4988. char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
  4989. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  4990. return 0;
  4991. switch (tp)
  4992. {
  4993. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  4994. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  4995. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  4996. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  4997. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  4998. default:
  4999. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  5000. return 0;
  5001. }
  5002. if (conn->chan) {
  5003. ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
  5004. } else {
  5005. ncircs = 0;
  5006. }
  5007. ncircs += connection_or_get_num_circuits(conn);
  5008. if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
  5009. tor_snprintf(ncircs_buf, sizeof(ncircs_buf), " NCIRCS=%d", ncircs);
  5010. }
  5011. orconn_target_get_name(name, sizeof(name), conn);
  5012. send_control_event(EVENT_OR_CONN_STATUS,
  5013. "650 ORCONN %s %s%s%s%s ID="U64_FORMAT"\r\n",
  5014. name, status,
  5015. reason ? " REASON=" : "",
  5016. orconn_end_reason_to_control_string(reason),
  5017. ncircs_buf,
  5018. U64_PRINTF_ARG(conn->base_.global_identifier));
  5019. return 0;
  5020. }
  5021. /**
  5022. * Print out STREAM_BW event for a single conn
  5023. */
  5024. int
  5025. control_event_stream_bandwidth(edge_connection_t *edge_conn)
  5026. {
  5027. circuit_t *circ;
  5028. origin_circuit_t *ocirc;
  5029. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  5030. if (!edge_conn->n_read && !edge_conn->n_written)
  5031. return 0;
  5032. send_control_event(EVENT_STREAM_BANDWIDTH_USED,
  5033. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  5034. U64_PRINTF_ARG(edge_conn->base_.global_identifier),
  5035. (unsigned long)edge_conn->n_read,
  5036. (unsigned long)edge_conn->n_written);
  5037. circ = circuit_get_by_edge_conn(edge_conn);
  5038. if (circ && CIRCUIT_IS_ORIGIN(circ)) {
  5039. ocirc = TO_ORIGIN_CIRCUIT(circ);
  5040. ocirc->n_read_circ_bw += edge_conn->n_read;
  5041. ocirc->n_written_circ_bw += edge_conn->n_written;
  5042. }
  5043. edge_conn->n_written = edge_conn->n_read = 0;
  5044. }
  5045. return 0;
  5046. }
  5047. /** A second or more has elapsed: tell any interested control
  5048. * connections how much bandwidth streams have used. */
  5049. int
  5050. control_event_stream_bandwidth_used(void)
  5051. {
  5052. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  5053. smartlist_t *conns = get_connection_array();
  5054. edge_connection_t *edge_conn;
  5055. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
  5056. {
  5057. if (conn->type != CONN_TYPE_AP)
  5058. continue;
  5059. edge_conn = TO_EDGE_CONN(conn);
  5060. if (!edge_conn->n_read && !edge_conn->n_written)
  5061. continue;
  5062. send_control_event(EVENT_STREAM_BANDWIDTH_USED,
  5063. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  5064. U64_PRINTF_ARG(edge_conn->base_.global_identifier),
  5065. (unsigned long)edge_conn->n_read,
  5066. (unsigned long)edge_conn->n_written);
  5067. edge_conn->n_written = edge_conn->n_read = 0;
  5068. }
  5069. SMARTLIST_FOREACH_END(conn);
  5070. }
  5071. return 0;
  5072. }
  5073. /** A second or more has elapsed: tell any interested control connections
  5074. * how much bandwidth origin circuits have used. */
  5075. int
  5076. control_event_circ_bandwidth_used(void)
  5077. {
  5078. origin_circuit_t *ocirc;
  5079. if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
  5080. return 0;
  5081. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  5082. if (!CIRCUIT_IS_ORIGIN(circ))
  5083. continue;
  5084. ocirc = TO_ORIGIN_CIRCUIT(circ);
  5085. if (!ocirc->n_read_circ_bw && !ocirc->n_written_circ_bw)
  5086. continue;
  5087. send_control_event(EVENT_CIRC_BANDWIDTH_USED,
  5088. "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu\r\n",
  5089. ocirc->global_identifier,
  5090. (unsigned long)ocirc->n_read_circ_bw,
  5091. (unsigned long)ocirc->n_written_circ_bw);
  5092. ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
  5093. }
  5094. SMARTLIST_FOREACH_END(circ);
  5095. return 0;
  5096. }
  5097. /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
  5098. * bandwidth counters. */
  5099. int
  5100. control_event_conn_bandwidth(connection_t *conn)
  5101. {
  5102. const char *conn_type_str;
  5103. if (!get_options()->TestingEnableConnBwEvent ||
  5104. !EVENT_IS_INTERESTING(EVENT_CONN_BW))
  5105. return 0;
  5106. if (!conn->n_read_conn_bw && !conn->n_written_conn_bw)
  5107. return 0;
  5108. switch (conn->type) {
  5109. case CONN_TYPE_OR:
  5110. conn_type_str = "OR";
  5111. break;
  5112. case CONN_TYPE_DIR:
  5113. conn_type_str = "DIR";
  5114. break;
  5115. case CONN_TYPE_EXIT:
  5116. conn_type_str = "EXIT";
  5117. break;
  5118. default:
  5119. return 0;
  5120. }
  5121. send_control_event(EVENT_CONN_BW,
  5122. "650 CONN_BW ID="U64_FORMAT" TYPE=%s "
  5123. "READ=%lu WRITTEN=%lu\r\n",
  5124. U64_PRINTF_ARG(conn->global_identifier),
  5125. conn_type_str,
  5126. (unsigned long)conn->n_read_conn_bw,
  5127. (unsigned long)conn->n_written_conn_bw);
  5128. conn->n_written_conn_bw = conn->n_read_conn_bw = 0;
  5129. return 0;
  5130. }
  5131. /** A second or more has elapsed: tell any interested control
  5132. * connections how much bandwidth connections have used. */
  5133. int
  5134. control_event_conn_bandwidth_used(void)
  5135. {
  5136. if (get_options()->TestingEnableConnBwEvent &&
  5137. EVENT_IS_INTERESTING(EVENT_CONN_BW)) {
  5138. SMARTLIST_FOREACH(get_connection_array(), connection_t *, conn,
  5139. control_event_conn_bandwidth(conn));
  5140. }
  5141. return 0;
  5142. }
  5143. /** Helper: iterate over cell statistics of <b>circ</b> and sum up added
  5144. * cells, removed cells, and waiting times by cell command and direction.
  5145. * Store results in <b>cell_stats</b>. Free cell statistics of the
  5146. * circuit afterwards. */
  5147. void
  5148. sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
  5149. {
  5150. memset(cell_stats, 0, sizeof(cell_stats_t));
  5151. SMARTLIST_FOREACH_BEGIN(circ->testing_cell_stats,
  5152. const testing_cell_stats_entry_t *, ent) {
  5153. tor_assert(ent->command <= CELL_COMMAND_MAX_);
  5154. if (!ent->removed && !ent->exitward) {
  5155. cell_stats->added_cells_appward[ent->command] += 1;
  5156. } else if (!ent->removed && ent->exitward) {
  5157. cell_stats->added_cells_exitward[ent->command] += 1;
  5158. } else if (!ent->exitward) {
  5159. cell_stats->removed_cells_appward[ent->command] += 1;
  5160. cell_stats->total_time_appward[ent->command] += ent->waiting_time * 10;
  5161. } else {
  5162. cell_stats->removed_cells_exitward[ent->command] += 1;
  5163. cell_stats->total_time_exitward[ent->command] += ent->waiting_time * 10;
  5164. }
  5165. } SMARTLIST_FOREACH_END(ent);
  5166. circuit_clear_testing_cell_stats(circ);
  5167. }
  5168. /** Helper: append a cell statistics string to <code>event_parts</code>,
  5169. * prefixed with <code>key</code>=. Statistics consist of comma-separated
  5170. * key:value pairs with lower-case command strings as keys and cell
  5171. * numbers or total waiting times as values. A key:value pair is included
  5172. * if the entry in <code>include_if_non_zero</code> is not zero, but with
  5173. * the (possibly zero) entry from <code>number_to_include</code>. Both
  5174. * arrays are expected to have a length of CELL_COMMAND_MAX_ + 1. If no
  5175. * entry in <code>include_if_non_zero</code> is positive, no string will
  5176. * be added to <code>event_parts</code>. */
  5177. void
  5178. append_cell_stats_by_command(smartlist_t *event_parts, const char *key,
  5179. const uint64_t *include_if_non_zero,
  5180. const uint64_t *number_to_include)
  5181. {
  5182. smartlist_t *key_value_strings = smartlist_new();
  5183. int i;
  5184. for (i = 0; i <= CELL_COMMAND_MAX_; i++) {
  5185. if (include_if_non_zero[i] > 0) {
  5186. smartlist_add_asprintf(key_value_strings, "%s:"U64_FORMAT,
  5187. cell_command_to_string(i),
  5188. U64_PRINTF_ARG(number_to_include[i]));
  5189. }
  5190. }
  5191. if (smartlist_len(key_value_strings) > 0) {
  5192. char *joined = smartlist_join_strings(key_value_strings, ",", 0, NULL);
  5193. smartlist_add_asprintf(event_parts, "%s=%s", key, joined);
  5194. SMARTLIST_FOREACH(key_value_strings, char *, cp, tor_free(cp));
  5195. tor_free(joined);
  5196. }
  5197. smartlist_free(key_value_strings);
  5198. }
  5199. /** Helper: format <b>cell_stats</b> for <b>circ</b> for inclusion in a
  5200. * CELL_STATS event and write result string to <b>event_string</b>. */
  5201. void
  5202. format_cell_stats(char **event_string, circuit_t *circ,
  5203. cell_stats_t *cell_stats)
  5204. {
  5205. smartlist_t *event_parts = smartlist_new();
  5206. if (CIRCUIT_IS_ORIGIN(circ)) {
  5207. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  5208. smartlist_add_asprintf(event_parts, "ID=%lu",
  5209. (unsigned long)ocirc->global_identifier);
  5210. } else if (TO_OR_CIRCUIT(circ)->p_chan) {
  5211. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  5212. smartlist_add_asprintf(event_parts, "InboundQueue=%lu",
  5213. (unsigned long)or_circ->p_circ_id);
  5214. smartlist_add_asprintf(event_parts, "InboundConn="U64_FORMAT,
  5215. U64_PRINTF_ARG(or_circ->p_chan->global_identifier));
  5216. append_cell_stats_by_command(event_parts, "InboundAdded",
  5217. cell_stats->added_cells_appward,
  5218. cell_stats->added_cells_appward);
  5219. append_cell_stats_by_command(event_parts, "InboundRemoved",
  5220. cell_stats->removed_cells_appward,
  5221. cell_stats->removed_cells_appward);
  5222. append_cell_stats_by_command(event_parts, "InboundTime",
  5223. cell_stats->removed_cells_appward,
  5224. cell_stats->total_time_appward);
  5225. }
  5226. if (circ->n_chan) {
  5227. smartlist_add_asprintf(event_parts, "OutboundQueue=%lu",
  5228. (unsigned long)circ->n_circ_id);
  5229. smartlist_add_asprintf(event_parts, "OutboundConn="U64_FORMAT,
  5230. U64_PRINTF_ARG(circ->n_chan->global_identifier));
  5231. append_cell_stats_by_command(event_parts, "OutboundAdded",
  5232. cell_stats->added_cells_exitward,
  5233. cell_stats->added_cells_exitward);
  5234. append_cell_stats_by_command(event_parts, "OutboundRemoved",
  5235. cell_stats->removed_cells_exitward,
  5236. cell_stats->removed_cells_exitward);
  5237. append_cell_stats_by_command(event_parts, "OutboundTime",
  5238. cell_stats->removed_cells_exitward,
  5239. cell_stats->total_time_exitward);
  5240. }
  5241. *event_string = smartlist_join_strings(event_parts, " ", 0, NULL);
  5242. SMARTLIST_FOREACH(event_parts, char *, cp, tor_free(cp));
  5243. smartlist_free(event_parts);
  5244. }
  5245. /** A second or more has elapsed: tell any interested control connection
  5246. * how many cells have been processed for a given circuit. */
  5247. int
  5248. control_event_circuit_cell_stats(void)
  5249. {
  5250. cell_stats_t *cell_stats;
  5251. char *event_string;
  5252. if (!get_options()->TestingEnableCellStatsEvent ||
  5253. !EVENT_IS_INTERESTING(EVENT_CELL_STATS))
  5254. return 0;
  5255. cell_stats = tor_malloc(sizeof(cell_stats_t));;
  5256. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  5257. if (!circ->testing_cell_stats)
  5258. continue;
  5259. sum_up_cell_stats_by_command(circ, cell_stats);
  5260. format_cell_stats(&event_string, circ, cell_stats);
  5261. send_control_event(EVENT_CELL_STATS,
  5262. "650 CELL_STATS %s\r\n", event_string);
  5263. tor_free(event_string);
  5264. }
  5265. SMARTLIST_FOREACH_END(circ);
  5266. tor_free(cell_stats);
  5267. return 0;
  5268. }
  5269. /** Tokens in <b>bucket</b> have been refilled: the read bucket was empty
  5270. * for <b>read_empty_time</b> millis, the write bucket was empty for
  5271. * <b>write_empty_time</b> millis, and buckets were last refilled
  5272. * <b>milliseconds_elapsed</b> millis ago. Only emit TB_EMPTY event if
  5273. * either read or write bucket have been empty before. */
  5274. int
  5275. control_event_tb_empty(const char *bucket, uint32_t read_empty_time,
  5276. uint32_t write_empty_time,
  5277. int milliseconds_elapsed)
  5278. {
  5279. if (get_options()->TestingEnableTbEmptyEvent &&
  5280. EVENT_IS_INTERESTING(EVENT_TB_EMPTY) &&
  5281. (read_empty_time > 0 || write_empty_time > 0)) {
  5282. send_control_event(EVENT_TB_EMPTY,
  5283. "650 TB_EMPTY %s READ=%d WRITTEN=%d "
  5284. "LAST=%d\r\n",
  5285. bucket, read_empty_time, write_empty_time,
  5286. milliseconds_elapsed);
  5287. }
  5288. return 0;
  5289. }
  5290. /* about 5 minutes worth. */
  5291. #define N_BW_EVENTS_TO_CACHE 300
  5292. /* Index into cached_bw_events to next write. */
  5293. static int next_measurement_idx = 0;
  5294. /* number of entries set in n_measurements */
  5295. static int n_measurements = 0;
  5296. static struct cached_bw_event_s {
  5297. uint32_t n_read;
  5298. uint32_t n_written;
  5299. } cached_bw_events[N_BW_EVENTS_TO_CACHE];
  5300. /** A second or more has elapsed: tell any interested control
  5301. * connections how much bandwidth we used. */
  5302. int
  5303. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  5304. {
  5305. cached_bw_events[next_measurement_idx].n_read = n_read;
  5306. cached_bw_events[next_measurement_idx].n_written = n_written;
  5307. if (++next_measurement_idx == N_BW_EVENTS_TO_CACHE)
  5308. next_measurement_idx = 0;
  5309. if (n_measurements < N_BW_EVENTS_TO_CACHE)
  5310. ++n_measurements;
  5311. if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
  5312. send_control_event(EVENT_BANDWIDTH_USED,
  5313. "650 BW %lu %lu\r\n",
  5314. (unsigned long)n_read,
  5315. (unsigned long)n_written);
  5316. }
  5317. return 0;
  5318. }
  5319. STATIC char *
  5320. get_bw_samples(void)
  5321. {
  5322. int i;
  5323. int idx = (next_measurement_idx + N_BW_EVENTS_TO_CACHE - n_measurements)
  5324. % N_BW_EVENTS_TO_CACHE;
  5325. tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
  5326. smartlist_t *elements = smartlist_new();
  5327. for (i = 0; i < n_measurements; ++i) {
  5328. tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
  5329. const struct cached_bw_event_s *bwe = &cached_bw_events[idx];
  5330. smartlist_add_asprintf(elements, "%u,%u",
  5331. (unsigned)bwe->n_read,
  5332. (unsigned)bwe->n_written);
  5333. idx = (idx + 1) % N_BW_EVENTS_TO_CACHE;
  5334. }
  5335. char *result = smartlist_join_strings(elements, " ", 0, NULL);
  5336. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  5337. smartlist_free(elements);
  5338. return result;
  5339. }
  5340. /** Called when we are sending a log message to the controllers: suspend
  5341. * sending further log messages to the controllers until we're done. Used by
  5342. * CONN_LOG_PROTECT. */
  5343. void
  5344. disable_control_logging(void)
  5345. {
  5346. ++disable_log_messages;
  5347. }
  5348. /** We're done sending a log message to the controllers: re-enable controller
  5349. * logging. Used by CONN_LOG_PROTECT. */
  5350. void
  5351. enable_control_logging(void)
  5352. {
  5353. if (--disable_log_messages < 0)
  5354. tor_assert(0);
  5355. }
  5356. /** We got a log message: tell any interested control connections. */
  5357. void
  5358. control_event_logmsg(int severity, uint32_t domain, const char *msg)
  5359. {
  5360. int event;
  5361. /* Don't even think of trying to add stuff to a buffer from a cpuworker
  5362. * thread. */
  5363. if (! in_main_thread())
  5364. return;
  5365. if (disable_log_messages)
  5366. return;
  5367. if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
  5368. severity <= LOG_NOTICE) {
  5369. char *esc = esc_for_log(msg);
  5370. ++disable_log_messages;
  5371. control_event_general_status(severity, "BUG REASON=%s", esc);
  5372. --disable_log_messages;
  5373. tor_free(esc);
  5374. }
  5375. event = log_severity_to_event(severity);
  5376. if (event >= 0 && EVENT_IS_INTERESTING(event)) {
  5377. char *b = NULL;
  5378. const char *s;
  5379. if (strchr(msg, '\n')) {
  5380. char *cp;
  5381. b = tor_strdup(msg);
  5382. for (cp = b; *cp; ++cp)
  5383. if (*cp == '\r' || *cp == '\n')
  5384. *cp = ' ';
  5385. }
  5386. switch (severity) {
  5387. case LOG_DEBUG: s = "DEBUG"; break;
  5388. case LOG_INFO: s = "INFO"; break;
  5389. case LOG_NOTICE: s = "NOTICE"; break;
  5390. case LOG_WARN: s = "WARN"; break;
  5391. case LOG_ERR: s = "ERR"; break;
  5392. default: s = "UnknownLogSeverity"; break;
  5393. }
  5394. ++disable_log_messages;
  5395. send_control_event(event, "650 %s %s\r\n", s, b?b:msg);
  5396. if (severity == LOG_ERR) {
  5397. /* Force a flush, since we may be about to die horribly */
  5398. queued_events_flush_all(1);
  5399. }
  5400. --disable_log_messages;
  5401. tor_free(b);
  5402. }
  5403. }
  5404. /** Called whenever we receive new router descriptors: tell any
  5405. * interested control connections. <b>routers</b> is a list of
  5406. * routerinfo_t's.
  5407. */
  5408. int
  5409. control_event_descriptors_changed(smartlist_t *routers)
  5410. {
  5411. char *msg;
  5412. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  5413. return 0;
  5414. {
  5415. smartlist_t *names = smartlist_new();
  5416. char *ids;
  5417. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  5418. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  5419. router_get_verbose_nickname(b, ri);
  5420. smartlist_add(names, b);
  5421. });
  5422. ids = smartlist_join_strings(names, " ", 0, NULL);
  5423. tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
  5424. send_control_event_string(EVENT_NEW_DESC, msg);
  5425. tor_free(ids);
  5426. tor_free(msg);
  5427. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  5428. smartlist_free(names);
  5429. }
  5430. return 0;
  5431. }
  5432. /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
  5433. * <b>expires</b> values less than 3 are special; see connection_edge.c. If
  5434. * <b>error</b> is non-NULL, it is an error code describing the failure
  5435. * mode of the mapping.
  5436. */
  5437. int
  5438. control_event_address_mapped(const char *from, const char *to, time_t expires,
  5439. const char *error, const int cached)
  5440. {
  5441. if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
  5442. return 0;
  5443. if (expires < 3 || expires == TIME_MAX)
  5444. send_control_event(EVENT_ADDRMAP,
  5445. "650 ADDRMAP %s %s NEVER %s%s"
  5446. "CACHED=\"%s\"\r\n",
  5447. from, to, error?error:"", error?" ":"",
  5448. cached?"YES":"NO");
  5449. else {
  5450. char buf[ISO_TIME_LEN+1];
  5451. char buf2[ISO_TIME_LEN+1];
  5452. format_local_iso_time(buf,expires);
  5453. format_iso_time(buf2,expires);
  5454. send_control_event(EVENT_ADDRMAP,
  5455. "650 ADDRMAP %s %s \"%s\""
  5456. " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
  5457. from, to, buf,
  5458. error?error:"", error?" ":"",
  5459. buf2, cached?"YES":"NO");
  5460. }
  5461. return 0;
  5462. }
  5463. /** The authoritative dirserver has received a new descriptor that
  5464. * has passed basic syntax checks and is properly self-signed.
  5465. *
  5466. * Notify any interested party of the new descriptor and what has
  5467. * been done with it, and also optionally give an explanation/reason. */
  5468. int
  5469. control_event_or_authdir_new_descriptor(const char *action,
  5470. const char *desc, size_t desclen,
  5471. const char *msg)
  5472. {
  5473. char firstline[1024];
  5474. char *buf;
  5475. size_t totallen;
  5476. char *esc = NULL;
  5477. size_t esclen;
  5478. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  5479. return 0;
  5480. tor_snprintf(firstline, sizeof(firstline),
  5481. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  5482. action,
  5483. msg ? msg : "");
  5484. /* Escape the server descriptor properly */
  5485. esclen = write_escaped_data(desc, desclen, &esc);
  5486. totallen = strlen(firstline) + esclen + 1;
  5487. buf = tor_malloc(totallen);
  5488. strlcpy(buf, firstline, totallen);
  5489. strlcpy(buf+strlen(firstline), esc, totallen);
  5490. send_control_event_string(EVENT_AUTHDIR_NEWDESCS,
  5491. buf);
  5492. send_control_event_string(EVENT_AUTHDIR_NEWDESCS,
  5493. "650 OK\r\n");
  5494. tor_free(esc);
  5495. tor_free(buf);
  5496. return 0;
  5497. }
  5498. /** Cached liveness for network liveness events and GETINFO
  5499. */
  5500. static int network_is_live = 0;
  5501. static int
  5502. get_cached_network_liveness(void)
  5503. {
  5504. return network_is_live;
  5505. }
  5506. static void
  5507. set_cached_network_liveness(int liveness)
  5508. {
  5509. network_is_live = liveness;
  5510. }
  5511. /** The network liveness has changed; this is called from circuitstats.c
  5512. * whenever we receive a cell, or when timeout expires and we assume the
  5513. * network is down. */
  5514. int
  5515. control_event_network_liveness_update(int liveness)
  5516. {
  5517. if (liveness > 0) {
  5518. if (get_cached_network_liveness() <= 0) {
  5519. /* Update cached liveness */
  5520. set_cached_network_liveness(1);
  5521. log_debug(LD_CONTROL, "Sending NETWORK_LIVENESS UP");
  5522. send_control_event_string(EVENT_NETWORK_LIVENESS,
  5523. "650 NETWORK_LIVENESS UP\r\n");
  5524. }
  5525. /* else was already live, no-op */
  5526. } else {
  5527. if (get_cached_network_liveness() > 0) {
  5528. /* Update cached liveness */
  5529. set_cached_network_liveness(0);
  5530. log_debug(LD_CONTROL, "Sending NETWORK_LIVENESS DOWN");
  5531. send_control_event_string(EVENT_NETWORK_LIVENESS,
  5532. "650 NETWORK_LIVENESS DOWN\r\n");
  5533. }
  5534. /* else was already dead, no-op */
  5535. }
  5536. return 0;
  5537. }
  5538. /** Helper function for NS-style events. Constructs and sends an event
  5539. * of type <b>event</b> with string <b>event_string</b> out of the set of
  5540. * networkstatuses <b>statuses</b>. Currently it is used for NS events
  5541. * and NEWCONSENSUS events. */
  5542. static int
  5543. control_event_networkstatus_changed_helper(smartlist_t *statuses,
  5544. uint16_t event,
  5545. const char *event_string)
  5546. {
  5547. smartlist_t *strs;
  5548. char *s, *esc = NULL;
  5549. if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
  5550. return 0;
  5551. strs = smartlist_new();
  5552. smartlist_add_strdup(strs, "650+");
  5553. smartlist_add_strdup(strs, event_string);
  5554. smartlist_add_strdup(strs, "\r\n");
  5555. SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
  5556. {
  5557. s = networkstatus_getinfo_helper_single(rs);
  5558. if (!s) continue;
  5559. smartlist_add(strs, s);
  5560. });
  5561. s = smartlist_join_strings(strs, "", 0, NULL);
  5562. write_escaped_data(s, strlen(s), &esc);
  5563. SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
  5564. smartlist_free(strs);
  5565. tor_free(s);
  5566. send_control_event_string(event, esc);
  5567. send_control_event_string(event,
  5568. "650 OK\r\n");
  5569. tor_free(esc);
  5570. return 0;
  5571. }
  5572. /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
  5573. * an NS event to any controller that cares. */
  5574. int
  5575. control_event_networkstatus_changed(smartlist_t *statuses)
  5576. {
  5577. return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
  5578. }
  5579. /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
  5580. * event consisting of an NS-style line for each relay in the consensus. */
  5581. int
  5582. control_event_newconsensus(const networkstatus_t *consensus)
  5583. {
  5584. if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
  5585. return 0;
  5586. return control_event_networkstatus_changed_helper(
  5587. consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
  5588. }
  5589. /** Called when we compute a new circuitbuildtimeout */
  5590. int
  5591. control_event_buildtimeout_set(buildtimeout_set_event_t type,
  5592. const char *args)
  5593. {
  5594. const char *type_string = NULL;
  5595. if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
  5596. return 0;
  5597. switch (type) {
  5598. case BUILDTIMEOUT_SET_EVENT_COMPUTED:
  5599. type_string = "COMPUTED";
  5600. break;
  5601. case BUILDTIMEOUT_SET_EVENT_RESET:
  5602. type_string = "RESET";
  5603. break;
  5604. case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
  5605. type_string = "SUSPENDED";
  5606. break;
  5607. case BUILDTIMEOUT_SET_EVENT_DISCARD:
  5608. type_string = "DISCARD";
  5609. break;
  5610. case BUILDTIMEOUT_SET_EVENT_RESUME:
  5611. type_string = "RESUME";
  5612. break;
  5613. default:
  5614. type_string = "UNKNOWN";
  5615. break;
  5616. }
  5617. send_control_event(EVENT_BUILDTIMEOUT_SET,
  5618. "650 BUILDTIMEOUT_SET %s %s\r\n",
  5619. type_string, args);
  5620. return 0;
  5621. }
  5622. /** Called when a signal has been processed from signal_callback */
  5623. int
  5624. control_event_signal(uintptr_t signal_num)
  5625. {
  5626. const char *signal_string = NULL;
  5627. if (!control_event_is_interesting(EVENT_GOT_SIGNAL))
  5628. return 0;
  5629. switch (signal_num) {
  5630. case SIGHUP:
  5631. signal_string = "RELOAD";
  5632. break;
  5633. case SIGUSR1:
  5634. signal_string = "DUMP";
  5635. break;
  5636. case SIGUSR2:
  5637. signal_string = "DEBUG";
  5638. break;
  5639. case SIGNEWNYM:
  5640. signal_string = "NEWNYM";
  5641. break;
  5642. case SIGCLEARDNSCACHE:
  5643. signal_string = "CLEARDNSCACHE";
  5644. break;
  5645. case SIGHEARTBEAT:
  5646. signal_string = "HEARTBEAT";
  5647. break;
  5648. default:
  5649. log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
  5650. (unsigned long)signal_num);
  5651. return -1;
  5652. }
  5653. send_control_event(EVENT_GOT_SIGNAL, "650 SIGNAL %s\r\n",
  5654. signal_string);
  5655. return 0;
  5656. }
  5657. /** Called when a single local_routerstatus_t has changed: Sends an NS event
  5658. * to any controller that cares. */
  5659. int
  5660. control_event_networkstatus_changed_single(const routerstatus_t *rs)
  5661. {
  5662. smartlist_t *statuses;
  5663. int r;
  5664. if (!EVENT_IS_INTERESTING(EVENT_NS))
  5665. return 0;
  5666. statuses = smartlist_new();
  5667. smartlist_add(statuses, (void*)rs);
  5668. r = control_event_networkstatus_changed(statuses);
  5669. smartlist_free(statuses);
  5670. return r;
  5671. }
  5672. /** Our own router descriptor has changed; tell any controllers that care.
  5673. */
  5674. int
  5675. control_event_my_descriptor_changed(void)
  5676. {
  5677. send_control_event(EVENT_DESCCHANGED, "650 DESCCHANGED\r\n");
  5678. return 0;
  5679. }
  5680. /** Helper: sends a status event where <b>type</b> is one of
  5681. * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
  5682. * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
  5683. * string corresponding to <b>args</b>. */
  5684. static int
  5685. control_event_status(int type, int severity, const char *format, va_list args)
  5686. {
  5687. char *user_buf = NULL;
  5688. char format_buf[160];
  5689. const char *status, *sev;
  5690. switch (type) {
  5691. case EVENT_STATUS_GENERAL:
  5692. status = "STATUS_GENERAL";
  5693. break;
  5694. case EVENT_STATUS_CLIENT:
  5695. status = "STATUS_CLIENT";
  5696. break;
  5697. case EVENT_STATUS_SERVER:
  5698. status = "STATUS_SERVER";
  5699. break;
  5700. default:
  5701. log_warn(LD_BUG, "Unrecognized status type %d", type);
  5702. return -1;
  5703. }
  5704. switch (severity) {
  5705. case LOG_NOTICE:
  5706. sev = "NOTICE";
  5707. break;
  5708. case LOG_WARN:
  5709. sev = "WARN";
  5710. break;
  5711. case LOG_ERR:
  5712. sev = "ERR";
  5713. break;
  5714. default:
  5715. log_warn(LD_BUG, "Unrecognized status severity %d", severity);
  5716. return -1;
  5717. }
  5718. if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
  5719. status, sev)<0) {
  5720. log_warn(LD_BUG, "Format string too long.");
  5721. return -1;
  5722. }
  5723. tor_vasprintf(&user_buf, format, args);
  5724. send_control_event(type, "%s %s\r\n", format_buf, user_buf);
  5725. tor_free(user_buf);
  5726. return 0;
  5727. }
  5728. #define CONTROL_EVENT_STATUS_BODY(event, sev) \
  5729. int r; \
  5730. do { \
  5731. va_list ap; \
  5732. if (!EVENT_IS_INTERESTING(event)) \
  5733. return 0; \
  5734. \
  5735. va_start(ap, format); \
  5736. r = control_event_status((event), (sev), format, ap); \
  5737. va_end(ap); \
  5738. } while (0)
  5739. /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
  5740. * by formatting the arguments using the printf-style <b>format</b>. */
  5741. int
  5742. control_event_general_status(int severity, const char *format, ...)
  5743. {
  5744. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, severity);
  5745. return r;
  5746. }
  5747. /** Format and send an EVENT_STATUS_GENERAL LOG_ERR event, and flush it to the
  5748. * controller(s) immediately. */
  5749. int
  5750. control_event_general_error(const char *format, ...)
  5751. {
  5752. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, LOG_ERR);
  5753. /* Force a flush, since we may be about to die horribly */
  5754. queued_events_flush_all(1);
  5755. return r;
  5756. }
  5757. /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
  5758. * by formatting the arguments using the printf-style <b>format</b>. */
  5759. int
  5760. control_event_client_status(int severity, const char *format, ...)
  5761. {
  5762. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, severity);
  5763. return r;
  5764. }
  5765. /** Format and send an EVENT_STATUS_CLIENT LOG_ERR event, and flush it to the
  5766. * controller(s) immediately. */
  5767. int
  5768. control_event_client_error(const char *format, ...)
  5769. {
  5770. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, LOG_ERR);
  5771. /* Force a flush, since we may be about to die horribly */
  5772. queued_events_flush_all(1);
  5773. return r;
  5774. }
  5775. /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
  5776. * by formatting the arguments using the printf-style <b>format</b>. */
  5777. int
  5778. control_event_server_status(int severity, const char *format, ...)
  5779. {
  5780. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, severity);
  5781. return r;
  5782. }
  5783. /** Format and send an EVENT_STATUS_SERVER LOG_ERR event, and flush it to the
  5784. * controller(s) immediately. */
  5785. int
  5786. control_event_server_error(const char *format, ...)
  5787. {
  5788. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, LOG_ERR);
  5789. /* Force a flush, since we may be about to die horribly */
  5790. queued_events_flush_all(1);
  5791. return r;
  5792. }
  5793. /** Called when the status of an entry guard with the given <b>nickname</b>
  5794. * and identity <b>digest</b> has changed to <b>status</b>: tells any
  5795. * controllers that care. */
  5796. int
  5797. control_event_guard(const char *nickname, const char *digest,
  5798. const char *status)
  5799. {
  5800. char hbuf[HEX_DIGEST_LEN+1];
  5801. base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
  5802. if (!EVENT_IS_INTERESTING(EVENT_GUARD))
  5803. return 0;
  5804. {
  5805. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  5806. const node_t *node = node_get_by_id(digest);
  5807. if (node) {
  5808. node_get_verbose_nickname(node, buf);
  5809. } else {
  5810. tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
  5811. }
  5812. send_control_event(EVENT_GUARD,
  5813. "650 GUARD ENTRY %s %s\r\n", buf, status);
  5814. }
  5815. return 0;
  5816. }
  5817. /** Called when a configuration option changes. This is generally triggered
  5818. * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
  5819. * a smartlist_t containing (key, value, ...) pairs in sequence.
  5820. * <b>value</b> can be NULL. */
  5821. int
  5822. control_event_conf_changed(const smartlist_t *elements)
  5823. {
  5824. int i;
  5825. char *result;
  5826. smartlist_t *lines;
  5827. if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) ||
  5828. smartlist_len(elements) == 0) {
  5829. return 0;
  5830. }
  5831. lines = smartlist_new();
  5832. for (i = 0; i < smartlist_len(elements); i += 2) {
  5833. char *k = smartlist_get(elements, i);
  5834. char *v = smartlist_get(elements, i+1);
  5835. if (v == NULL) {
  5836. smartlist_add_asprintf(lines, "650-%s", k);
  5837. } else {
  5838. smartlist_add_asprintf(lines, "650-%s=%s", k, v);
  5839. }
  5840. }
  5841. result = smartlist_join_strings(lines, "\r\n", 0, NULL);
  5842. send_control_event(EVENT_CONF_CHANGED,
  5843. "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
  5844. tor_free(result);
  5845. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  5846. smartlist_free(lines);
  5847. return 0;
  5848. }
  5849. /** Helper: Return a newly allocated string containing a path to the
  5850. * file where we store our authentication cookie. */
  5851. char *
  5852. get_controller_cookie_file_name(void)
  5853. {
  5854. const or_options_t *options = get_options();
  5855. if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
  5856. return tor_strdup(options->CookieAuthFile);
  5857. } else {
  5858. return get_datadir_fname("control_auth_cookie");
  5859. }
  5860. }
  5861. /* Initialize the cookie-based authentication system of the
  5862. * ControlPort. If <b>enabled</b> is 0, then disable the cookie
  5863. * authentication system. */
  5864. int
  5865. init_control_cookie_authentication(int enabled)
  5866. {
  5867. char *fname = NULL;
  5868. int retval;
  5869. if (!enabled) {
  5870. authentication_cookie_is_set = 0;
  5871. return 0;
  5872. }
  5873. fname = get_controller_cookie_file_name();
  5874. retval = init_cookie_authentication(fname, "", /* no header */
  5875. AUTHENTICATION_COOKIE_LEN,
  5876. get_options()->CookieAuthFileGroupReadable,
  5877. &authentication_cookie,
  5878. &authentication_cookie_is_set);
  5879. tor_free(fname);
  5880. return retval;
  5881. }
  5882. /** A copy of the process specifier of Tor's owning controller, or
  5883. * NULL if this Tor instance is not currently owned by a process. */
  5884. static char *owning_controller_process_spec = NULL;
  5885. /** A process-termination monitor for Tor's owning controller, or NULL
  5886. * if this Tor instance is not currently owned by a process. */
  5887. static tor_process_monitor_t *owning_controller_process_monitor = NULL;
  5888. /** Process-termination monitor callback for Tor's owning controller
  5889. * process. */
  5890. static void
  5891. owning_controller_procmon_cb(void *unused)
  5892. {
  5893. (void)unused;
  5894. lost_owning_controller("process", "vanished");
  5895. }
  5896. /** Set <b>process_spec</b> as Tor's owning controller process.
  5897. * Exit on failure. */
  5898. void
  5899. monitor_owning_controller_process(const char *process_spec)
  5900. {
  5901. const char *msg;
  5902. tor_assert((owning_controller_process_spec == NULL) ==
  5903. (owning_controller_process_monitor == NULL));
  5904. if (owning_controller_process_spec != NULL) {
  5905. if ((process_spec != NULL) && !strcmp(process_spec,
  5906. owning_controller_process_spec)) {
  5907. /* Same process -- return now, instead of disposing of and
  5908. * recreating the process-termination monitor. */
  5909. return;
  5910. }
  5911. /* We are currently owned by a process, and we should no longer be
  5912. * owned by it. Free the process-termination monitor. */
  5913. tor_process_monitor_free(owning_controller_process_monitor);
  5914. owning_controller_process_monitor = NULL;
  5915. tor_free(owning_controller_process_spec);
  5916. owning_controller_process_spec = NULL;
  5917. }
  5918. tor_assert((owning_controller_process_spec == NULL) &&
  5919. (owning_controller_process_monitor == NULL));
  5920. if (process_spec == NULL)
  5921. return;
  5922. owning_controller_process_spec = tor_strdup(process_spec);
  5923. owning_controller_process_monitor =
  5924. tor_process_monitor_new(tor_libevent_get_base(),
  5925. owning_controller_process_spec,
  5926. LD_CONTROL,
  5927. owning_controller_procmon_cb, NULL,
  5928. &msg);
  5929. if (owning_controller_process_monitor == NULL) {
  5930. log_err(LD_BUG, "Couldn't create process-termination monitor for "
  5931. "owning controller: %s. Exiting.",
  5932. msg);
  5933. owning_controller_process_spec = NULL;
  5934. tor_cleanup();
  5935. exit(0);
  5936. }
  5937. }
  5938. /** Convert the name of a bootstrapping phase <b>s</b> into strings
  5939. * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
  5940. static int
  5941. bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
  5942. const char **summary)
  5943. {
  5944. switch (s) {
  5945. case BOOTSTRAP_STATUS_UNDEF:
  5946. *tag = "undef";
  5947. *summary = "Undefined";
  5948. break;
  5949. case BOOTSTRAP_STATUS_STARTING:
  5950. *tag = "starting";
  5951. *summary = "Starting";
  5952. break;
  5953. case BOOTSTRAP_STATUS_CONN_DIR:
  5954. *tag = "conn_dir";
  5955. *summary = "Connecting to directory server";
  5956. break;
  5957. case BOOTSTRAP_STATUS_HANDSHAKE:
  5958. *tag = "status_handshake";
  5959. *summary = "Finishing handshake";
  5960. break;
  5961. case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
  5962. *tag = "handshake_dir";
  5963. *summary = "Finishing handshake with directory server";
  5964. break;
  5965. case BOOTSTRAP_STATUS_ONEHOP_CREATE:
  5966. *tag = "onehop_create";
  5967. *summary = "Establishing an encrypted directory connection";
  5968. break;
  5969. case BOOTSTRAP_STATUS_REQUESTING_STATUS:
  5970. *tag = "requesting_status";
  5971. *summary = "Asking for networkstatus consensus";
  5972. break;
  5973. case BOOTSTRAP_STATUS_LOADING_STATUS:
  5974. *tag = "loading_status";
  5975. *summary = "Loading networkstatus consensus";
  5976. break;
  5977. case BOOTSTRAP_STATUS_LOADING_KEYS:
  5978. *tag = "loading_keys";
  5979. *summary = "Loading authority key certs";
  5980. break;
  5981. case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
  5982. *tag = "requesting_descriptors";
  5983. /* XXXX this appears to incorrectly report internal on most loads */
  5984. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  5985. "Asking for relay descriptors for internal paths" :
  5986. "Asking for relay descriptors";
  5987. break;
  5988. /* If we're sure there are no exits in the consensus,
  5989. * inform the controller by adding "internal"
  5990. * to the status summaries.
  5991. * (We only check this while loading descriptors,
  5992. * so we may not know in the earlier stages.)
  5993. * But if there are exits, we can't be sure whether
  5994. * we're creating internal or exit paths/circuits.
  5995. * XXXX Or should be use different tags or statuses
  5996. * for internal and exit/all? */
  5997. case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
  5998. *tag = "loading_descriptors";
  5999. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  6000. "Loading relay descriptors for internal paths" :
  6001. "Loading relay descriptors";
  6002. break;
  6003. case BOOTSTRAP_STATUS_CONN_OR:
  6004. *tag = "conn_or";
  6005. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  6006. "Connecting to the Tor network internally" :
  6007. "Connecting to the Tor network";
  6008. break;
  6009. case BOOTSTRAP_STATUS_HANDSHAKE_OR:
  6010. *tag = "handshake_or";
  6011. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  6012. "Finishing handshake with first hop of internal circuit" :
  6013. "Finishing handshake with first hop";
  6014. break;
  6015. case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
  6016. *tag = "circuit_create";
  6017. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  6018. "Establishing an internal Tor circuit" :
  6019. "Establishing a Tor circuit";
  6020. break;
  6021. case BOOTSTRAP_STATUS_DONE:
  6022. *tag = "done";
  6023. *summary = "Done";
  6024. break;
  6025. default:
  6026. // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
  6027. *tag = *summary = "unknown";
  6028. return -1;
  6029. }
  6030. return 0;
  6031. }
  6032. /** What percentage through the bootstrap process are we? We remember
  6033. * this so we can avoid sending redundant bootstrap status events, and
  6034. * so we can guess context for the bootstrap messages which are
  6035. * ambiguous. It starts at 'undef', but gets set to 'starting' while
  6036. * Tor initializes. */
  6037. static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
  6038. /** As bootstrap_percent, but holds the bootstrapping level at which we last
  6039. * logged a NOTICE-level message. We use this, plus BOOTSTRAP_PCT_INCREMENT,
  6040. * to avoid flooding the log with a new message every time we get a few more
  6041. * microdescriptors */
  6042. static int notice_bootstrap_percent = 0;
  6043. /** How many problems have we had getting to the next bootstrapping phase?
  6044. * These include failure to establish a connection to a Tor relay,
  6045. * failures to finish the TLS handshake, failures to validate the
  6046. * consensus document, etc. */
  6047. static int bootstrap_problems = 0;
  6048. /** We only tell the controller once we've hit a threshold of problems
  6049. * for the current phase. */
  6050. #define BOOTSTRAP_PROBLEM_THRESHOLD 10
  6051. /** When our bootstrapping progress level changes, but our bootstrapping
  6052. * status has not advanced, we only log at NOTICE when we have made at least
  6053. * this much progress.
  6054. */
  6055. #define BOOTSTRAP_PCT_INCREMENT 5
  6056. /** Called when Tor has made progress at bootstrapping its directory
  6057. * information and initial circuits.
  6058. *
  6059. * <b>status</b> is the new status, that is, what task we will be doing
  6060. * next. <b>progress</b> is zero if we just started this task, else it
  6061. * represents progress on the task.
  6062. *
  6063. * Return true if we logged a message at level NOTICE, and false otherwise.
  6064. */
  6065. int
  6066. control_event_bootstrap(bootstrap_status_t status, int progress)
  6067. {
  6068. const char *tag, *summary;
  6069. char buf[BOOTSTRAP_MSG_LEN];
  6070. if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
  6071. return 0; /* already bootstrapped; nothing to be done here. */
  6072. /* special case for handshaking status, since our TLS handshaking code
  6073. * can't distinguish what the connection is going to be for. */
  6074. if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
  6075. if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
  6076. status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
  6077. } else {
  6078. status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
  6079. }
  6080. }
  6081. if (status > bootstrap_percent ||
  6082. (progress && progress > bootstrap_percent)) {
  6083. int loglevel = LOG_NOTICE;
  6084. bootstrap_status_to_string(status, &tag, &summary);
  6085. if (status <= bootstrap_percent &&
  6086. (progress < notice_bootstrap_percent + BOOTSTRAP_PCT_INCREMENT)) {
  6087. /* We log the message at info if the status hasn't advanced, and if less
  6088. * than BOOTSTRAP_PCT_INCREMENT progress has been made.
  6089. */
  6090. loglevel = LOG_INFO;
  6091. }
  6092. tor_log(loglevel, LD_CONTROL,
  6093. "Bootstrapped %d%%: %s", progress ? progress : status, summary);
  6094. tor_snprintf(buf, sizeof(buf),
  6095. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
  6096. progress ? progress : status, tag, summary);
  6097. tor_snprintf(last_sent_bootstrap_message,
  6098. sizeof(last_sent_bootstrap_message),
  6099. "NOTICE %s", buf);
  6100. control_event_client_status(LOG_NOTICE, "%s", buf);
  6101. if (status > bootstrap_percent) {
  6102. bootstrap_percent = status; /* new milestone reached */
  6103. }
  6104. if (progress > bootstrap_percent) {
  6105. /* incremental progress within a milestone */
  6106. bootstrap_percent = progress;
  6107. bootstrap_problems = 0; /* Progress! Reset our problem counter. */
  6108. }
  6109. if (loglevel == LOG_NOTICE &&
  6110. bootstrap_percent > notice_bootstrap_percent) {
  6111. /* Remember that we gave a notice at this level. */
  6112. notice_bootstrap_percent = bootstrap_percent;
  6113. }
  6114. return loglevel == LOG_NOTICE;
  6115. }
  6116. return 0;
  6117. }
  6118. /** Called when Tor has failed to make bootstrapping progress in a way
  6119. * that indicates a problem. <b>warn</b> gives a hint as to why, and
  6120. * <b>reason</b> provides an "or_conn_end_reason" tag. <b>or_conn</b>
  6121. * is the connection that caused this problem.
  6122. */
  6123. MOCK_IMPL(void,
  6124. control_event_bootstrap_problem, (const char *warn, int reason,
  6125. or_connection_t *or_conn))
  6126. {
  6127. int status = bootstrap_percent;
  6128. const char *tag = "", *summary = "";
  6129. char buf[BOOTSTRAP_MSG_LEN];
  6130. const char *recommendation = "ignore";
  6131. int severity;
  6132. /* bootstrap_percent must not be in "undefined" state here. */
  6133. tor_assert(status >= 0);
  6134. if (or_conn->have_noted_bootstrap_problem)
  6135. return;
  6136. or_conn->have_noted_bootstrap_problem = 1;
  6137. if (bootstrap_percent == 100)
  6138. return; /* already bootstrapped; nothing to be done here. */
  6139. bootstrap_problems++;
  6140. if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
  6141. recommendation = "warn";
  6142. if (reason == END_OR_CONN_REASON_NO_ROUTE)
  6143. recommendation = "warn";
  6144. /* If we are using bridges and all our OR connections are now
  6145. closed, it means that we totally failed to connect to our
  6146. bridges. Throw a warning. */
  6147. if (get_options()->UseBridges && !any_other_active_or_conns(or_conn))
  6148. recommendation = "warn";
  6149. if (we_are_hibernating())
  6150. recommendation = "ignore";
  6151. while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
  6152. status--; /* find a recognized status string based on current progress */
  6153. status = bootstrap_percent; /* set status back to the actual number */
  6154. severity = !strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO;
  6155. log_fn(severity,
  6156. LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
  6157. "count %d; recommendation %s; host %s at %s:%d)",
  6158. status, summary, warn,
  6159. orconn_end_reason_to_control_string(reason),
  6160. bootstrap_problems, recommendation,
  6161. hex_str(or_conn->identity_digest, DIGEST_LEN),
  6162. or_conn->base_.address,
  6163. or_conn->base_.port);
  6164. connection_or_report_broken_states(severity, LD_HANDSHAKE);
  6165. tor_snprintf(buf, sizeof(buf),
  6166. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
  6167. "COUNT=%d RECOMMENDATION=%s HOSTID=\"%s\" HOSTADDR=\"%s:%d\"",
  6168. bootstrap_percent, tag, summary, warn,
  6169. orconn_end_reason_to_control_string(reason), bootstrap_problems,
  6170. recommendation,
  6171. hex_str(or_conn->identity_digest, DIGEST_LEN),
  6172. or_conn->base_.address,
  6173. (int)or_conn->base_.port);
  6174. tor_snprintf(last_sent_bootstrap_message,
  6175. sizeof(last_sent_bootstrap_message),
  6176. "WARN %s", buf);
  6177. control_event_client_status(LOG_WARN, "%s", buf);
  6178. }
  6179. /** We just generated a new summary of which countries we've seen clients
  6180. * from recently. Send a copy to the controller in case it wants to
  6181. * display it for the user. */
  6182. void
  6183. control_event_clients_seen(const char *controller_str)
  6184. {
  6185. send_control_event(EVENT_CLIENTS_SEEN,
  6186. "650 CLIENTS_SEEN %s\r\n", controller_str);
  6187. }
  6188. /** A new pluggable transport called <b>transport_name</b> was
  6189. * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
  6190. * "server" or "client" depending on the mode of the pluggable
  6191. * transport.
  6192. * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
  6193. */
  6194. void
  6195. control_event_transport_launched(const char *mode, const char *transport_name,
  6196. tor_addr_t *addr, uint16_t port)
  6197. {
  6198. send_control_event(EVENT_TRANSPORT_LAUNCHED,
  6199. "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
  6200. mode, transport_name, fmt_addr(addr), port);
  6201. }
  6202. /** Convert rendezvous auth type to string for HS_DESC control events
  6203. */
  6204. const char *
  6205. rend_auth_type_to_string(rend_auth_type_t auth_type)
  6206. {
  6207. const char *str;
  6208. switch (auth_type) {
  6209. case REND_NO_AUTH:
  6210. str = "NO_AUTH";
  6211. break;
  6212. case REND_BASIC_AUTH:
  6213. str = "BASIC_AUTH";
  6214. break;
  6215. case REND_STEALTH_AUTH:
  6216. str = "STEALTH_AUTH";
  6217. break;
  6218. default:
  6219. str = "UNKNOWN";
  6220. }
  6221. return str;
  6222. }
  6223. /** Return a longname the node whose identity is <b>id_digest</b>. If
  6224. * node_get_by_id() returns NULL, base 16 encoding of <b>id_digest</b> is
  6225. * returned instead.
  6226. *
  6227. * This function is not thread-safe. Each call to this function invalidates
  6228. * previous values returned by this function.
  6229. */
  6230. MOCK_IMPL(const char *,
  6231. node_describe_longname_by_id,(const char *id_digest))
  6232. {
  6233. static char longname[MAX_VERBOSE_NICKNAME_LEN+1];
  6234. node_get_verbose_nickname_by_id(id_digest, longname);
  6235. return longname;
  6236. }
  6237. /** Return either the onion address if the given pointer is a non empty
  6238. * string else the unknown string. */
  6239. static const char *
  6240. rend_hsaddress_str_or_unknown(const char *onion_address)
  6241. {
  6242. static const char *str_unknown = "UNKNOWN";
  6243. const char *str_ret = str_unknown;
  6244. /* No valid pointer, unknown it is. */
  6245. if (!onion_address) {
  6246. goto end;
  6247. }
  6248. /* Empty onion address thus we don't know, unknown it is. */
  6249. if (onion_address[0] == '\0') {
  6250. goto end;
  6251. }
  6252. /* All checks are good so return the given onion address. */
  6253. str_ret = onion_address;
  6254. end:
  6255. return str_ret;
  6256. }
  6257. /** send HS_DESC requested event.
  6258. *
  6259. * <b>rend_query</b> is used to fetch requested onion address and auth type.
  6260. * <b>hs_dir</b> is the description of contacting hs directory.
  6261. * <b>desc_id_base32</b> is the ID of requested hs descriptor.
  6262. */
  6263. void
  6264. control_event_hs_descriptor_requested(const rend_data_t *rend_query,
  6265. const char *id_digest,
  6266. const char *desc_id_base32)
  6267. {
  6268. if (!id_digest || !rend_query || !desc_id_base32) {
  6269. log_warn(LD_BUG, "Called with rend_query==%p, "
  6270. "id_digest==%p, desc_id_base32==%p",
  6271. rend_query, id_digest, desc_id_base32);
  6272. return;
  6273. }
  6274. send_control_event(EVENT_HS_DESC,
  6275. "650 HS_DESC REQUESTED %s %s %s %s\r\n",
  6276. rend_hsaddress_str_or_unknown(
  6277. rend_data_get_address(rend_query)),
  6278. rend_auth_type_to_string(
  6279. TO_REND_DATA_V2(rend_query)->auth_type),
  6280. node_describe_longname_by_id(id_digest),
  6281. desc_id_base32);
  6282. }
  6283. /** For an HS descriptor query <b>rend_data</b>, using the
  6284. * <b>onion_address</b> and HSDir fingerprint <b>hsdir_fp</b>, find out
  6285. * which descriptor ID in the query is the right one.
  6286. *
  6287. * Return a pointer of the binary descriptor ID found in the query's object
  6288. * or NULL if not found. */
  6289. static const char *
  6290. get_desc_id_from_query(const rend_data_t *rend_data, const char *hsdir_fp)
  6291. {
  6292. int replica;
  6293. const char *desc_id = NULL;
  6294. const rend_data_v2_t *rend_data_v2 = TO_REND_DATA_V2(rend_data);
  6295. /* Possible if the fetch was done using a descriptor ID. This means that
  6296. * the HSFETCH command was used. */
  6297. if (!tor_digest_is_zero(rend_data_v2->desc_id_fetch)) {
  6298. desc_id = rend_data_v2->desc_id_fetch;
  6299. goto end;
  6300. }
  6301. /* OK, we have an onion address so now let's find which descriptor ID
  6302. * is the one associated with the HSDir fingerprint. */
  6303. for (replica = 0; replica < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
  6304. replica++) {
  6305. const char *digest = rend_data_get_desc_id(rend_data, replica, NULL);
  6306. SMARTLIST_FOREACH_BEGIN(rend_data->hsdirs_fp, char *, fingerprint) {
  6307. if (tor_memcmp(fingerprint, hsdir_fp, DIGEST_LEN) == 0) {
  6308. /* Found it! This descriptor ID is the right one. */
  6309. desc_id = digest;
  6310. goto end;
  6311. }
  6312. } SMARTLIST_FOREACH_END(fingerprint);
  6313. }
  6314. end:
  6315. return desc_id;
  6316. }
  6317. /** send HS_DESC CREATED event when a local service generates a descriptor.
  6318. *
  6319. * <b>service_id</b> is the descriptor onion address.
  6320. * <b>desc_id_base32</b> is the descriptor ID.
  6321. * <b>replica</b> is the the descriptor replica number.
  6322. */
  6323. void
  6324. control_event_hs_descriptor_created(const char *service_id,
  6325. const char *desc_id_base32,
  6326. int replica)
  6327. {
  6328. if (!service_id || !desc_id_base32) {
  6329. log_warn(LD_BUG, "Called with service_digest==%p, "
  6330. "desc_id_base32==%p", service_id, desc_id_base32);
  6331. return;
  6332. }
  6333. send_control_event(EVENT_HS_DESC,
  6334. "650 HS_DESC CREATED %s UNKNOWN UNKNOWN %s "
  6335. "REPLICA=%d\r\n",
  6336. service_id,
  6337. desc_id_base32,
  6338. replica);
  6339. }
  6340. /** send HS_DESC upload event.
  6341. *
  6342. * <b>service_id</b> is the descriptor onion address.
  6343. * <b>hs_dir</b> is the description of contacting hs directory.
  6344. * <b>desc_id_base32</b> is the ID of requested hs descriptor.
  6345. */
  6346. void
  6347. control_event_hs_descriptor_upload(const char *service_id,
  6348. const char *id_digest,
  6349. const char *desc_id_base32)
  6350. {
  6351. if (!service_id || !id_digest || !desc_id_base32) {
  6352. log_warn(LD_BUG, "Called with service_digest==%p, "
  6353. "desc_id_base32==%p, id_digest==%p", service_id,
  6354. desc_id_base32, id_digest);
  6355. return;
  6356. }
  6357. send_control_event(EVENT_HS_DESC,
  6358. "650 HS_DESC UPLOAD %s UNKNOWN %s %s\r\n",
  6359. service_id,
  6360. node_describe_longname_by_id(id_digest),
  6361. desc_id_base32);
  6362. }
  6363. /** send HS_DESC event after got response from hs directory.
  6364. *
  6365. * NOTE: this is an internal function used by following functions:
  6366. * control_event_hs_descriptor_received
  6367. * control_event_hs_descriptor_failed
  6368. *
  6369. * So do not call this function directly.
  6370. */
  6371. void
  6372. control_event_hs_descriptor_receive_end(const char *action,
  6373. const char *onion_address,
  6374. const rend_data_t *rend_data,
  6375. const char *id_digest,
  6376. const char *reason)
  6377. {
  6378. char *desc_id_field = NULL;
  6379. char *reason_field = NULL;
  6380. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  6381. const char *desc_id = NULL;
  6382. if (!action || !rend_data || !onion_address) {
  6383. log_warn(LD_BUG, "Called with action==%p, rend_data==%p, "
  6384. "onion_address==%p", action, rend_data, onion_address);
  6385. return;
  6386. }
  6387. desc_id = get_desc_id_from_query(rend_data, id_digest);
  6388. if (desc_id != NULL) {
  6389. /* Set the descriptor ID digest to base32 so we can send it. */
  6390. base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_id,
  6391. DIGEST_LEN);
  6392. /* Extra whitespace is needed before the value. */
  6393. tor_asprintf(&desc_id_field, " %s", desc_id_base32);
  6394. }
  6395. if (reason) {
  6396. tor_asprintf(&reason_field, " REASON=%s", reason);
  6397. }
  6398. send_control_event(EVENT_HS_DESC,
  6399. "650 HS_DESC %s %s %s %s%s%s\r\n",
  6400. action,
  6401. rend_hsaddress_str_or_unknown(onion_address),
  6402. rend_auth_type_to_string(
  6403. TO_REND_DATA_V2(rend_data)->auth_type),
  6404. id_digest ?
  6405. node_describe_longname_by_id(id_digest) : "UNKNOWN",
  6406. desc_id_field ? desc_id_field : "",
  6407. reason_field ? reason_field : "");
  6408. tor_free(desc_id_field);
  6409. tor_free(reason_field);
  6410. }
  6411. /** send HS_DESC event after got response from hs directory.
  6412. *
  6413. * NOTE: this is an internal function used by following functions:
  6414. * control_event_hs_descriptor_uploaded
  6415. * control_event_hs_descriptor_upload_failed
  6416. *
  6417. * So do not call this function directly.
  6418. */
  6419. void
  6420. control_event_hs_descriptor_upload_end(const char *action,
  6421. const char *onion_address,
  6422. const char *id_digest,
  6423. const char *reason)
  6424. {
  6425. char *reason_field = NULL;
  6426. if (!action || !id_digest) {
  6427. log_warn(LD_BUG, "Called with action==%p, id_digest==%p", action,
  6428. id_digest);
  6429. return;
  6430. }
  6431. if (reason) {
  6432. tor_asprintf(&reason_field, " REASON=%s", reason);
  6433. }
  6434. send_control_event(EVENT_HS_DESC,
  6435. "650 HS_DESC %s %s UNKNOWN %s%s\r\n",
  6436. action,
  6437. rend_hsaddress_str_or_unknown(onion_address),
  6438. node_describe_longname_by_id(id_digest),
  6439. reason_field ? reason_field : "");
  6440. tor_free(reason_field);
  6441. }
  6442. /** send HS_DESC RECEIVED event
  6443. *
  6444. * called when we successfully received a hidden service descriptor.
  6445. */
  6446. void
  6447. control_event_hs_descriptor_received(const char *onion_address,
  6448. const rend_data_t *rend_data,
  6449. const char *id_digest)
  6450. {
  6451. if (!rend_data || !id_digest || !onion_address) {
  6452. log_warn(LD_BUG, "Called with rend_data==%p, id_digest==%p, "
  6453. "onion_address==%p", rend_data, id_digest, onion_address);
  6454. return;
  6455. }
  6456. control_event_hs_descriptor_receive_end("RECEIVED", onion_address,
  6457. rend_data, id_digest, NULL);
  6458. }
  6459. /** send HS_DESC UPLOADED event
  6460. *
  6461. * called when we successfully uploaded a hidden service descriptor.
  6462. */
  6463. void
  6464. control_event_hs_descriptor_uploaded(const char *id_digest,
  6465. const char *onion_address)
  6466. {
  6467. if (!id_digest) {
  6468. log_warn(LD_BUG, "Called with id_digest==%p",
  6469. id_digest);
  6470. return;
  6471. }
  6472. control_event_hs_descriptor_upload_end("UPLOADED", onion_address,
  6473. id_digest, NULL);
  6474. }
  6475. /** Send HS_DESC event to inform controller that query <b>rend_data</b>
  6476. * failed to retrieve hidden service descriptor from directory identified by
  6477. * <b>id_digest</b>. If NULL, "UNKNOWN" is used. If <b>reason</b> is not NULL,
  6478. * add it to REASON= field.
  6479. */
  6480. void
  6481. control_event_hs_descriptor_failed(const rend_data_t *rend_data,
  6482. const char *id_digest,
  6483. const char *reason)
  6484. {
  6485. if (!rend_data) {
  6486. log_warn(LD_BUG, "Called with rend_data==%p", rend_data);
  6487. return;
  6488. }
  6489. control_event_hs_descriptor_receive_end("FAILED",
  6490. rend_data_get_address(rend_data),
  6491. rend_data, id_digest, reason);
  6492. }
  6493. /** Send HS_DESC_CONTENT event after completion of a successful fetch from hs
  6494. * directory. If <b>hsdir_id_digest</b> is NULL, it is replaced by "UNKNOWN".
  6495. * If <b>content</b> is NULL, it is replaced by an empty string. The
  6496. * <b>onion_address</b> or <b>desc_id</b> set to NULL will no trigger the
  6497. * control event. */
  6498. void
  6499. control_event_hs_descriptor_content(const char *onion_address,
  6500. const char *desc_id,
  6501. const char *hsdir_id_digest,
  6502. const char *content)
  6503. {
  6504. static const char *event_name = "HS_DESC_CONTENT";
  6505. char *esc_content = NULL;
  6506. if (!onion_address || !desc_id) {
  6507. log_warn(LD_BUG, "Called with onion_address==%p, desc_id==%p, ",
  6508. onion_address, desc_id);
  6509. return;
  6510. }
  6511. if (content == NULL) {
  6512. /* Point it to empty content so it can still be escaped. */
  6513. content = "";
  6514. }
  6515. write_escaped_data(content, strlen(content), &esc_content);
  6516. send_control_event(EVENT_HS_DESC_CONTENT,
  6517. "650+%s %s %s %s\r\n%s650 OK\r\n",
  6518. event_name,
  6519. rend_hsaddress_str_or_unknown(onion_address),
  6520. desc_id,
  6521. hsdir_id_digest ?
  6522. node_describe_longname_by_id(hsdir_id_digest) :
  6523. "UNKNOWN",
  6524. esc_content);
  6525. tor_free(esc_content);
  6526. }
  6527. /** Send HS_DESC event to inform controller upload of hidden service
  6528. * descriptor identified by <b>id_digest</b> failed. If <b>reason</b>
  6529. * is not NULL, add it to REASON= field.
  6530. */
  6531. void
  6532. control_event_hs_descriptor_upload_failed(const char *id_digest,
  6533. const char *onion_address,
  6534. const char *reason)
  6535. {
  6536. if (!id_digest) {
  6537. log_warn(LD_BUG, "Called with id_digest==%p",
  6538. id_digest);
  6539. return;
  6540. }
  6541. control_event_hs_descriptor_upload_end("UPLOAD_FAILED", onion_address,
  6542. id_digest, reason);
  6543. }
  6544. /** Free any leftover allocated memory of the control.c subsystem. */
  6545. void
  6546. control_free_all(void)
  6547. {
  6548. if (authentication_cookie) /* Free the auth cookie */
  6549. tor_free(authentication_cookie);
  6550. if (detached_onion_services) { /* Free the detached onion services */
  6551. SMARTLIST_FOREACH(detached_onion_services, char *, cp, tor_free(cp));
  6552. smartlist_free(detached_onion_services);
  6553. }
  6554. if (queued_control_events) {
  6555. SMARTLIST_FOREACH(queued_control_events, queued_event_t *, ev,
  6556. queued_event_free(ev));
  6557. smartlist_free(queued_control_events);
  6558. queued_control_events = NULL;
  6559. }
  6560. if (flush_queued_events_event) {
  6561. tor_event_free(flush_queued_events_event);
  6562. flush_queued_events_event = NULL;
  6563. }
  6564. }
  6565. #ifdef TOR_UNIT_TESTS
  6566. /* For testing: change the value of global_event_mask */
  6567. void
  6568. control_testing_set_global_event_mask(uint64_t mask)
  6569. {
  6570. global_event_mask = mask;
  6571. }
  6572. #endif