control.c 259 KB

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