control.c 207 KB

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