control.c 264 KB

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