control.c 261 KB

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