control.c 264 KB

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