control.c 198 KB

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