control.c 259 KB

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