control.c 264 KB

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