control.c 222 KB

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