control.c 264 KB

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