control.c 259 KB

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