control.c 252 KB

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