control.c 259 KB

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