control.c 254 KB

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