control.c 197 KB

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