control.c 261 KB

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