control.c 237 KB

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