control.c 259 KB

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