control.c 221 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684
  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. (void) control_conn;
  1938. if (!strcmp(question, "circuit-status")) {
  1939. smartlist_t *status = smartlist_new();
  1940. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ_) {
  1941. origin_circuit_t *circ;
  1942. char *circdesc;
  1943. const char *state;
  1944. if (! CIRCUIT_IS_ORIGIN(circ_) || circ_->marked_for_close)
  1945. continue;
  1946. circ = TO_ORIGIN_CIRCUIT(circ_);
  1947. if (circ->base_.state == CIRCUIT_STATE_OPEN)
  1948. state = "BUILT";
  1949. else if (circ->cpath)
  1950. state = "EXTENDED";
  1951. else
  1952. state = "LAUNCHED";
  1953. circdesc = circuit_describe_status_for_controller(circ);
  1954. smartlist_add_asprintf(status, "%lu %s%s%s",
  1955. (unsigned long)circ->global_identifier,
  1956. state, *circdesc ? " " : "", circdesc);
  1957. tor_free(circdesc);
  1958. }
  1959. SMARTLIST_FOREACH_END(circ_);
  1960. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1961. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1962. smartlist_free(status);
  1963. } else if (!strcmp(question, "stream-status")) {
  1964. smartlist_t *conns = get_connection_array();
  1965. smartlist_t *status = smartlist_new();
  1966. char buf[256];
  1967. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1968. const char *state;
  1969. entry_connection_t *conn;
  1970. circuit_t *circ;
  1971. origin_circuit_t *origin_circ = NULL;
  1972. if (base_conn->type != CONN_TYPE_AP ||
  1973. base_conn->marked_for_close ||
  1974. base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
  1975. base_conn->state == AP_CONN_STATE_NATD_WAIT)
  1976. continue;
  1977. conn = TO_ENTRY_CONN(base_conn);
  1978. switch (base_conn->state)
  1979. {
  1980. case AP_CONN_STATE_CONTROLLER_WAIT:
  1981. case AP_CONN_STATE_CIRCUIT_WAIT:
  1982. if (conn->socks_request &&
  1983. SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  1984. state = "NEWRESOLVE";
  1985. else
  1986. state = "NEW";
  1987. break;
  1988. case AP_CONN_STATE_RENDDESC_WAIT:
  1989. case AP_CONN_STATE_CONNECT_WAIT:
  1990. state = "SENTCONNECT"; break;
  1991. case AP_CONN_STATE_RESOLVE_WAIT:
  1992. state = "SENTRESOLVE"; break;
  1993. case AP_CONN_STATE_OPEN:
  1994. state = "SUCCEEDED"; break;
  1995. default:
  1996. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  1997. base_conn->state);
  1998. continue;
  1999. }
  2000. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  2001. if (circ && CIRCUIT_IS_ORIGIN(circ))
  2002. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2003. write_stream_target_to_buf(conn, buf, sizeof(buf));
  2004. smartlist_add_asprintf(status, "%lu %s %lu %s",
  2005. (unsigned long) base_conn->global_identifier,state,
  2006. origin_circ?
  2007. (unsigned long)origin_circ->global_identifier : 0ul,
  2008. buf);
  2009. } SMARTLIST_FOREACH_END(base_conn);
  2010. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  2011. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  2012. smartlist_free(status);
  2013. } else if (!strcmp(question, "orconn-status")) {
  2014. smartlist_t *conns = get_connection_array();
  2015. smartlist_t *status = smartlist_new();
  2016. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  2017. const char *state;
  2018. char name[128];
  2019. or_connection_t *conn;
  2020. if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
  2021. continue;
  2022. conn = TO_OR_CONN(base_conn);
  2023. if (conn->base_.state == OR_CONN_STATE_OPEN)
  2024. state = "CONNECTED";
  2025. else if (conn->nickname)
  2026. state = "LAUNCHED";
  2027. else
  2028. state = "NEW";
  2029. orconn_target_get_name(name, sizeof(name), conn);
  2030. smartlist_add_asprintf(status, "%s %s", name, state);
  2031. } SMARTLIST_FOREACH_END(base_conn);
  2032. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  2033. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  2034. smartlist_free(status);
  2035. } else if (!strcmpstart(question, "address-mappings/")) {
  2036. time_t min_e, max_e;
  2037. smartlist_t *mappings;
  2038. question += strlen("address-mappings/");
  2039. if (!strcmp(question, "all")) {
  2040. min_e = 0; max_e = TIME_MAX;
  2041. } else if (!strcmp(question, "cache")) {
  2042. min_e = 2; max_e = TIME_MAX;
  2043. } else if (!strcmp(question, "config")) {
  2044. min_e = 0; max_e = 0;
  2045. } else if (!strcmp(question, "control")) {
  2046. min_e = 1; max_e = 1;
  2047. } else {
  2048. return 0;
  2049. }
  2050. mappings = smartlist_new();
  2051. addressmap_get_mappings(mappings, min_e, max_e, 1);
  2052. *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
  2053. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  2054. smartlist_free(mappings);
  2055. } else if (!strcmpstart(question, "status/")) {
  2056. /* Note that status/ is not a catch-all for events; there's only supposed
  2057. * to be a status GETINFO if there's a corresponding STATUS event. */
  2058. if (!strcmp(question, "status/circuit-established")) {
  2059. *answer = tor_strdup(have_completed_a_circuit() ? "1" : "0");
  2060. } else if (!strcmp(question, "status/enough-dir-info")) {
  2061. *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
  2062. } else if (!strcmp(question, "status/good-server-descriptor") ||
  2063. !strcmp(question, "status/accepted-server-descriptor")) {
  2064. /* They're equivalent for now, until we can figure out how to make
  2065. * good-server-descriptor be what we want. See comment in
  2066. * control-spec.txt. */
  2067. *answer = tor_strdup(directories_have_accepted_server_descriptor()
  2068. ? "1" : "0");
  2069. } else if (!strcmp(question, "status/reachability-succeeded/or")) {
  2070. *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
  2071. } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
  2072. *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
  2073. } else if (!strcmp(question, "status/reachability-succeeded")) {
  2074. tor_asprintf(answer, "OR=%d DIR=%d",
  2075. check_whether_orport_reachable() ? 1 : 0,
  2076. check_whether_dirport_reachable() ? 1 : 0);
  2077. } else if (!strcmp(question, "status/bootstrap-phase")) {
  2078. *answer = tor_strdup(last_sent_bootstrap_message);
  2079. } else if (!strcmpstart(question, "status/version/")) {
  2080. int is_server = server_mode(get_options());
  2081. networkstatus_t *c = networkstatus_get_latest_consensus();
  2082. version_status_t status;
  2083. const char *recommended;
  2084. if (c) {
  2085. recommended = is_server ? c->server_versions : c->client_versions;
  2086. status = tor_version_is_obsolete(VERSION, recommended);
  2087. } else {
  2088. recommended = "?";
  2089. status = VS_UNKNOWN;
  2090. }
  2091. if (!strcmp(question, "status/version/recommended")) {
  2092. *answer = tor_strdup(recommended);
  2093. return 0;
  2094. }
  2095. if (!strcmp(question, "status/version/current")) {
  2096. switch (status)
  2097. {
  2098. case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
  2099. case VS_OLD: *answer = tor_strdup("obsolete"); break;
  2100. case VS_NEW: *answer = tor_strdup("new"); break;
  2101. case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
  2102. case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
  2103. case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
  2104. case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
  2105. default: tor_fragile_assert();
  2106. }
  2107. } else if (!strcmp(question, "status/version/num-versioning") ||
  2108. !strcmp(question, "status/version/num-concurring")) {
  2109. tor_asprintf(answer, "%d", get_n_authorities(V3_DIRINFO));
  2110. log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
  2111. "information", question);
  2112. }
  2113. } else if (!strcmp(question, "status/clients-seen")) {
  2114. char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
  2115. if (!bridge_stats) {
  2116. *errmsg = "No bridge-client stats available";
  2117. return -1;
  2118. }
  2119. *answer = bridge_stats;
  2120. } else if (!strcmp(question, "status/fresh-relay-descs")) {
  2121. if (!server_mode(get_options())) {
  2122. *errmsg = "Only relays have descriptors";
  2123. return -1;
  2124. }
  2125. routerinfo_t *r;
  2126. extrainfo_t *e;
  2127. if (router_build_fresh_descriptor(&r, &e) < 0) {
  2128. *errmsg = "Error generating descriptor";
  2129. return -1;
  2130. }
  2131. size_t size = r->cache_info.signed_descriptor_len + 1;
  2132. if (e) {
  2133. size += e->cache_info.signed_descriptor_len + 1;
  2134. }
  2135. tor_assert(r->cache_info.signed_descriptor_len);
  2136. char *descs = tor_malloc(size);
  2137. char *cp = descs;
  2138. memcpy(cp, signed_descriptor_get_body(&r->cache_info),
  2139. r->cache_info.signed_descriptor_len);
  2140. cp += r->cache_info.signed_descriptor_len - 1;
  2141. if (e) {
  2142. if (cp[0] == '\0') {
  2143. cp[0] = '\n';
  2144. } else if (cp[0] != '\n') {
  2145. cp[1] = '\n';
  2146. cp++;
  2147. }
  2148. memcpy(cp, signed_descriptor_get_body(&e->cache_info),
  2149. e->cache_info.signed_descriptor_len);
  2150. cp += e->cache_info.signed_descriptor_len - 1;
  2151. }
  2152. if (cp[0] == '\n') {
  2153. cp[0] = '\0';
  2154. } else if (cp[0] != '\0') {
  2155. cp[1] = '\0';
  2156. }
  2157. *answer = descs;
  2158. routerinfo_free(r);
  2159. extrainfo_free(e);
  2160. } else {
  2161. return 0;
  2162. }
  2163. }
  2164. return 0;
  2165. }
  2166. /** Implementation helper for GETINFO: knows how to enumerate hidden services
  2167. * created via the control port. */
  2168. static int
  2169. getinfo_helper_onions(control_connection_t *control_conn,
  2170. const char *question, char **answer,
  2171. const char **errmsg)
  2172. {
  2173. smartlist_t *onion_list = NULL;
  2174. if (control_conn && !strcmp(question, "onions/current")) {
  2175. onion_list = control_conn->ephemeral_onion_services;
  2176. } else if (!strcmp(question, "onions/detached")) {
  2177. onion_list = detached_onion_services;
  2178. } else {
  2179. return 0;
  2180. }
  2181. if (!onion_list || smartlist_len(onion_list) == 0) {
  2182. if (errmsg) {
  2183. *errmsg = "No onion services of the specified type.";
  2184. }
  2185. return -1;
  2186. }
  2187. if (answer) {
  2188. *answer = smartlist_join_strings(onion_list, "\r\n", 0, NULL);
  2189. }
  2190. return 0;
  2191. }
  2192. /** Implementation helper for GETINFO: answers queries about network
  2193. * liveness. */
  2194. static int
  2195. getinfo_helper_liveness(control_connection_t *control_conn,
  2196. const char *question, char **answer,
  2197. const char **errmsg)
  2198. {
  2199. (void)control_conn;
  2200. (void)errmsg;
  2201. if (strcmp(question, "network-liveness") == 0) {
  2202. if (get_cached_network_liveness()) {
  2203. *answer = tor_strdup("up");
  2204. } else {
  2205. *answer = tor_strdup("down");
  2206. }
  2207. }
  2208. return 0;
  2209. }
  2210. /** Callback function for GETINFO: on a given control connection, try to
  2211. * answer the question <b>q</b> and store the newly-allocated answer in
  2212. * *<b>a</b>. If an internal error occurs, return -1 and optionally set
  2213. * *<b>error_out</b> to point to an error message to be delivered to the
  2214. * controller. On success, _or if the key is not recognized_, return 0. Do not
  2215. * set <b>a</b> if the key is not recognized.
  2216. */
  2217. typedef int (*getinfo_helper_t)(control_connection_t *,
  2218. const char *q, char **a,
  2219. const char **error_out);
  2220. /** A single item for the GETINFO question-to-answer-function table. */
  2221. typedef struct getinfo_item_t {
  2222. const char *varname; /**< The value (or prefix) of the question. */
  2223. getinfo_helper_t fn; /**< The function that knows the answer: NULL if
  2224. * this entry is documentation-only. */
  2225. const char *desc; /**< Description of the variable. */
  2226. int is_prefix; /** Must varname match exactly, or must it be a prefix? */
  2227. } getinfo_item_t;
  2228. #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
  2229. #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
  2230. #define DOC(name, desc) { name, NULL, desc, 0 }
  2231. /** Table mapping questions accepted by GETINFO to the functions that know how
  2232. * to answer them. */
  2233. static const getinfo_item_t getinfo_items[] = {
  2234. ITEM("version", misc, "The current version of Tor."),
  2235. ITEM("bw-event-cache", misc, "Cached BW events for a short interval."),
  2236. ITEM("config-file", misc, "Current location of the \"torrc\" file."),
  2237. ITEM("config-defaults-file", misc, "Current location of the defaults file."),
  2238. ITEM("config-text", misc,
  2239. "Return the string that would be written by a saveconf command."),
  2240. ITEM("accounting/bytes", accounting,
  2241. "Number of bytes read/written so far in the accounting interval."),
  2242. ITEM("accounting/bytes-left", accounting,
  2243. "Number of bytes left to write/read so far in the accounting interval."),
  2244. ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
  2245. ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
  2246. ITEM("accounting/interval-start", accounting,
  2247. "Time when the accounting period starts."),
  2248. ITEM("accounting/interval-end", accounting,
  2249. "Time when the accounting period ends."),
  2250. ITEM("accounting/interval-wake", accounting,
  2251. "Time to wake up in this accounting period."),
  2252. ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
  2253. ITEM("entry-guards", entry_guards,
  2254. "Which nodes are we using as entry guards?"),
  2255. ITEM("fingerprint", misc, NULL),
  2256. PREFIX("config/", config, "Current configuration values."),
  2257. DOC("config/names",
  2258. "List of configuration options, types, and documentation."),
  2259. DOC("config/defaults",
  2260. "List of default values for configuration options. "
  2261. "See also config/names"),
  2262. ITEM("info/names", misc,
  2263. "List of GETINFO options, types, and documentation."),
  2264. ITEM("events/names", misc,
  2265. "Events that the controller can ask for with SETEVENTS."),
  2266. ITEM("signal/names", misc, "Signal names recognized by the SIGNAL command"),
  2267. ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
  2268. PREFIX("desc/id/", dir, "Router descriptors by ID."),
  2269. PREFIX("desc/name/", dir, "Router descriptors by nickname."),
  2270. ITEM("desc/all-recent", dir,
  2271. "All non-expired, non-superseded router descriptors."),
  2272. ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
  2273. PREFIX("md/id/", dir, "Microdescriptors by ID"),
  2274. PREFIX("md/name/", dir, "Microdescriptors by name"),
  2275. PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
  2276. PREFIX("hs/client/desc/id", dir,
  2277. "Hidden Service descriptor in client's cache by onion."),
  2278. PREFIX("hs/service/desc/id/", dir,
  2279. "Hidden Service descriptor in services's cache by onion."),
  2280. PREFIX("net/listeners/", listeners, "Bound addresses by type"),
  2281. ITEM("ns/all", networkstatus,
  2282. "Brief summary of router status (v2 directory format)"),
  2283. PREFIX("ns/id/", networkstatus,
  2284. "Brief summary of router status by ID (v2 directory format)."),
  2285. PREFIX("ns/name/", networkstatus,
  2286. "Brief summary of router status by nickname (v2 directory format)."),
  2287. PREFIX("ns/purpose/", networkstatus,
  2288. "Brief summary of router status by purpose (v2 directory format)."),
  2289. PREFIX("consensus/", networkstatus,
  2290. "Information about and from the ns consensus."),
  2291. ITEM("network-status", dir,
  2292. "Brief summary of router status (v1 directory format)"),
  2293. ITEM("network-liveness", liveness,
  2294. "Current opinion on whether the network is live"),
  2295. ITEM("circuit-status", events, "List of current circuits originating here."),
  2296. ITEM("stream-status", events,"List of current streams."),
  2297. ITEM("orconn-status", events, "A list of current OR connections."),
  2298. ITEM("dormant", misc,
  2299. "Is Tor dormant (not building circuits because it's idle)?"),
  2300. PREFIX("address-mappings/", events, NULL),
  2301. DOC("address-mappings/all", "Current address mappings."),
  2302. DOC("address-mappings/cache", "Current cached DNS replies."),
  2303. DOC("address-mappings/config",
  2304. "Current address mappings from configuration."),
  2305. DOC("address-mappings/control", "Current address mappings from controller."),
  2306. PREFIX("status/", events, NULL),
  2307. DOC("status/circuit-established",
  2308. "Whether we think client functionality is working."),
  2309. DOC("status/enough-dir-info",
  2310. "Whether we have enough up-to-date directory information to build "
  2311. "circuits."),
  2312. DOC("status/bootstrap-phase",
  2313. "The last bootstrap phase status event that Tor sent."),
  2314. DOC("status/clients-seen",
  2315. "Breakdown of client countries seen by a bridge."),
  2316. DOC("status/fresh-relay-descs",
  2317. "A fresh relay/ei descriptor pair for Tor's current state. Not stored."),
  2318. DOC("status/version/recommended", "List of currently recommended versions."),
  2319. DOC("status/version/current", "Status of the current version."),
  2320. DOC("status/version/num-versioning", "Number of versioning authorities."),
  2321. DOC("status/version/num-concurring",
  2322. "Number of versioning authorities agreeing on the status of the "
  2323. "current version"),
  2324. ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
  2325. ITEM("traffic/read", misc,"Bytes read since the process was started."),
  2326. ITEM("traffic/written", misc,
  2327. "Bytes written since the process was started."),
  2328. ITEM("process/pid", misc, "Process id belonging to the main tor process."),
  2329. ITEM("process/uid", misc, "User id running the tor process."),
  2330. ITEM("process/user", misc,
  2331. "Username under which the tor process is running."),
  2332. ITEM("process/descriptor-limit", misc, "File descriptor limit."),
  2333. ITEM("limits/max-mem-in-queues", misc, "Actual limit on memory in queues"),
  2334. ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
  2335. PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
  2336. PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
  2337. PREFIX("dir/status/", dir,
  2338. "v2 networkstatus docs as retrieved from a DirPort."),
  2339. ITEM("dir/status-vote/current/consensus", dir,
  2340. "v3 Networkstatus consensus as retrieved from a DirPort."),
  2341. ITEM("exit-policy/default", policies,
  2342. "The default value appended to the configured exit policy."),
  2343. ITEM("exit-policy/reject-private/default", policies,
  2344. "The default rules appended to the configured exit policy by"
  2345. " ExitPolicyRejectPrivate."),
  2346. ITEM("exit-policy/reject-private/relay", policies,
  2347. "The relay-specific rules appended to the configured exit policy by"
  2348. " ExitPolicyRejectPrivate."),
  2349. ITEM("exit-policy/full", policies, "The entire exit policy of onion router"),
  2350. ITEM("exit-policy/ipv4", policies, "IPv4 parts of exit policy"),
  2351. ITEM("exit-policy/ipv6", policies, "IPv6 parts of exit policy"),
  2352. PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
  2353. ITEM("onions/current", onions,
  2354. "Onion services owned by the current control connection."),
  2355. ITEM("onions/detached", onions,
  2356. "Onion services detached from the control connection."),
  2357. { NULL, NULL, NULL, 0 }
  2358. };
  2359. /** Allocate and return a list of recognized GETINFO options. */
  2360. static char *
  2361. list_getinfo_options(void)
  2362. {
  2363. int i;
  2364. smartlist_t *lines = smartlist_new();
  2365. char *ans;
  2366. for (i = 0; getinfo_items[i].varname; ++i) {
  2367. if (!getinfo_items[i].desc)
  2368. continue;
  2369. smartlist_add_asprintf(lines, "%s%s -- %s\n",
  2370. getinfo_items[i].varname,
  2371. getinfo_items[i].is_prefix ? "*" : "",
  2372. getinfo_items[i].desc);
  2373. }
  2374. smartlist_sort_strings(lines);
  2375. ans = smartlist_join_strings(lines, "", 0, NULL);
  2376. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  2377. smartlist_free(lines);
  2378. return ans;
  2379. }
  2380. /** Lookup the 'getinfo' entry <b>question</b>, and return
  2381. * the answer in <b>*answer</b> (or NULL if key not recognized).
  2382. * Return 0 if success or unrecognized, or -1 if recognized but
  2383. * internal error. */
  2384. static int
  2385. handle_getinfo_helper(control_connection_t *control_conn,
  2386. const char *question, char **answer,
  2387. const char **err_out)
  2388. {
  2389. int i;
  2390. *answer = NULL; /* unrecognized key by default */
  2391. for (i = 0; getinfo_items[i].varname; ++i) {
  2392. int match;
  2393. if (getinfo_items[i].is_prefix)
  2394. match = !strcmpstart(question, getinfo_items[i].varname);
  2395. else
  2396. match = !strcmp(question, getinfo_items[i].varname);
  2397. if (match) {
  2398. tor_assert(getinfo_items[i].fn);
  2399. return getinfo_items[i].fn(control_conn, question, answer, err_out);
  2400. }
  2401. }
  2402. return 0; /* unrecognized */
  2403. }
  2404. /** Called when we receive a GETINFO command. Try to fetch all requested
  2405. * information, and reply with information or error message. */
  2406. static int
  2407. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  2408. const char *body)
  2409. {
  2410. smartlist_t *questions = smartlist_new();
  2411. smartlist_t *answers = smartlist_new();
  2412. smartlist_t *unrecognized = smartlist_new();
  2413. char *msg = NULL, *ans = NULL;
  2414. int i;
  2415. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2416. smartlist_split_string(questions, body, " ",
  2417. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2418. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  2419. const char *errmsg = NULL;
  2420. if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
  2421. if (!errmsg)
  2422. errmsg = "Internal error";
  2423. connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
  2424. goto done;
  2425. }
  2426. if (!ans) {
  2427. smartlist_add(unrecognized, (char*)q);
  2428. } else {
  2429. smartlist_add(answers, tor_strdup(q));
  2430. smartlist_add(answers, ans);
  2431. }
  2432. } SMARTLIST_FOREACH_END(q);
  2433. if (smartlist_len(unrecognized)) {
  2434. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  2435. connection_printf_to_buf(conn,
  2436. "552-Unrecognized key \"%s\"\r\n",
  2437. (char*)smartlist_get(unrecognized, i));
  2438. connection_printf_to_buf(conn,
  2439. "552 Unrecognized key \"%s\"\r\n",
  2440. (char*)smartlist_get(unrecognized, i));
  2441. goto done;
  2442. }
  2443. for (i = 0; i < smartlist_len(answers); i += 2) {
  2444. char *k = smartlist_get(answers, i);
  2445. char *v = smartlist_get(answers, i+1);
  2446. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  2447. connection_printf_to_buf(conn, "250-%s=", k);
  2448. connection_write_str_to_buf(v, conn);
  2449. connection_write_str_to_buf("\r\n", conn);
  2450. } else {
  2451. char *esc = NULL;
  2452. size_t esc_len;
  2453. esc_len = write_escaped_data(v, strlen(v), &esc);
  2454. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  2455. connection_write_to_buf(esc, esc_len, TO_CONN(conn));
  2456. tor_free(esc);
  2457. }
  2458. }
  2459. connection_write_str_to_buf("250 OK\r\n", conn);
  2460. done:
  2461. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  2462. smartlist_free(answers);
  2463. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  2464. smartlist_free(questions);
  2465. smartlist_free(unrecognized);
  2466. tor_free(msg);
  2467. return 0;
  2468. }
  2469. /** Given a string, convert it to a circuit purpose. */
  2470. static uint8_t
  2471. circuit_purpose_from_string(const char *string)
  2472. {
  2473. if (!strcasecmpstart(string, "purpose="))
  2474. string += strlen("purpose=");
  2475. if (!strcasecmp(string, "general"))
  2476. return CIRCUIT_PURPOSE_C_GENERAL;
  2477. else if (!strcasecmp(string, "controller"))
  2478. return CIRCUIT_PURPOSE_CONTROLLER;
  2479. else
  2480. return CIRCUIT_PURPOSE_UNKNOWN;
  2481. }
  2482. /** Return a newly allocated smartlist containing the arguments to the command
  2483. * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
  2484. * or if <b>max_args</b> is nonnegative and there are more than
  2485. * <b>max_args</b> arguments, send a 512 error to the controller, using
  2486. * <b>command</b> as the command name in the error message. */
  2487. static smartlist_t *
  2488. getargs_helper(const char *command, control_connection_t *conn,
  2489. const char *body, int min_args, int max_args)
  2490. {
  2491. smartlist_t *args = smartlist_new();
  2492. smartlist_split_string(args, body, " ",
  2493. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2494. if (smartlist_len(args) < min_args) {
  2495. connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
  2496. goto err;
  2497. } else if (max_args >= 0 && smartlist_len(args) > max_args) {
  2498. connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
  2499. goto err;
  2500. }
  2501. return args;
  2502. err:
  2503. SMARTLIST_FOREACH(args, char *, s, tor_free(s));
  2504. smartlist_free(args);
  2505. return NULL;
  2506. }
  2507. /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
  2508. * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
  2509. * such element exists. */
  2510. static const char *
  2511. find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
  2512. {
  2513. int i;
  2514. for (i = start_at; i < smartlist_len(sl); ++i) {
  2515. const char *elt = smartlist_get(sl, i);
  2516. if (!strcasecmpstart(elt, prefix))
  2517. return elt;
  2518. }
  2519. return NULL;
  2520. }
  2521. /** Helper. Return true iff s is an argument that we should treat as a
  2522. * key-value pair. */
  2523. static int
  2524. is_keyval_pair(const char *s)
  2525. {
  2526. /* An argument is a key-value pair if it has an =, and it isn't of the form
  2527. * $fingeprint=name */
  2528. return strchr(s, '=') && s[0] != '$';
  2529. }
  2530. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  2531. * circuit, and report success or failure. */
  2532. static int
  2533. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  2534. const char *body)
  2535. {
  2536. smartlist_t *router_nicknames=NULL, *nodes=NULL;
  2537. origin_circuit_t *circ = NULL;
  2538. int zero_circ;
  2539. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  2540. smartlist_t *args;
  2541. (void) len;
  2542. router_nicknames = smartlist_new();
  2543. args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
  2544. if (!args)
  2545. goto done;
  2546. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  2547. if (zero_circ) {
  2548. const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
  2549. if (purp) {
  2550. intended_purpose = circuit_purpose_from_string(purp);
  2551. if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2552. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2553. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2554. smartlist_free(args);
  2555. goto done;
  2556. }
  2557. }
  2558. if ((smartlist_len(args) == 1) ||
  2559. (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
  2560. // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
  2561. circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
  2562. if (!circ) {
  2563. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2564. } else {
  2565. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2566. (unsigned long)circ->global_identifier);
  2567. }
  2568. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2569. smartlist_free(args);
  2570. goto done;
  2571. }
  2572. // "EXTENDCIRCUIT 0 router1,router2" ||
  2573. // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
  2574. }
  2575. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  2576. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2577. (char*)smartlist_get(args, 0));
  2578. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2579. smartlist_free(args);
  2580. goto done;
  2581. }
  2582. if (smartlist_len(args) < 2) {
  2583. connection_printf_to_buf(conn,
  2584. "512 syntax error: not enough arguments.\r\n");
  2585. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2586. smartlist_free(args);
  2587. goto done;
  2588. }
  2589. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  2590. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2591. smartlist_free(args);
  2592. nodes = smartlist_new();
  2593. SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
  2594. const node_t *node = node_get_by_nickname(n, 1);
  2595. if (!node) {
  2596. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  2597. goto done;
  2598. }
  2599. if (!node_has_descriptor(node)) {
  2600. connection_printf_to_buf(conn, "552 No descriptor for \"%s\"\r\n", n);
  2601. goto done;
  2602. }
  2603. smartlist_add(nodes, (void*)node);
  2604. } SMARTLIST_FOREACH_END(n);
  2605. if (!smartlist_len(nodes)) {
  2606. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  2607. goto done;
  2608. }
  2609. if (zero_circ) {
  2610. /* start a new circuit */
  2611. circ = origin_circuit_init(intended_purpose, 0);
  2612. }
  2613. /* now circ refers to something that is ready to be extended */
  2614. int first_node = zero_circ;
  2615. SMARTLIST_FOREACH(nodes, const node_t *, node,
  2616. {
  2617. extend_info_t *info = extend_info_from_node(node, first_node);
  2618. if (first_node && !info) {
  2619. log_warn(LD_CONTROL,
  2620. "controller tried to connect to a node that doesn't have any "
  2621. "addresses that are allowed by the firewall configuration; "
  2622. "circuit marked for closing.");
  2623. circuit_mark_for_close(TO_CIRCUIT(circ), -END_CIRC_REASON_CONNECTFAILED);
  2624. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2625. goto done;
  2626. } else {
  2627. /* True, since node_has_descriptor(node) == true and we are extending
  2628. * to the node's primary address */
  2629. tor_assert(info);
  2630. }
  2631. circuit_append_new_exit(circ, info);
  2632. extend_info_free(info);
  2633. first_node = 0;
  2634. });
  2635. /* now that we've populated the cpath, start extending */
  2636. if (zero_circ) {
  2637. int err_reason = 0;
  2638. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  2639. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2640. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2641. goto done;
  2642. }
  2643. } else {
  2644. if (circ->base_.state == CIRCUIT_STATE_OPEN) {
  2645. int err_reason = 0;
  2646. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2647. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  2648. log_info(LD_CONTROL,
  2649. "send_next_onion_skin failed; circuit marked for closing.");
  2650. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2651. connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
  2652. goto done;
  2653. }
  2654. }
  2655. }
  2656. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2657. (unsigned long)circ->global_identifier);
  2658. if (zero_circ) /* send a 'launched' event, for completeness */
  2659. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  2660. done:
  2661. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  2662. smartlist_free(router_nicknames);
  2663. smartlist_free(nodes);
  2664. return 0;
  2665. }
  2666. /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
  2667. * circuit and it's a valid purpose, change it. */
  2668. static int
  2669. handle_control_setcircuitpurpose(control_connection_t *conn,
  2670. uint32_t len, const char *body)
  2671. {
  2672. origin_circuit_t *circ = NULL;
  2673. uint8_t new_purpose;
  2674. smartlist_t *args;
  2675. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2676. args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
  2677. if (!args)
  2678. goto done;
  2679. if (!(circ = get_circ(smartlist_get(args,0)))) {
  2680. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2681. (char*)smartlist_get(args, 0));
  2682. goto done;
  2683. }
  2684. {
  2685. const char *purp = find_element_starting_with(args,1,"PURPOSE=");
  2686. if (!purp) {
  2687. connection_write_str_to_buf("552 No purpose given\r\n", conn);
  2688. goto done;
  2689. }
  2690. new_purpose = circuit_purpose_from_string(purp);
  2691. if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2692. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2693. goto done;
  2694. }
  2695. }
  2696. circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
  2697. connection_write_str_to_buf("250 OK\r\n", conn);
  2698. done:
  2699. if (args) {
  2700. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2701. smartlist_free(args);
  2702. }
  2703. return 0;
  2704. }
  2705. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  2706. * stream, and report success or failure. */
  2707. static int
  2708. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  2709. const char *body)
  2710. {
  2711. entry_connection_t *ap_conn = NULL;
  2712. origin_circuit_t *circ = NULL;
  2713. int zero_circ;
  2714. smartlist_t *args;
  2715. crypt_path_t *cpath=NULL;
  2716. int hop=0, hop_line_ok=1;
  2717. (void) len;
  2718. args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
  2719. if (!args)
  2720. return 0;
  2721. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  2722. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  2723. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2724. (char*)smartlist_get(args, 0));
  2725. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  2726. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2727. (char*)smartlist_get(args, 1));
  2728. } else if (circ) {
  2729. const char *hopstring = find_element_starting_with(args,2,"HOP=");
  2730. if (hopstring) {
  2731. hopstring += strlen("HOP=");
  2732. hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
  2733. &hop_line_ok, NULL);
  2734. if (!hop_line_ok) { /* broken hop line */
  2735. connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
  2736. }
  2737. }
  2738. }
  2739. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2740. smartlist_free(args);
  2741. if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
  2742. return 0;
  2743. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
  2744. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
  2745. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
  2746. connection_write_str_to_buf(
  2747. "555 Connection is not managed by controller.\r\n",
  2748. conn);
  2749. return 0;
  2750. }
  2751. /* Do we need to detach it first? */
  2752. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
  2753. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2754. circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
  2755. connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
  2756. /* Un-mark it as ending, since we're going to reuse it. */
  2757. edge_conn->edge_has_sent_end = 0;
  2758. edge_conn->end_reason = 0;
  2759. if (tmpcirc)
  2760. circuit_detach_stream(tmpcirc, edge_conn);
  2761. CONNECTION_AP_EXPECT_NONPENDING(ap_conn);
  2762. TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  2763. }
  2764. if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
  2765. connection_write_str_to_buf(
  2766. "551 Can't attach stream to non-open origin circuit\r\n",
  2767. conn);
  2768. return 0;
  2769. }
  2770. /* Is this a single hop circuit? */
  2771. if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
  2772. const node_t *node = NULL;
  2773. char *exit_digest = NULL;
  2774. if (circ->build_state &&
  2775. circ->build_state->chosen_exit &&
  2776. !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
  2777. exit_digest = circ->build_state->chosen_exit->identity_digest;
  2778. node = node_get_by_id(exit_digest);
  2779. }
  2780. /* Do both the client and relay allow one-hop exit circuits? */
  2781. if (!node ||
  2782. !node_allows_single_hop_exits(node) ||
  2783. !get_options()->AllowSingleHopCircuits) {
  2784. connection_write_str_to_buf(
  2785. "551 Can't attach stream to this one-hop circuit.\r\n", conn);
  2786. return 0;
  2787. }
  2788. tor_assert(exit_digest);
  2789. ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
  2790. }
  2791. if (circ && hop>0) {
  2792. /* find this hop in the circuit, and set cpath */
  2793. cpath = circuit_get_cpath_hop(circ, hop);
  2794. if (!cpath) {
  2795. connection_printf_to_buf(conn,
  2796. "551 Circuit doesn't have %d hops.\r\n", hop);
  2797. return 0;
  2798. }
  2799. }
  2800. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
  2801. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  2802. return 0;
  2803. }
  2804. send_control_done(conn);
  2805. return 0;
  2806. }
  2807. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  2808. * descriptor, and report success or failure. */
  2809. static int
  2810. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  2811. const char *body)
  2812. {
  2813. char *desc;
  2814. const char *msg=NULL;
  2815. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  2816. int cache = 0; /* eventually, we may switch this to 1 */
  2817. const char *cp = memchr(body, '\n', len);
  2818. smartlist_t *args = smartlist_new();
  2819. tor_assert(cp);
  2820. ++cp;
  2821. char *cmdline = tor_memdup_nulterm(body, cp-body);
  2822. smartlist_split_string(args, cmdline, " ",
  2823. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2824. SMARTLIST_FOREACH_BEGIN(args, char *, option) {
  2825. if (!strcasecmpstart(option, "purpose=")) {
  2826. option += strlen("purpose=");
  2827. purpose = router_purpose_from_string(option);
  2828. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  2829. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  2830. option);
  2831. goto done;
  2832. }
  2833. } else if (!strcasecmpstart(option, "cache=")) {
  2834. option += strlen("cache=");
  2835. if (!strcasecmp(option, "no"))
  2836. cache = 0;
  2837. else if (!strcasecmp(option, "yes"))
  2838. cache = 1;
  2839. else {
  2840. connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
  2841. option);
  2842. goto done;
  2843. }
  2844. } else { /* unrecognized argument? */
  2845. connection_printf_to_buf(conn,
  2846. "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
  2847. goto done;
  2848. }
  2849. } SMARTLIST_FOREACH_END(option);
  2850. read_escaped_data(cp, len-(cp-body), &desc);
  2851. switch (router_load_single_router(desc, purpose, cache, &msg)) {
  2852. case -1:
  2853. if (!msg) msg = "Could not parse descriptor";
  2854. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  2855. break;
  2856. case 0:
  2857. if (!msg) msg = "Descriptor not added";
  2858. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  2859. break;
  2860. case 1:
  2861. send_control_done(conn);
  2862. break;
  2863. }
  2864. tor_free(desc);
  2865. done:
  2866. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  2867. smartlist_free(args);
  2868. tor_free(cmdline);
  2869. return 0;
  2870. }
  2871. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  2872. * address of the named AP stream, and report success or failure. */
  2873. static int
  2874. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  2875. const char *body)
  2876. {
  2877. entry_connection_t *ap_conn = NULL;
  2878. char *new_addr = NULL;
  2879. uint16_t new_port = 0;
  2880. smartlist_t *args;
  2881. (void) len;
  2882. args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
  2883. if (!args)
  2884. return 0;
  2885. if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  2886. || !ap_conn->socks_request) {
  2887. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2888. (char*)smartlist_get(args, 0));
  2889. } else {
  2890. int ok = 1;
  2891. if (smartlist_len(args) > 2) { /* they included a port too */
  2892. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  2893. 10, 1, 65535, &ok, NULL);
  2894. }
  2895. if (!ok) {
  2896. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  2897. (char*)smartlist_get(args, 2));
  2898. } else {
  2899. new_addr = tor_strdup(smartlist_get(args, 1));
  2900. }
  2901. }
  2902. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2903. smartlist_free(args);
  2904. if (!new_addr)
  2905. return 0;
  2906. strlcpy(ap_conn->socks_request->address, new_addr,
  2907. sizeof(ap_conn->socks_request->address));
  2908. if (new_port)
  2909. ap_conn->socks_request->port = new_port;
  2910. tor_free(new_addr);
  2911. send_control_done(conn);
  2912. return 0;
  2913. }
  2914. /** Called when we get a CLOSESTREAM command; try to close the named stream
  2915. * and report success or failure. */
  2916. static int
  2917. handle_control_closestream(control_connection_t *conn, uint32_t len,
  2918. const char *body)
  2919. {
  2920. entry_connection_t *ap_conn=NULL;
  2921. uint8_t reason=0;
  2922. smartlist_t *args;
  2923. int ok;
  2924. (void) len;
  2925. args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
  2926. if (!args)
  2927. return 0;
  2928. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  2929. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2930. (char*)smartlist_get(args, 0));
  2931. else {
  2932. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  2933. &ok, NULL);
  2934. if (!ok) {
  2935. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  2936. (char*)smartlist_get(args, 1));
  2937. ap_conn = NULL;
  2938. }
  2939. }
  2940. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2941. smartlist_free(args);
  2942. if (!ap_conn)
  2943. return 0;
  2944. connection_mark_unattached_ap(ap_conn, reason);
  2945. send_control_done(conn);
  2946. return 0;
  2947. }
  2948. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  2949. * and report success or failure. */
  2950. static int
  2951. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  2952. const char *body)
  2953. {
  2954. origin_circuit_t *circ = NULL;
  2955. int safe = 0;
  2956. smartlist_t *args;
  2957. (void) len;
  2958. args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
  2959. if (!args)
  2960. return 0;
  2961. if (!(circ=get_circ(smartlist_get(args, 0))))
  2962. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2963. (char*)smartlist_get(args, 0));
  2964. else {
  2965. int i;
  2966. for (i=1; i < smartlist_len(args); ++i) {
  2967. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  2968. safe = 1;
  2969. else
  2970. log_info(LD_CONTROL, "Skipping unknown option %s",
  2971. (char*)smartlist_get(args,i));
  2972. }
  2973. }
  2974. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2975. smartlist_free(args);
  2976. if (!circ)
  2977. return 0;
  2978. if (!safe || !circ->p_streams) {
  2979. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
  2980. }
  2981. send_control_done(conn);
  2982. return 0;
  2983. }
  2984. /** Called when we get a RESOLVE command: start trying to resolve
  2985. * the listed addresses. */
  2986. static int
  2987. handle_control_resolve(control_connection_t *conn, uint32_t len,
  2988. const char *body)
  2989. {
  2990. smartlist_t *args, *failed;
  2991. int is_reverse = 0;
  2992. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2993. if (!(conn->event_mask & (((event_mask_t)1)<<EVENT_ADDRMAP))) {
  2994. log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
  2995. "isn't listening for ADDRMAP events. It probably won't see "
  2996. "the answer.");
  2997. }
  2998. args = smartlist_new();
  2999. smartlist_split_string(args, body, " ",
  3000. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3001. {
  3002. const char *modearg = find_element_starting_with(args, 0, "mode=");
  3003. if (modearg && !strcasecmp(modearg, "mode=reverse"))
  3004. is_reverse = 1;
  3005. }
  3006. failed = smartlist_new();
  3007. SMARTLIST_FOREACH(args, const char *, arg, {
  3008. if (!is_keyval_pair(arg)) {
  3009. if (dnsserv_launch_request(arg, is_reverse, conn)<0)
  3010. smartlist_add(failed, (char*)arg);
  3011. }
  3012. });
  3013. send_control_done(conn);
  3014. SMARTLIST_FOREACH(failed, const char *, arg, {
  3015. control_event_address_mapped(arg, arg, time(NULL),
  3016. "internal", 0);
  3017. });
  3018. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3019. smartlist_free(args);
  3020. smartlist_free(failed);
  3021. return 0;
  3022. }
  3023. /** Called when we get a PROTOCOLINFO command: send back a reply. */
  3024. static int
  3025. handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
  3026. const char *body)
  3027. {
  3028. const char *bad_arg = NULL;
  3029. smartlist_t *args;
  3030. (void)len;
  3031. conn->have_sent_protocolinfo = 1;
  3032. args = smartlist_new();
  3033. smartlist_split_string(args, body, " ",
  3034. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3035. SMARTLIST_FOREACH(args, const char *, arg, {
  3036. int ok;
  3037. tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
  3038. if (!ok) {
  3039. bad_arg = arg;
  3040. break;
  3041. }
  3042. });
  3043. if (bad_arg) {
  3044. connection_printf_to_buf(conn, "513 No such version %s\r\n",
  3045. escaped(bad_arg));
  3046. /* Don't tolerate bad arguments when not authenticated. */
  3047. if (!STATE_IS_OPEN(TO_CONN(conn)->state))
  3048. connection_mark_for_close(TO_CONN(conn));
  3049. goto done;
  3050. } else {
  3051. const or_options_t *options = get_options();
  3052. int cookies = options->CookieAuthentication;
  3053. char *cfile = get_controller_cookie_file_name();
  3054. char *abs_cfile;
  3055. char *esc_cfile;
  3056. char *methods;
  3057. abs_cfile = make_path_absolute(cfile);
  3058. esc_cfile = esc_for_log(abs_cfile);
  3059. {
  3060. int passwd = (options->HashedControlPassword != NULL ||
  3061. options->HashedControlSessionPassword != NULL);
  3062. smartlist_t *mlist = smartlist_new();
  3063. if (cookies) {
  3064. smartlist_add(mlist, (char*)"COOKIE");
  3065. smartlist_add(mlist, (char*)"SAFECOOKIE");
  3066. }
  3067. if (passwd)
  3068. smartlist_add(mlist, (char*)"HASHEDPASSWORD");
  3069. if (!cookies && !passwd)
  3070. smartlist_add(mlist, (char*)"NULL");
  3071. methods = smartlist_join_strings(mlist, ",", 0, NULL);
  3072. smartlist_free(mlist);
  3073. }
  3074. connection_printf_to_buf(conn,
  3075. "250-PROTOCOLINFO 1\r\n"
  3076. "250-AUTH METHODS=%s%s%s\r\n"
  3077. "250-VERSION Tor=%s\r\n"
  3078. "250 OK\r\n",
  3079. methods,
  3080. cookies?" COOKIEFILE=":"",
  3081. cookies?esc_cfile:"",
  3082. escaped(VERSION));
  3083. tor_free(methods);
  3084. tor_free(cfile);
  3085. tor_free(abs_cfile);
  3086. tor_free(esc_cfile);
  3087. }
  3088. done:
  3089. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3090. smartlist_free(args);
  3091. return 0;
  3092. }
  3093. /** Called when we get an AUTHCHALLENGE command. */
  3094. static int
  3095. handle_control_authchallenge(control_connection_t *conn, uint32_t len,
  3096. const char *body)
  3097. {
  3098. const char *cp = body;
  3099. char *client_nonce;
  3100. size_t client_nonce_len;
  3101. char server_hash[DIGEST256_LEN];
  3102. char server_hash_encoded[HEX_DIGEST256_LEN+1];
  3103. char server_nonce[SAFECOOKIE_SERVER_NONCE_LEN];
  3104. char server_nonce_encoded[(2*SAFECOOKIE_SERVER_NONCE_LEN) + 1];
  3105. cp += strspn(cp, " \t\n\r");
  3106. if (!strcasecmpstart(cp, "SAFECOOKIE")) {
  3107. cp += strlen("SAFECOOKIE");
  3108. } else {
  3109. connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
  3110. "authentication\r\n", conn);
  3111. connection_mark_for_close(TO_CONN(conn));
  3112. return -1;
  3113. }
  3114. if (!authentication_cookie_is_set) {
  3115. connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
  3116. conn);
  3117. connection_mark_for_close(TO_CONN(conn));
  3118. return -1;
  3119. }
  3120. cp += strspn(cp, " \t\n\r");
  3121. if (*cp == '"') {
  3122. const char *newcp =
  3123. decode_escaped_string(cp, len - (cp - body),
  3124. &client_nonce, &client_nonce_len);
  3125. if (newcp == NULL) {
  3126. connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
  3127. conn);
  3128. connection_mark_for_close(TO_CONN(conn));
  3129. return -1;
  3130. }
  3131. cp = newcp;
  3132. } else {
  3133. size_t client_nonce_encoded_len = strspn(cp, "0123456789ABCDEFabcdef");
  3134. client_nonce_len = client_nonce_encoded_len / 2;
  3135. client_nonce = tor_malloc_zero(client_nonce_len);
  3136. if (base16_decode(client_nonce, client_nonce_len,
  3137. cp, client_nonce_encoded_len) < 0) {
  3138. connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
  3139. conn);
  3140. connection_mark_for_close(TO_CONN(conn));
  3141. tor_free(client_nonce);
  3142. return -1;
  3143. }
  3144. cp += client_nonce_encoded_len;
  3145. }
  3146. cp += strspn(cp, " \t\n\r");
  3147. if (*cp != '\0' ||
  3148. cp != body + len) {
  3149. connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
  3150. conn);
  3151. connection_mark_for_close(TO_CONN(conn));
  3152. tor_free(client_nonce);
  3153. return -1;
  3154. }
  3155. crypto_rand(server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
  3156. /* Now compute and send the server-to-controller response, and the
  3157. * server's nonce. */
  3158. tor_assert(authentication_cookie != NULL);
  3159. {
  3160. size_t tmp_len = (AUTHENTICATION_COOKIE_LEN +
  3161. client_nonce_len +
  3162. SAFECOOKIE_SERVER_NONCE_LEN);
  3163. char *tmp = tor_malloc_zero(tmp_len);
  3164. char *client_hash = tor_malloc_zero(DIGEST256_LEN);
  3165. memcpy(tmp, authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  3166. memcpy(tmp + AUTHENTICATION_COOKIE_LEN, client_nonce, client_nonce_len);
  3167. memcpy(tmp + AUTHENTICATION_COOKIE_LEN + client_nonce_len,
  3168. server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
  3169. crypto_hmac_sha256(server_hash,
  3170. SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT,
  3171. strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT),
  3172. tmp,
  3173. tmp_len);
  3174. crypto_hmac_sha256(client_hash,
  3175. SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT,
  3176. strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT),
  3177. tmp,
  3178. tmp_len);
  3179. conn->safecookie_client_hash = client_hash;
  3180. tor_free(tmp);
  3181. }
  3182. base16_encode(server_hash_encoded, sizeof(server_hash_encoded),
  3183. server_hash, sizeof(server_hash));
  3184. base16_encode(server_nonce_encoded, sizeof(server_nonce_encoded),
  3185. server_nonce, sizeof(server_nonce));
  3186. connection_printf_to_buf(conn,
  3187. "250 AUTHCHALLENGE SERVERHASH=%s "
  3188. "SERVERNONCE=%s\r\n",
  3189. server_hash_encoded,
  3190. server_nonce_encoded);
  3191. tor_free(client_nonce);
  3192. return 0;
  3193. }
  3194. /** Called when we get a USEFEATURE command: parse the feature list, and
  3195. * set up the control_connection's options properly. */
  3196. static int
  3197. handle_control_usefeature(control_connection_t *conn,
  3198. uint32_t len,
  3199. const char *body)
  3200. {
  3201. smartlist_t *args;
  3202. int bad = 0;
  3203. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3204. args = smartlist_new();
  3205. smartlist_split_string(args, body, " ",
  3206. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3207. SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
  3208. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  3209. ;
  3210. else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
  3211. ;
  3212. else {
  3213. connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
  3214. arg);
  3215. bad = 1;
  3216. break;
  3217. }
  3218. } SMARTLIST_FOREACH_END(arg);
  3219. if (!bad) {
  3220. send_control_done(conn);
  3221. }
  3222. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3223. smartlist_free(args);
  3224. return 0;
  3225. }
  3226. /** Implementation for the DROPGUARDS command. */
  3227. static int
  3228. handle_control_dropguards(control_connection_t *conn,
  3229. uint32_t len,
  3230. const char *body)
  3231. {
  3232. smartlist_t *args;
  3233. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3234. args = smartlist_new();
  3235. smartlist_split_string(args, body, " ",
  3236. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3237. if (smartlist_len(args)) {
  3238. connection_printf_to_buf(conn, "512 Too many arguments to DROPGUARDS\r\n");
  3239. } else {
  3240. remove_all_entry_guards();
  3241. send_control_done(conn);
  3242. }
  3243. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3244. smartlist_free(args);
  3245. return 0;
  3246. }
  3247. /** Implementation for the HSFETCH command. */
  3248. static int
  3249. handle_control_hsfetch(control_connection_t *conn, uint32_t len,
  3250. const char *body)
  3251. {
  3252. int i;
  3253. char digest[DIGEST_LEN], *hsaddress = NULL, *arg1 = NULL, *desc_id = NULL;
  3254. smartlist_t *args = NULL, *hsdirs = NULL;
  3255. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3256. static const char *hsfetch_command = "HSFETCH";
  3257. static const char *v2_str = "v2-";
  3258. const size_t v2_str_len = strlen(v2_str);
  3259. rend_data_t *rend_query = NULL;
  3260. /* Make sure we have at least one argument, the HSAddress. */
  3261. args = getargs_helper(hsfetch_command, conn, body, 1, -1);
  3262. if (!args) {
  3263. goto exit;
  3264. }
  3265. /* Extract the first argument (either HSAddress or DescID). */
  3266. arg1 = smartlist_get(args, 0);
  3267. /* Test if it's an HS address without the .onion part. */
  3268. if (rend_valid_service_id(arg1)) {
  3269. hsaddress = arg1;
  3270. } else if (strcmpstart(arg1, v2_str) == 0 &&
  3271. rend_valid_descriptor_id(arg1 + v2_str_len) &&
  3272. base32_decode(digest, sizeof(digest), arg1 + v2_str_len,
  3273. REND_DESC_ID_V2_LEN_BASE32) == 0) {
  3274. /* We have a well formed version 2 descriptor ID. Keep the decoded value
  3275. * of the id. */
  3276. desc_id = digest;
  3277. } else {
  3278. connection_printf_to_buf(conn, "513 Unrecognized \"%s\"\r\n",
  3279. arg1);
  3280. goto done;
  3281. }
  3282. static const char *opt_server = "SERVER=";
  3283. /* Skip first argument because it's the HSAddress or DescID. */
  3284. for (i = 1; i < smartlist_len(args); ++i) {
  3285. const char *arg = smartlist_get(args, i);
  3286. const node_t *node;
  3287. if (!strcasecmpstart(arg, opt_server)) {
  3288. const char *server;
  3289. server = arg + strlen(opt_server);
  3290. node = node_get_by_hex_id(server);
  3291. if (!node) {
  3292. connection_printf_to_buf(conn, "552 Server \"%s\" not found\r\n",
  3293. server);
  3294. goto done;
  3295. }
  3296. if (!hsdirs) {
  3297. /* Stores routerstatus_t object for each specified server. */
  3298. hsdirs = smartlist_new();
  3299. }
  3300. /* Valid server, add it to our local list. */
  3301. smartlist_add(hsdirs, node->rs);
  3302. } else {
  3303. connection_printf_to_buf(conn, "513 Unexpected argument \"%s\"\r\n",
  3304. arg);
  3305. goto done;
  3306. }
  3307. }
  3308. rend_query = rend_data_client_create(hsaddress, desc_id, NULL,
  3309. REND_NO_AUTH);
  3310. if (rend_query == NULL) {
  3311. connection_printf_to_buf(conn, "551 Error creating the HS query\r\n");
  3312. goto done;
  3313. }
  3314. /* Using a descriptor ID, we force the user to provide at least one
  3315. * hsdir server using the SERVER= option. */
  3316. if (desc_id && (!hsdirs || !smartlist_len(hsdirs))) {
  3317. connection_printf_to_buf(conn, "512 %s option is required\r\n",
  3318. opt_server);
  3319. goto done;
  3320. }
  3321. /* We are about to trigger HSDir fetch so send the OK now because after
  3322. * that 650 event(s) are possible so better to have the 250 OK before them
  3323. * to avoid out of order replies. */
  3324. send_control_done(conn);
  3325. /* Trigger the fetch using the built rend query and possibly a list of HS
  3326. * directory to use. This function ignores the client cache thus this will
  3327. * always send a fetch command. */
  3328. rend_client_fetch_v2_desc(rend_query, hsdirs);
  3329. done:
  3330. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3331. smartlist_free(args);
  3332. /* Contains data pointer that we don't own thus no cleanup. */
  3333. smartlist_free(hsdirs);
  3334. rend_data_free(rend_query);
  3335. exit:
  3336. return 0;
  3337. }
  3338. /** Implementation for the HSPOST command. */
  3339. static int
  3340. handle_control_hspost(control_connection_t *conn,
  3341. uint32_t len,
  3342. const char *body)
  3343. {
  3344. static const char *opt_server = "SERVER=";
  3345. smartlist_t *args = smartlist_new();
  3346. smartlist_t *hs_dirs = NULL;
  3347. const char *encoded_desc = body;
  3348. size_t encoded_desc_len = len;
  3349. char *cp = memchr(body, '\n', len);
  3350. char *argline = tor_strndup(body, cp-body);
  3351. /* If any SERVER= options were specified, try parse the options line */
  3352. if (!strcasecmpstart(argline, opt_server)) {
  3353. /* encoded_desc begins after a newline character */
  3354. cp = cp + 1;
  3355. encoded_desc = cp;
  3356. encoded_desc_len = len-(cp-body);
  3357. smartlist_split_string(args, argline, " ",
  3358. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3359. SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
  3360. if (!strcasecmpstart(arg, opt_server)) {
  3361. const char *server = arg + strlen(opt_server);
  3362. const node_t *node = node_get_by_hex_id(server);
  3363. if (!node || !node->rs) {
  3364. connection_printf_to_buf(conn, "552 Server \"%s\" not found\r\n",
  3365. server);
  3366. goto done;
  3367. }
  3368. if (!node->rs->is_hs_dir) {
  3369. connection_printf_to_buf(conn, "552 Server \"%s\" is not a HSDir"
  3370. "\r\n", server);
  3371. goto done;
  3372. }
  3373. /* Valid server, add it to our local list. */
  3374. if (!hs_dirs)
  3375. hs_dirs = smartlist_new();
  3376. smartlist_add(hs_dirs, node->rs);
  3377. } else {
  3378. connection_printf_to_buf(conn, "512 Unexpected argument \"%s\"\r\n",
  3379. arg);
  3380. goto done;
  3381. }
  3382. } SMARTLIST_FOREACH_END(arg);
  3383. }
  3384. /* Read the dot encoded descriptor, and parse it. */
  3385. rend_encoded_v2_service_descriptor_t *desc =
  3386. tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
  3387. read_escaped_data(encoded_desc, encoded_desc_len, &desc->desc_str);
  3388. rend_service_descriptor_t *parsed = NULL;
  3389. char *intro_content = NULL;
  3390. size_t intro_size;
  3391. size_t encoded_size;
  3392. const char *next_desc;
  3393. if (!rend_parse_v2_service_descriptor(&parsed, desc->desc_id, &intro_content,
  3394. &intro_size, &encoded_size,
  3395. &next_desc, desc->desc_str, 1)) {
  3396. /* Post the descriptor. */
  3397. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  3398. if (!rend_get_service_id(parsed->pk, serviceid)) {
  3399. smartlist_t *descs = smartlist_new();
  3400. smartlist_add(descs, desc);
  3401. /* We are about to trigger HS descriptor upload so send the OK now
  3402. * because after that 650 event(s) are possible so better to have the
  3403. * 250 OK before them to avoid out of order replies. */
  3404. send_control_done(conn);
  3405. /* Trigger the descriptor upload */
  3406. directory_post_to_hs_dir(parsed, descs, hs_dirs, serviceid, 0);
  3407. smartlist_free(descs);
  3408. }
  3409. rend_service_descriptor_free(parsed);
  3410. } else {
  3411. connection_printf_to_buf(conn, "554 Invalid descriptor\r\n");
  3412. }
  3413. tor_free(intro_content);
  3414. rend_encoded_v2_service_descriptor_free(desc);
  3415. done:
  3416. tor_free(argline);
  3417. smartlist_free(hs_dirs); /* Contents belong to the rend service code. */
  3418. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  3419. smartlist_free(args);
  3420. return 0;
  3421. }
  3422. /** Called when we get a ADD_ONION command; parse the body, and set up
  3423. * the new ephemeral Onion Service. */
  3424. static int
  3425. handle_control_add_onion(control_connection_t *conn,
  3426. uint32_t len,
  3427. const char *body)
  3428. {
  3429. smartlist_t *args;
  3430. size_t arg_len;
  3431. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3432. args = getargs_helper("ADD_ONION", conn, body, 2, -1);
  3433. if (!args)
  3434. return 0;
  3435. arg_len = smartlist_len(args);
  3436. /* Parse all of the arguments that do not involve handling cryptographic
  3437. * material first, since there's no reason to touch that at all if any of
  3438. * the other arguments are malformed.
  3439. */
  3440. smartlist_t *port_cfgs = smartlist_new();
  3441. smartlist_t *auth_clients = NULL;
  3442. smartlist_t *auth_created_clients = NULL;
  3443. int discard_pk = 0;
  3444. int detach = 0;
  3445. int max_streams = 0;
  3446. int max_streams_close_circuit = 0;
  3447. rend_auth_type_t auth_type = REND_NO_AUTH;
  3448. for (size_t i = 1; i < arg_len; i++) {
  3449. static const char *port_prefix = "Port=";
  3450. static const char *flags_prefix = "Flags=";
  3451. static const char *max_s_prefix = "MaxStreams=";
  3452. static const char *auth_prefix = "ClientAuth=";
  3453. const char *arg = smartlist_get(args, i);
  3454. if (!strcasecmpstart(arg, port_prefix)) {
  3455. /* "Port=VIRTPORT[,TARGET]". */
  3456. const char *port_str = arg + strlen(port_prefix);
  3457. rend_service_port_config_t *cfg =
  3458. rend_service_parse_port_config(port_str, ",", NULL);
  3459. if (!cfg) {
  3460. connection_printf_to_buf(conn, "512 Invalid VIRTPORT/TARGET\r\n");
  3461. goto out;
  3462. }
  3463. smartlist_add(port_cfgs, cfg);
  3464. } else if (!strcasecmpstart(arg, max_s_prefix)) {
  3465. /* "MaxStreams=[0..65535]". */
  3466. const char *max_s_str = arg + strlen(max_s_prefix);
  3467. int ok = 0;
  3468. max_streams = (int)tor_parse_long(max_s_str, 10, 0, 65535, &ok, NULL);
  3469. if (!ok) {
  3470. connection_printf_to_buf(conn, "512 Invalid MaxStreams\r\n");
  3471. goto out;
  3472. }
  3473. } else if (!strcasecmpstart(arg, flags_prefix)) {
  3474. /* "Flags=Flag[,Flag]", where Flag can be:
  3475. * * 'DiscardPK' - If tor generates the keypair, do not include it in
  3476. * the response.
  3477. * * 'Detach' - Do not tie this onion service to any particular control
  3478. * connection.
  3479. * * 'MaxStreamsCloseCircuit' - Close the circuit if MaxStreams is
  3480. * exceeded.
  3481. * * 'BasicAuth' - Client authorization using the 'basic' method.
  3482. */
  3483. static const char *discard_flag = "DiscardPK";
  3484. static const char *detach_flag = "Detach";
  3485. static const char *max_s_close_flag = "MaxStreamsCloseCircuit";
  3486. static const char *basicauth_flag = "BasicAuth";
  3487. smartlist_t *flags = smartlist_new();
  3488. int bad = 0;
  3489. smartlist_split_string(flags, arg + strlen(flags_prefix), ",",
  3490. SPLIT_IGNORE_BLANK, 0);
  3491. if (smartlist_len(flags) < 1) {
  3492. connection_printf_to_buf(conn, "512 Invalid 'Flags' argument\r\n");
  3493. bad = 1;
  3494. }
  3495. SMARTLIST_FOREACH_BEGIN(flags, const char *, flag)
  3496. {
  3497. if (!strcasecmp(flag, discard_flag)) {
  3498. discard_pk = 1;
  3499. } else if (!strcasecmp(flag, detach_flag)) {
  3500. detach = 1;
  3501. } else if (!strcasecmp(flag, max_s_close_flag)) {
  3502. max_streams_close_circuit = 1;
  3503. } else if (!strcasecmp(flag, basicauth_flag)) {
  3504. auth_type = REND_BASIC_AUTH;
  3505. } else {
  3506. connection_printf_to_buf(conn,
  3507. "512 Invalid 'Flags' argument: %s\r\n",
  3508. escaped(flag));
  3509. bad = 1;
  3510. break;
  3511. }
  3512. } SMARTLIST_FOREACH_END(flag);
  3513. SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
  3514. smartlist_free(flags);
  3515. if (bad)
  3516. goto out;
  3517. } else if (!strcasecmpstart(arg, auth_prefix)) {
  3518. char *err_msg = NULL;
  3519. int created = 0;
  3520. rend_authorized_client_t *client =
  3521. add_onion_helper_clientauth(arg + strlen(auth_prefix),
  3522. &created, &err_msg);
  3523. if (!client) {
  3524. if (err_msg) {
  3525. connection_write_str_to_buf(err_msg, conn);
  3526. tor_free(err_msg);
  3527. }
  3528. goto out;
  3529. }
  3530. if (auth_clients != NULL) {
  3531. int bad = 0;
  3532. SMARTLIST_FOREACH_BEGIN(auth_clients, rend_authorized_client_t *, ac) {
  3533. if (strcmp(ac->client_name, client->client_name) == 0) {
  3534. bad = 1;
  3535. break;
  3536. }
  3537. } SMARTLIST_FOREACH_END(ac);
  3538. if (bad) {
  3539. connection_printf_to_buf(conn,
  3540. "512 Duplicate name in ClientAuth\r\n");
  3541. rend_authorized_client_free(client);
  3542. goto out;
  3543. }
  3544. } else {
  3545. auth_clients = smartlist_new();
  3546. auth_created_clients = smartlist_new();
  3547. }
  3548. smartlist_add(auth_clients, client);
  3549. if (created) {
  3550. smartlist_add(auth_created_clients, client);
  3551. }
  3552. } else {
  3553. connection_printf_to_buf(conn, "513 Invalid argument\r\n");
  3554. goto out;
  3555. }
  3556. }
  3557. if (smartlist_len(port_cfgs) == 0) {
  3558. connection_printf_to_buf(conn, "512 Missing 'Port' argument\r\n");
  3559. goto out;
  3560. } else if (auth_type == REND_NO_AUTH && auth_clients != NULL) {
  3561. connection_printf_to_buf(conn, "512 No auth type specified\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 clients specified\r\n");
  3565. goto out;
  3566. } else if ((auth_type == REND_BASIC_AUTH &&
  3567. smartlist_len(auth_clients) > 512) ||
  3568. (auth_type == REND_STEALTH_AUTH &&
  3569. smartlist_len(auth_clients) > 16)) {
  3570. connection_printf_to_buf(conn, "512 Too many auth clients\r\n");
  3571. goto out;
  3572. }
  3573. /* Parse the "keytype:keyblob" argument. */
  3574. crypto_pk_t *pk = NULL;
  3575. const char *key_new_alg = NULL;
  3576. char *key_new_blob = NULL;
  3577. char *err_msg = NULL;
  3578. pk = add_onion_helper_keyarg(smartlist_get(args, 0), discard_pk,
  3579. &key_new_alg, &key_new_blob,
  3580. &err_msg);
  3581. if (!pk) {
  3582. if (err_msg) {
  3583. connection_write_str_to_buf(err_msg, conn);
  3584. tor_free(err_msg);
  3585. }
  3586. goto out;
  3587. }
  3588. tor_assert(!err_msg);
  3589. /* Create the HS, using private key pk, client authentication auth_type,
  3590. * the list of auth_clients, and port config port_cfg.
  3591. * rend_service_add_ephemeral() will take ownership of pk and port_cfg,
  3592. * regardless of success/failure.
  3593. */
  3594. char *service_id = NULL;
  3595. int ret = rend_service_add_ephemeral(pk, port_cfgs, max_streams,
  3596. max_streams_close_circuit,
  3597. auth_type, auth_clients,
  3598. &service_id);
  3599. port_cfgs = NULL; /* port_cfgs is now owned by the rendservice code. */
  3600. auth_clients = NULL; /* so is auth_clients */
  3601. switch (ret) {
  3602. case RSAE_OKAY:
  3603. {
  3604. if (detach) {
  3605. if (!detached_onion_services)
  3606. detached_onion_services = smartlist_new();
  3607. smartlist_add(detached_onion_services, service_id);
  3608. } else {
  3609. if (!conn->ephemeral_onion_services)
  3610. conn->ephemeral_onion_services = smartlist_new();
  3611. smartlist_add(conn->ephemeral_onion_services, service_id);
  3612. }
  3613. tor_assert(service_id);
  3614. connection_printf_to_buf(conn, "250-ServiceID=%s\r\n", service_id);
  3615. if (key_new_alg) {
  3616. tor_assert(key_new_blob);
  3617. connection_printf_to_buf(conn, "250-PrivateKey=%s:%s\r\n",
  3618. key_new_alg, key_new_blob);
  3619. }
  3620. if (auth_created_clients) {
  3621. SMARTLIST_FOREACH(auth_created_clients, rend_authorized_client_t *, ac, {
  3622. char *encoded = rend_auth_encode_cookie(ac->descriptor_cookie,
  3623. auth_type);
  3624. tor_assert(encoded);
  3625. connection_printf_to_buf(conn, "250-ClientAuth=%s:%s\r\n",
  3626. ac->client_name, encoded);
  3627. memwipe(encoded, 0, strlen(encoded));
  3628. tor_free(encoded);
  3629. });
  3630. }
  3631. connection_printf_to_buf(conn, "250 OK\r\n");
  3632. break;
  3633. }
  3634. case RSAE_BADPRIVKEY:
  3635. connection_printf_to_buf(conn, "551 Failed to generate onion address\r\n");
  3636. break;
  3637. case RSAE_ADDREXISTS:
  3638. connection_printf_to_buf(conn, "550 Onion address collision\r\n");
  3639. break;
  3640. case RSAE_BADVIRTPORT:
  3641. connection_printf_to_buf(conn, "512 Invalid VIRTPORT/TARGET\r\n");
  3642. break;
  3643. case RSAE_BADAUTH:
  3644. connection_printf_to_buf(conn, "512 Invalid client authorization\r\n");
  3645. break;
  3646. case RSAE_INTERNAL: /* FALLSTHROUGH */
  3647. default:
  3648. connection_printf_to_buf(conn, "551 Failed to add Onion Service\r\n");
  3649. }
  3650. if (key_new_blob) {
  3651. memwipe(key_new_blob, 0, strlen(key_new_blob));
  3652. tor_free(key_new_blob);
  3653. }
  3654. out:
  3655. if (port_cfgs) {
  3656. SMARTLIST_FOREACH(port_cfgs, rend_service_port_config_t*, p,
  3657. rend_service_port_config_free(p));
  3658. smartlist_free(port_cfgs);
  3659. }
  3660. if (auth_clients) {
  3661. SMARTLIST_FOREACH(auth_clients, rend_authorized_client_t *, ac,
  3662. rend_authorized_client_free(ac));
  3663. smartlist_free(auth_clients);
  3664. }
  3665. if (auth_created_clients) {
  3666. // Do not free entries; they are the same as auth_clients
  3667. smartlist_free(auth_created_clients);
  3668. }
  3669. SMARTLIST_FOREACH(args, char *, cp, {
  3670. memwipe(cp, 0, strlen(cp));
  3671. tor_free(cp);
  3672. });
  3673. smartlist_free(args);
  3674. return 0;
  3675. }
  3676. /** Helper function to handle parsing the KeyType:KeyBlob argument to the
  3677. * ADD_ONION command. Return a new crypto_pk_t and if a new key was generated
  3678. * and the private key not discarded, the algorithm and serialized private key,
  3679. * or NULL and an optional control protocol error message on failure. The
  3680. * caller is responsible for freeing the returned key_new_blob and err_msg.
  3681. *
  3682. * Note: The error messages returned are deliberately vague to avoid echoing
  3683. * key material.
  3684. */
  3685. STATIC crypto_pk_t *
  3686. add_onion_helper_keyarg(const char *arg, int discard_pk,
  3687. const char **key_new_alg_out, char **key_new_blob_out,
  3688. char **err_msg_out)
  3689. {
  3690. smartlist_t *key_args = smartlist_new();
  3691. crypto_pk_t *pk = NULL;
  3692. const char *key_new_alg = NULL;
  3693. char *key_new_blob = NULL;
  3694. char *err_msg = NULL;
  3695. int ok = 0;
  3696. smartlist_split_string(key_args, arg, ":", SPLIT_IGNORE_BLANK, 0);
  3697. if (smartlist_len(key_args) != 2) {
  3698. err_msg = tor_strdup("512 Invalid key type/blob\r\n");
  3699. goto err;
  3700. }
  3701. /* The format is "KeyType:KeyBlob". */
  3702. static const char *key_type_new = "NEW";
  3703. static const char *key_type_best = "BEST";
  3704. static const char *key_type_rsa1024 = "RSA1024";
  3705. const char *key_type = smartlist_get(key_args, 0);
  3706. const char *key_blob = smartlist_get(key_args, 1);
  3707. if (!strcasecmp(key_type_rsa1024, key_type)) {
  3708. /* "RSA:<Base64 Blob>" - Loading a pre-existing RSA1024 key. */
  3709. pk = crypto_pk_base64_decode(key_blob, strlen(key_blob));
  3710. if (!pk) {
  3711. err_msg = tor_strdup("512 Failed to decode RSA key\r\n");
  3712. goto err;
  3713. }
  3714. if (crypto_pk_num_bits(pk) != PK_BYTES*8) {
  3715. err_msg = tor_strdup("512 Invalid RSA key size\r\n");
  3716. goto err;
  3717. }
  3718. } else if (!strcasecmp(key_type_new, key_type)) {
  3719. /* "NEW:<Algorithm>" - Generating a new key, blob as algorithm. */
  3720. if (!strcasecmp(key_type_rsa1024, key_blob) ||
  3721. !strcasecmp(key_type_best, key_blob)) {
  3722. /* "RSA1024", RSA 1024 bit, also currently "BEST" by default. */
  3723. pk = crypto_pk_new();
  3724. if (crypto_pk_generate_key(pk)) {
  3725. tor_asprintf(&err_msg, "551 Failed to generate %s key\r\n",
  3726. key_type_rsa1024);
  3727. goto err;
  3728. }
  3729. if (!discard_pk) {
  3730. if (crypto_pk_base64_encode(pk, &key_new_blob)) {
  3731. tor_asprintf(&err_msg, "551 Failed to encode %s key\r\n",
  3732. key_type_rsa1024);
  3733. goto err;
  3734. }
  3735. key_new_alg = key_type_rsa1024;
  3736. }
  3737. } else {
  3738. err_msg = tor_strdup("513 Invalid key type\r\n");
  3739. goto err;
  3740. }
  3741. } else {
  3742. err_msg = tor_strdup("513 Invalid key type\r\n");
  3743. goto err;
  3744. }
  3745. /* Succeded in loading or generating a private key. */
  3746. tor_assert(pk);
  3747. ok = 1;
  3748. err:
  3749. SMARTLIST_FOREACH(key_args, char *, cp, {
  3750. memwipe(cp, 0, strlen(cp));
  3751. tor_free(cp);
  3752. });
  3753. smartlist_free(key_args);
  3754. if (!ok) {
  3755. crypto_pk_free(pk);
  3756. pk = NULL;
  3757. }
  3758. if (err_msg_out) {
  3759. *err_msg_out = err_msg;
  3760. } else {
  3761. tor_free(err_msg);
  3762. }
  3763. *key_new_alg_out = key_new_alg;
  3764. *key_new_blob_out = key_new_blob;
  3765. return pk;
  3766. }
  3767. /** Helper function to handle parsing a ClientAuth argument to the
  3768. * ADD_ONION command. Return a new rend_authorized_client_t, or NULL
  3769. * and an optional control protocol error message on failure. The
  3770. * caller is responsible for freeing the returned auth_client and err_msg.
  3771. *
  3772. * If 'created' is specified, it will be set to 1 when a new cookie has
  3773. * been generated.
  3774. */
  3775. STATIC rend_authorized_client_t *
  3776. add_onion_helper_clientauth(const char *arg, int *created, char **err_msg)
  3777. {
  3778. int ok = 0;
  3779. tor_assert(arg);
  3780. tor_assert(created);
  3781. tor_assert(err_msg);
  3782. *err_msg = NULL;
  3783. smartlist_t *auth_args = smartlist_new();
  3784. rend_authorized_client_t *client =
  3785. tor_malloc_zero(sizeof(rend_authorized_client_t));
  3786. smartlist_split_string(auth_args, arg, ":", 0, 0);
  3787. if (smartlist_len(auth_args) < 1 || smartlist_len(auth_args) > 2) {
  3788. *err_msg = tor_strdup("512 Invalid ClientAuth syntax\r\n");
  3789. goto err;
  3790. }
  3791. client->client_name = tor_strdup(smartlist_get(auth_args, 0));
  3792. if (smartlist_len(auth_args) == 2) {
  3793. char *decode_err_msg = NULL;
  3794. if (rend_auth_decode_cookie(smartlist_get(auth_args, 1),
  3795. client->descriptor_cookie,
  3796. NULL, &decode_err_msg) < 0) {
  3797. tor_assert(decode_err_msg);
  3798. tor_asprintf(err_msg, "512 %s\r\n", decode_err_msg);
  3799. tor_free(decode_err_msg);
  3800. goto err;
  3801. }
  3802. *created = 0;
  3803. } else {
  3804. crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
  3805. *created = 1;
  3806. }
  3807. if (!rend_valid_client_name(client->client_name)) {
  3808. *err_msg = tor_strdup("512 Invalid name in ClientAuth\r\n");
  3809. goto err;
  3810. }
  3811. ok = 1;
  3812. err:
  3813. SMARTLIST_FOREACH(auth_args, char *, arg, tor_free(arg));
  3814. smartlist_free(auth_args);
  3815. if (!ok) {
  3816. rend_authorized_client_free(client);
  3817. client = NULL;
  3818. }
  3819. return client;
  3820. }
  3821. /** Called when we get a DEL_ONION command; parse the body, and remove
  3822. * the existing ephemeral Onion Service. */
  3823. static int
  3824. handle_control_del_onion(control_connection_t *conn,
  3825. uint32_t len,
  3826. const char *body)
  3827. {
  3828. smartlist_t *args;
  3829. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3830. args = getargs_helper("DEL_ONION", conn, body, 1, 1);
  3831. if (!args)
  3832. return 0;
  3833. const char *service_id = smartlist_get(args, 0);
  3834. if (!rend_valid_service_id(service_id)) {
  3835. connection_printf_to_buf(conn, "512 Malformed Onion Service id\r\n");
  3836. goto out;
  3837. }
  3838. /* Determine if the onion service belongs to this particular control
  3839. * connection, or if it is in the global list of detached services. If it
  3840. * is in neither, either the service ID is invalid in some way, or it
  3841. * explicitly belongs to a different control connection, and an error
  3842. * should be returned.
  3843. */
  3844. smartlist_t *services[2] = {
  3845. conn->ephemeral_onion_services,
  3846. detached_onion_services
  3847. };
  3848. smartlist_t *onion_services = NULL;
  3849. int idx = -1;
  3850. for (size_t i = 0; i < ARRAY_LENGTH(services); i++) {
  3851. idx = smartlist_string_pos(services[i], service_id);
  3852. if (idx != -1) {
  3853. onion_services = services[i];
  3854. break;
  3855. }
  3856. }
  3857. if (onion_services == NULL) {
  3858. connection_printf_to_buf(conn, "552 Unknown Onion Service id\r\n");
  3859. } else {
  3860. int ret = rend_service_del_ephemeral(service_id);
  3861. if (ret) {
  3862. /* This should *NEVER* fail, since the service is on either the
  3863. * per-control connection list, or the global one.
  3864. */
  3865. log_warn(LD_BUG, "Failed to remove Onion Service %s.",
  3866. escaped(service_id));
  3867. tor_fragile_assert();
  3868. }
  3869. /* Remove/scrub the service_id from the appropriate list. */
  3870. char *cp = smartlist_get(onion_services, idx);
  3871. smartlist_del(onion_services, idx);
  3872. memwipe(cp, 0, strlen(cp));
  3873. tor_free(cp);
  3874. send_control_done(conn);
  3875. }
  3876. out:
  3877. SMARTLIST_FOREACH(args, char *, cp, {
  3878. memwipe(cp, 0, strlen(cp));
  3879. tor_free(cp);
  3880. });
  3881. smartlist_free(args);
  3882. return 0;
  3883. }
  3884. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  3885. int
  3886. connection_control_finished_flushing(control_connection_t *conn)
  3887. {
  3888. tor_assert(conn);
  3889. return 0;
  3890. }
  3891. /** Called when <b>conn</b> has gotten its socket closed. */
  3892. int
  3893. connection_control_reached_eof(control_connection_t *conn)
  3894. {
  3895. tor_assert(conn);
  3896. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  3897. connection_mark_for_close(TO_CONN(conn));
  3898. return 0;
  3899. }
  3900. /** Shut down this Tor instance in the same way that SIGINT would, but
  3901. * with a log message appropriate for the loss of an owning controller. */
  3902. static void
  3903. lost_owning_controller(const char *owner_type, const char *loss_manner)
  3904. {
  3905. log_notice(LD_CONTROL, "Owning controller %s has %s -- exiting now.",
  3906. owner_type, loss_manner);
  3907. activate_signal(SIGTERM);
  3908. }
  3909. /** Called when <b>conn</b> is being freed. */
  3910. void
  3911. connection_control_closed(control_connection_t *conn)
  3912. {
  3913. tor_assert(conn);
  3914. conn->event_mask = 0;
  3915. control_update_global_event_mask();
  3916. /* Close all ephemeral Onion Services if any.
  3917. * The list and it's contents are scrubbed/freed in connection_free_.
  3918. */
  3919. if (conn->ephemeral_onion_services) {
  3920. SMARTLIST_FOREACH(conn->ephemeral_onion_services, char *, cp, {
  3921. rend_service_del_ephemeral(cp);
  3922. });
  3923. }
  3924. if (conn->is_owning_control_connection) {
  3925. lost_owning_controller("connection", "closed");
  3926. }
  3927. }
  3928. /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
  3929. * stage of the protocol. */
  3930. static int
  3931. is_valid_initial_command(control_connection_t *conn, const char *cmd)
  3932. {
  3933. if (conn->base_.state == CONTROL_CONN_STATE_OPEN)
  3934. return 1;
  3935. if (!strcasecmp(cmd, "PROTOCOLINFO"))
  3936. return (!conn->have_sent_protocolinfo &&
  3937. conn->safecookie_client_hash == NULL);
  3938. if (!strcasecmp(cmd, "AUTHCHALLENGE"))
  3939. return (conn->safecookie_client_hash == NULL);
  3940. if (!strcasecmp(cmd, "AUTHENTICATE") ||
  3941. !strcasecmp(cmd, "QUIT"))
  3942. return 1;
  3943. return 0;
  3944. }
  3945. /** Do not accept any control command of more than 1MB in length. Anything
  3946. * that needs to be anywhere near this long probably means that one of our
  3947. * interfaces is broken. */
  3948. #define MAX_COMMAND_LINE_LENGTH (1024*1024)
  3949. /** Wrapper around peek_(evbuffer|buf)_has_control0 command: presents the same
  3950. * interface as those underlying functions, but takes a connection_t intead of
  3951. * an evbuffer or a buf_t.
  3952. */
  3953. static int
  3954. peek_connection_has_control0_command(connection_t *conn)
  3955. {
  3956. IF_HAS_BUFFEREVENT(conn, {
  3957. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  3958. return peek_evbuffer_has_control0_command(input);
  3959. }) ELSE_IF_NO_BUFFEREVENT {
  3960. return peek_buf_has_control0_command(conn->inbuf);
  3961. }
  3962. }
  3963. /** Called when data has arrived on a v1 control connection: Try to fetch
  3964. * commands from conn->inbuf, and execute them.
  3965. */
  3966. int
  3967. connection_control_process_inbuf(control_connection_t *conn)
  3968. {
  3969. size_t data_len;
  3970. uint32_t cmd_data_len;
  3971. int cmd_len;
  3972. char *args;
  3973. tor_assert(conn);
  3974. tor_assert(conn->base_.state == CONTROL_CONN_STATE_OPEN ||
  3975. conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH);
  3976. if (!conn->incoming_cmd) {
  3977. conn->incoming_cmd = tor_malloc(1024);
  3978. conn->incoming_cmd_len = 1024;
  3979. conn->incoming_cmd_cur_len = 0;
  3980. }
  3981. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  3982. peek_connection_has_control0_command(TO_CONN(conn))) {
  3983. /* Detect v0 commands and send a "no more v0" message. */
  3984. size_t body_len;
  3985. char buf[128];
  3986. set_uint16(buf+2, htons(0x0000)); /* type == error */
  3987. set_uint16(buf+4, htons(0x0001)); /* code == internal error */
  3988. strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
  3989. "and later; upgrade your controller.",
  3990. sizeof(buf)-6);
  3991. body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
  3992. set_uint16(buf+0, htons(body_len));
  3993. connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
  3994. connection_mark_and_flush(TO_CONN(conn));
  3995. return 0;
  3996. }
  3997. again:
  3998. while (1) {
  3999. size_t last_idx;
  4000. int r;
  4001. /* First, fetch a line. */
  4002. do {
  4003. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  4004. r = connection_fetch_from_buf_line(TO_CONN(conn),
  4005. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  4006. &data_len);
  4007. if (r == 0)
  4008. /* Line not all here yet. Wait. */
  4009. return 0;
  4010. else if (r == -1) {
  4011. if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
  4012. connection_write_str_to_buf("500 Line too long.\r\n", conn);
  4013. connection_stop_reading(TO_CONN(conn));
  4014. connection_mark_and_flush(TO_CONN(conn));
  4015. }
  4016. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  4017. conn->incoming_cmd_len *= 2;
  4018. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  4019. conn->incoming_cmd_len);
  4020. }
  4021. } while (r != 1);
  4022. tor_assert(data_len);
  4023. last_idx = conn->incoming_cmd_cur_len;
  4024. conn->incoming_cmd_cur_len += (int)data_len;
  4025. /* We have appended a line to incoming_cmd. Is the command done? */
  4026. if (last_idx == 0 && *conn->incoming_cmd != '+')
  4027. /* One line command, didn't start with '+'. */
  4028. break;
  4029. /* XXXX this code duplication is kind of dumb. */
  4030. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  4031. tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  4032. /* Just appended ".\r\n"; we're done. Remove it. */
  4033. conn->incoming_cmd[last_idx] = '\0';
  4034. conn->incoming_cmd_cur_len -= 3;
  4035. break;
  4036. } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
  4037. tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
  4038. /* Just appended ".\n"; we're done. Remove it. */
  4039. conn->incoming_cmd[last_idx] = '\0';
  4040. conn->incoming_cmd_cur_len -= 2;
  4041. break;
  4042. }
  4043. /* Otherwise, read another line. */
  4044. }
  4045. data_len = conn->incoming_cmd_cur_len;
  4046. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  4047. * recognize it.
  4048. */
  4049. cmd_len = 0;
  4050. while ((size_t)cmd_len < data_len
  4051. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  4052. ++cmd_len;
  4053. conn->incoming_cmd[cmd_len]='\0';
  4054. args = conn->incoming_cmd+cmd_len+1;
  4055. tor_assert(data_len>(size_t)cmd_len);
  4056. data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
  4057. while (TOR_ISSPACE(*args)) {
  4058. ++args;
  4059. --data_len;
  4060. }
  4061. /* If the connection is already closing, ignore further commands */
  4062. if (TO_CONN(conn)->marked_for_close) {
  4063. return 0;
  4064. }
  4065. /* Otherwise, Quit is always valid. */
  4066. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  4067. connection_write_str_to_buf("250 closing connection\r\n", conn);
  4068. connection_mark_and_flush(TO_CONN(conn));
  4069. return 0;
  4070. }
  4071. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  4072. !is_valid_initial_command(conn, conn->incoming_cmd)) {
  4073. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  4074. connection_mark_for_close(TO_CONN(conn));
  4075. return 0;
  4076. }
  4077. if (data_len >= UINT32_MAX) {
  4078. connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
  4079. connection_mark_for_close(TO_CONN(conn));
  4080. return 0;
  4081. }
  4082. /* XXXX Why is this not implemented as a table like the GETINFO
  4083. * items are? Even handling the plus signs at the beginnings of
  4084. * commands wouldn't be very hard with proper macros. */
  4085. cmd_data_len = (uint32_t)data_len;
  4086. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  4087. if (handle_control_setconf(conn, cmd_data_len, args))
  4088. return -1;
  4089. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  4090. if (handle_control_resetconf(conn, cmd_data_len, args))
  4091. return -1;
  4092. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  4093. if (handle_control_getconf(conn, cmd_data_len, args))
  4094. return -1;
  4095. } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
  4096. if (handle_control_loadconf(conn, cmd_data_len, args))
  4097. return -1;
  4098. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  4099. if (handle_control_setevents(conn, cmd_data_len, args))
  4100. return -1;
  4101. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  4102. if (handle_control_authenticate(conn, cmd_data_len, args))
  4103. return -1;
  4104. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  4105. if (handle_control_saveconf(conn, cmd_data_len, args))
  4106. return -1;
  4107. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  4108. if (handle_control_signal(conn, cmd_data_len, args))
  4109. return -1;
  4110. } else if (!strcasecmp(conn->incoming_cmd, "TAKEOWNERSHIP")) {
  4111. if (handle_control_takeownership(conn, cmd_data_len, args))
  4112. return -1;
  4113. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  4114. if (handle_control_mapaddress(conn, cmd_data_len, args))
  4115. return -1;
  4116. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  4117. if (handle_control_getinfo(conn, cmd_data_len, args))
  4118. return -1;
  4119. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  4120. if (handle_control_extendcircuit(conn, cmd_data_len, args))
  4121. return -1;
  4122. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  4123. if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
  4124. return -1;
  4125. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  4126. connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
  4127. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  4128. if (handle_control_attachstream(conn, cmd_data_len, args))
  4129. return -1;
  4130. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  4131. if (handle_control_postdescriptor(conn, cmd_data_len, args))
  4132. return -1;
  4133. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  4134. if (handle_control_redirectstream(conn, cmd_data_len, args))
  4135. return -1;
  4136. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  4137. if (handle_control_closestream(conn, cmd_data_len, args))
  4138. return -1;
  4139. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  4140. if (handle_control_closecircuit(conn, cmd_data_len, args))
  4141. return -1;
  4142. } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
  4143. if (handle_control_usefeature(conn, cmd_data_len, args))
  4144. return -1;
  4145. } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
  4146. if (handle_control_resolve(conn, cmd_data_len, args))
  4147. return -1;
  4148. } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
  4149. if (handle_control_protocolinfo(conn, cmd_data_len, args))
  4150. return -1;
  4151. } else if (!strcasecmp(conn->incoming_cmd, "AUTHCHALLENGE")) {
  4152. if (handle_control_authchallenge(conn, cmd_data_len, args))
  4153. return -1;
  4154. } else if (!strcasecmp(conn->incoming_cmd, "DROPGUARDS")) {
  4155. if (handle_control_dropguards(conn, cmd_data_len, args))
  4156. return -1;
  4157. } else if (!strcasecmp(conn->incoming_cmd, "HSFETCH")) {
  4158. if (handle_control_hsfetch(conn, cmd_data_len, args))
  4159. return -1;
  4160. } else if (!strcasecmp(conn->incoming_cmd, "+HSPOST")) {
  4161. if (handle_control_hspost(conn, cmd_data_len, args))
  4162. return -1;
  4163. } else if (!strcasecmp(conn->incoming_cmd, "ADD_ONION")) {
  4164. int ret = handle_control_add_onion(conn, cmd_data_len, args);
  4165. memwipe(args, 0, cmd_data_len); /* Scrub the private key. */
  4166. if (ret)
  4167. return -1;
  4168. } else if (!strcasecmp(conn->incoming_cmd, "DEL_ONION")) {
  4169. int ret = handle_control_del_onion(conn, cmd_data_len, args);
  4170. memwipe(args, 0, cmd_data_len); /* Scrub the service id/pk. */
  4171. if (ret)
  4172. return -1;
  4173. } else {
  4174. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  4175. conn->incoming_cmd);
  4176. }
  4177. conn->incoming_cmd_cur_len = 0;
  4178. goto again;
  4179. }
  4180. /** Something major has happened to circuit <b>circ</b>: tell any
  4181. * interested control connections. */
  4182. int
  4183. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
  4184. int reason_code)
  4185. {
  4186. const char *status;
  4187. char reasons[64] = "";
  4188. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  4189. return 0;
  4190. tor_assert(circ);
  4191. switch (tp)
  4192. {
  4193. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  4194. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  4195. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  4196. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  4197. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  4198. default:
  4199. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  4200. tor_fragile_assert();
  4201. return 0;
  4202. }
  4203. if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
  4204. const char *reason_str = circuit_end_reason_to_control_string(reason_code);
  4205. char unk_reason_buf[16];
  4206. if (!reason_str) {
  4207. tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
  4208. reason_str = unk_reason_buf;
  4209. }
  4210. if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
  4211. tor_snprintf(reasons, sizeof(reasons),
  4212. " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
  4213. } else {
  4214. tor_snprintf(reasons, sizeof(reasons),
  4215. " REASON=%s", reason_str);
  4216. }
  4217. }
  4218. {
  4219. char *circdesc = circuit_describe_status_for_controller(circ);
  4220. const char *sp = strlen(circdesc) ? " " : "";
  4221. send_control_event(EVENT_CIRCUIT_STATUS,
  4222. "650 CIRC %lu %s%s%s%s\r\n",
  4223. (unsigned long)circ->global_identifier,
  4224. status, sp,
  4225. circdesc,
  4226. reasons);
  4227. tor_free(circdesc);
  4228. }
  4229. return 0;
  4230. }
  4231. /** Something minor has happened to circuit <b>circ</b>: tell any
  4232. * interested control connections. */
  4233. static int
  4234. control_event_circuit_status_minor(origin_circuit_t *circ,
  4235. circuit_status_minor_event_t e,
  4236. int purpose, const struct timeval *tv)
  4237. {
  4238. const char *event_desc;
  4239. char event_tail[160] = "";
  4240. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
  4241. return 0;
  4242. tor_assert(circ);
  4243. switch (e)
  4244. {
  4245. case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
  4246. event_desc = "PURPOSE_CHANGED";
  4247. {
  4248. /* event_tail can currently be up to 68 chars long */
  4249. const char *hs_state_str =
  4250. circuit_purpose_to_controller_hs_state_string(purpose);
  4251. tor_snprintf(event_tail, sizeof(event_tail),
  4252. " OLD_PURPOSE=%s%s%s",
  4253. circuit_purpose_to_controller_string(purpose),
  4254. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  4255. (hs_state_str != NULL) ? hs_state_str : "");
  4256. }
  4257. break;
  4258. case CIRC_MINOR_EVENT_CANNIBALIZED:
  4259. event_desc = "CANNIBALIZED";
  4260. {
  4261. /* event_tail can currently be up to 130 chars long */
  4262. const char *hs_state_str =
  4263. circuit_purpose_to_controller_hs_state_string(purpose);
  4264. const struct timeval *old_timestamp_began = tv;
  4265. char tbuf[ISO_TIME_USEC_LEN+1];
  4266. format_iso_time_nospace_usec(tbuf, old_timestamp_began);
  4267. tor_snprintf(event_tail, sizeof(event_tail),
  4268. " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
  4269. circuit_purpose_to_controller_string(purpose),
  4270. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  4271. (hs_state_str != NULL) ? hs_state_str : "",
  4272. tbuf);
  4273. }
  4274. break;
  4275. default:
  4276. log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
  4277. tor_fragile_assert();
  4278. return 0;
  4279. }
  4280. {
  4281. char *circdesc = circuit_describe_status_for_controller(circ);
  4282. const char *sp = strlen(circdesc) ? " " : "";
  4283. send_control_event(EVENT_CIRCUIT_STATUS_MINOR,
  4284. "650 CIRC_MINOR %lu %s%s%s%s\r\n",
  4285. (unsigned long)circ->global_identifier,
  4286. event_desc, sp,
  4287. circdesc,
  4288. event_tail);
  4289. tor_free(circdesc);
  4290. }
  4291. return 0;
  4292. }
  4293. /**
  4294. * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
  4295. * interested controllers.
  4296. */
  4297. int
  4298. control_event_circuit_purpose_changed(origin_circuit_t *circ,
  4299. int old_purpose)
  4300. {
  4301. return control_event_circuit_status_minor(circ,
  4302. CIRC_MINOR_EVENT_PURPOSE_CHANGED,
  4303. old_purpose,
  4304. NULL);
  4305. }
  4306. /**
  4307. * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
  4308. * created-time from <b>old_tv_created</b>: tell any interested controllers.
  4309. */
  4310. int
  4311. control_event_circuit_cannibalized(origin_circuit_t *circ,
  4312. int old_purpose,
  4313. const struct timeval *old_tv_created)
  4314. {
  4315. return control_event_circuit_status_minor(circ,
  4316. CIRC_MINOR_EVENT_CANNIBALIZED,
  4317. old_purpose,
  4318. old_tv_created);
  4319. }
  4320. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  4321. * <b>buf</b>, determine the address:port combination requested on
  4322. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  4323. * failure. */
  4324. static int
  4325. write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
  4326. {
  4327. char buf2[256];
  4328. if (conn->chosen_exit_name)
  4329. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  4330. return -1;
  4331. if (!conn->socks_request)
  4332. return -1;
  4333. if (tor_snprintf(buf, len, "%s%s%s:%d",
  4334. conn->socks_request->address,
  4335. conn->chosen_exit_name ? buf2 : "",
  4336. !conn->chosen_exit_name && connection_edge_is_rendezvous_stream(
  4337. ENTRY_TO_EDGE_CONN(conn)) ? ".onion" : "",
  4338. conn->socks_request->port)<0)
  4339. return -1;
  4340. return 0;
  4341. }
  4342. /** Something has happened to the stream associated with AP connection
  4343. * <b>conn</b>: tell any interested control connections. */
  4344. int
  4345. control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
  4346. int reason_code)
  4347. {
  4348. char reason_buf[64];
  4349. char addrport_buf[64];
  4350. const char *status;
  4351. circuit_t *circ;
  4352. origin_circuit_t *origin_circ = NULL;
  4353. char buf[256];
  4354. const char *purpose = "";
  4355. tor_assert(conn->socks_request);
  4356. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  4357. return 0;
  4358. if (tp == STREAM_EVENT_CLOSED &&
  4359. (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
  4360. return 0;
  4361. write_stream_target_to_buf(conn, buf, sizeof(buf));
  4362. reason_buf[0] = '\0';
  4363. switch (tp)
  4364. {
  4365. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  4366. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  4367. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  4368. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  4369. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  4370. case STREAM_EVENT_NEW: status = "NEW"; break;
  4371. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  4372. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  4373. case STREAM_EVENT_REMAP: status = "REMAP"; break;
  4374. default:
  4375. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  4376. return 0;
  4377. }
  4378. if (reason_code && (tp == STREAM_EVENT_FAILED ||
  4379. tp == STREAM_EVENT_CLOSED ||
  4380. tp == STREAM_EVENT_FAILED_RETRIABLE)) {
  4381. const char *reason_str = stream_end_reason_to_control_string(reason_code);
  4382. char *r = NULL;
  4383. if (!reason_str) {
  4384. tor_asprintf(&r, " UNKNOWN_%d", reason_code);
  4385. reason_str = r;
  4386. }
  4387. if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
  4388. tor_snprintf(reason_buf, sizeof(reason_buf),
  4389. " REASON=END REMOTE_REASON=%s", reason_str);
  4390. else
  4391. tor_snprintf(reason_buf, sizeof(reason_buf),
  4392. " REASON=%s", reason_str);
  4393. tor_free(r);
  4394. } else if (reason_code && tp == STREAM_EVENT_REMAP) {
  4395. switch (reason_code) {
  4396. case REMAP_STREAM_SOURCE_CACHE:
  4397. strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
  4398. break;
  4399. case REMAP_STREAM_SOURCE_EXIT:
  4400. strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
  4401. break;
  4402. default:
  4403. tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
  4404. reason_code);
  4405. /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
  4406. break;
  4407. }
  4408. }
  4409. if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
  4410. /*
  4411. * When the control conn is an AF_UNIX socket and we have no address,
  4412. * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
  4413. * dnsserv.c.
  4414. */
  4415. if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
  4416. tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
  4417. ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
  4418. } else {
  4419. /*
  4420. * else leave it blank so control on AF_UNIX doesn't need to make
  4421. * something up.
  4422. */
  4423. addrport_buf[0] = '\0';
  4424. }
  4425. } else {
  4426. addrport_buf[0] = '\0';
  4427. }
  4428. if (tp == STREAM_EVENT_NEW_RESOLVE) {
  4429. purpose = " PURPOSE=DNS_REQUEST";
  4430. } else if (tp == STREAM_EVENT_NEW) {
  4431. if (conn->use_begindir) {
  4432. connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
  4433. int linked_dir_purpose = -1;
  4434. if (linked && linked->type == CONN_TYPE_DIR)
  4435. linked_dir_purpose = linked->purpose;
  4436. if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
  4437. purpose = " PURPOSE=DIR_UPLOAD";
  4438. else
  4439. purpose = " PURPOSE=DIR_FETCH";
  4440. } else
  4441. purpose = " PURPOSE=USER";
  4442. }
  4443. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  4444. if (circ && CIRCUIT_IS_ORIGIN(circ))
  4445. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  4446. send_control_event(EVENT_STREAM_STATUS,
  4447. "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
  4448. U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
  4449. status,
  4450. origin_circ?
  4451. (unsigned long)origin_circ->global_identifier : 0ul,
  4452. buf, reason_buf, addrport_buf, purpose);
  4453. /* XXX need to specify its intended exit, etc? */
  4454. return 0;
  4455. }
  4456. /** Figure out the best name for the target router of an OR connection
  4457. * <b>conn</b>, and write it into the <b>len</b>-character buffer
  4458. * <b>name</b>. */
  4459. static void
  4460. orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
  4461. {
  4462. const node_t *node = node_get_by_id(conn->identity_digest);
  4463. if (node) {
  4464. tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
  4465. node_get_verbose_nickname(node, name);
  4466. } else if (! tor_digest_is_zero(conn->identity_digest)) {
  4467. name[0] = '$';
  4468. base16_encode(name+1, len-1, conn->identity_digest,
  4469. DIGEST_LEN);
  4470. } else {
  4471. tor_snprintf(name, len, "%s:%d",
  4472. conn->base_.address, conn->base_.port);
  4473. }
  4474. }
  4475. /** Called when the status of an OR connection <b>conn</b> changes: tell any
  4476. * interested control connections. <b>tp</b> is the new status for the
  4477. * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
  4478. * may be the reason why.
  4479. */
  4480. int
  4481. control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
  4482. int reason)
  4483. {
  4484. int ncircs = 0;
  4485. const char *status;
  4486. char name[128];
  4487. char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
  4488. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  4489. return 0;
  4490. switch (tp)
  4491. {
  4492. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  4493. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  4494. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  4495. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  4496. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  4497. default:
  4498. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  4499. return 0;
  4500. }
  4501. if (conn->chan) {
  4502. ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
  4503. } else {
  4504. ncircs = 0;
  4505. }
  4506. ncircs += connection_or_get_num_circuits(conn);
  4507. if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
  4508. tor_snprintf(ncircs_buf, sizeof(ncircs_buf), " NCIRCS=%d", ncircs);
  4509. }
  4510. orconn_target_get_name(name, sizeof(name), conn);
  4511. send_control_event(EVENT_OR_CONN_STATUS,
  4512. "650 ORCONN %s %s%s%s%s ID="U64_FORMAT"\r\n",
  4513. name, status,
  4514. reason ? " REASON=" : "",
  4515. orconn_end_reason_to_control_string(reason),
  4516. ncircs_buf,
  4517. U64_PRINTF_ARG(conn->base_.global_identifier));
  4518. return 0;
  4519. }
  4520. /**
  4521. * Print out STREAM_BW event for a single conn
  4522. */
  4523. int
  4524. control_event_stream_bandwidth(edge_connection_t *edge_conn)
  4525. {
  4526. circuit_t *circ;
  4527. origin_circuit_t *ocirc;
  4528. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  4529. if (!edge_conn->n_read && !edge_conn->n_written)
  4530. return 0;
  4531. send_control_event(EVENT_STREAM_BANDWIDTH_USED,
  4532. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  4533. U64_PRINTF_ARG(edge_conn->base_.global_identifier),
  4534. (unsigned long)edge_conn->n_read,
  4535. (unsigned long)edge_conn->n_written);
  4536. circ = circuit_get_by_edge_conn(edge_conn);
  4537. if (circ && CIRCUIT_IS_ORIGIN(circ)) {
  4538. ocirc = TO_ORIGIN_CIRCUIT(circ);
  4539. ocirc->n_read_circ_bw += edge_conn->n_read;
  4540. ocirc->n_written_circ_bw += edge_conn->n_written;
  4541. }
  4542. edge_conn->n_written = edge_conn->n_read = 0;
  4543. }
  4544. return 0;
  4545. }
  4546. /** A second or more has elapsed: tell any interested control
  4547. * connections how much bandwidth streams have used. */
  4548. int
  4549. control_event_stream_bandwidth_used(void)
  4550. {
  4551. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  4552. smartlist_t *conns = get_connection_array();
  4553. edge_connection_t *edge_conn;
  4554. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
  4555. {
  4556. if (conn->type != CONN_TYPE_AP)
  4557. continue;
  4558. edge_conn = TO_EDGE_CONN(conn);
  4559. if (!edge_conn->n_read && !edge_conn->n_written)
  4560. continue;
  4561. send_control_event(EVENT_STREAM_BANDWIDTH_USED,
  4562. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  4563. U64_PRINTF_ARG(edge_conn->base_.global_identifier),
  4564. (unsigned long)edge_conn->n_read,
  4565. (unsigned long)edge_conn->n_written);
  4566. edge_conn->n_written = edge_conn->n_read = 0;
  4567. }
  4568. SMARTLIST_FOREACH_END(conn);
  4569. }
  4570. return 0;
  4571. }
  4572. /** A second or more has elapsed: tell any interested control connections
  4573. * how much bandwidth origin circuits have used. */
  4574. int
  4575. control_event_circ_bandwidth_used(void)
  4576. {
  4577. origin_circuit_t *ocirc;
  4578. if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
  4579. return 0;
  4580. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  4581. if (!CIRCUIT_IS_ORIGIN(circ))
  4582. continue;
  4583. ocirc = TO_ORIGIN_CIRCUIT(circ);
  4584. if (!ocirc->n_read_circ_bw && !ocirc->n_written_circ_bw)
  4585. continue;
  4586. send_control_event(EVENT_CIRC_BANDWIDTH_USED,
  4587. "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu\r\n",
  4588. ocirc->global_identifier,
  4589. (unsigned long)ocirc->n_read_circ_bw,
  4590. (unsigned long)ocirc->n_written_circ_bw);
  4591. ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
  4592. }
  4593. SMARTLIST_FOREACH_END(circ);
  4594. return 0;
  4595. }
  4596. /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
  4597. * bandwidth counters. */
  4598. int
  4599. control_event_conn_bandwidth(connection_t *conn)
  4600. {
  4601. const char *conn_type_str;
  4602. if (!get_options()->TestingEnableConnBwEvent ||
  4603. !EVENT_IS_INTERESTING(EVENT_CONN_BW))
  4604. return 0;
  4605. if (!conn->n_read_conn_bw && !conn->n_written_conn_bw)
  4606. return 0;
  4607. switch (conn->type) {
  4608. case CONN_TYPE_OR:
  4609. conn_type_str = "OR";
  4610. break;
  4611. case CONN_TYPE_DIR:
  4612. conn_type_str = "DIR";
  4613. break;
  4614. case CONN_TYPE_EXIT:
  4615. conn_type_str = "EXIT";
  4616. break;
  4617. default:
  4618. return 0;
  4619. }
  4620. send_control_event(EVENT_CONN_BW,
  4621. "650 CONN_BW ID="U64_FORMAT" TYPE=%s "
  4622. "READ=%lu WRITTEN=%lu\r\n",
  4623. U64_PRINTF_ARG(conn->global_identifier),
  4624. conn_type_str,
  4625. (unsigned long)conn->n_read_conn_bw,
  4626. (unsigned long)conn->n_written_conn_bw);
  4627. conn->n_written_conn_bw = conn->n_read_conn_bw = 0;
  4628. return 0;
  4629. }
  4630. /** A second or more has elapsed: tell any interested control
  4631. * connections how much bandwidth connections have used. */
  4632. int
  4633. control_event_conn_bandwidth_used(void)
  4634. {
  4635. if (get_options()->TestingEnableConnBwEvent &&
  4636. EVENT_IS_INTERESTING(EVENT_CONN_BW)) {
  4637. SMARTLIST_FOREACH(get_connection_array(), connection_t *, conn,
  4638. control_event_conn_bandwidth(conn));
  4639. }
  4640. return 0;
  4641. }
  4642. /** Helper: iterate over cell statistics of <b>circ</b> and sum up added
  4643. * cells, removed cells, and waiting times by cell command and direction.
  4644. * Store results in <b>cell_stats</b>. Free cell statistics of the
  4645. * circuit afterwards. */
  4646. void
  4647. sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
  4648. {
  4649. memset(cell_stats, 0, sizeof(cell_stats_t));
  4650. SMARTLIST_FOREACH_BEGIN(circ->testing_cell_stats,
  4651. const testing_cell_stats_entry_t *, ent) {
  4652. tor_assert(ent->command <= CELL_COMMAND_MAX_);
  4653. if (!ent->removed && !ent->exitward) {
  4654. cell_stats->added_cells_appward[ent->command] += 1;
  4655. } else if (!ent->removed && ent->exitward) {
  4656. cell_stats->added_cells_exitward[ent->command] += 1;
  4657. } else if (!ent->exitward) {
  4658. cell_stats->removed_cells_appward[ent->command] += 1;
  4659. cell_stats->total_time_appward[ent->command] += ent->waiting_time * 10;
  4660. } else {
  4661. cell_stats->removed_cells_exitward[ent->command] += 1;
  4662. cell_stats->total_time_exitward[ent->command] += ent->waiting_time * 10;
  4663. }
  4664. } SMARTLIST_FOREACH_END(ent);
  4665. circuit_clear_testing_cell_stats(circ);
  4666. }
  4667. /** Helper: append a cell statistics string to <code>event_parts</code>,
  4668. * prefixed with <code>key</code>=. Statistics consist of comma-separated
  4669. * key:value pairs with lower-case command strings as keys and cell
  4670. * numbers or total waiting times as values. A key:value pair is included
  4671. * if the entry in <code>include_if_non_zero</code> is not zero, but with
  4672. * the (possibly zero) entry from <code>number_to_include</code>. Both
  4673. * arrays are expected to have a length of CELL_COMMAND_MAX_ + 1. If no
  4674. * entry in <code>include_if_non_zero</code> is positive, no string will
  4675. * be added to <code>event_parts</code>. */
  4676. void
  4677. append_cell_stats_by_command(smartlist_t *event_parts, const char *key,
  4678. const uint64_t *include_if_non_zero,
  4679. const uint64_t *number_to_include)
  4680. {
  4681. smartlist_t *key_value_strings = smartlist_new();
  4682. int i;
  4683. for (i = 0; i <= CELL_COMMAND_MAX_; i++) {
  4684. if (include_if_non_zero[i] > 0) {
  4685. smartlist_add_asprintf(key_value_strings, "%s:"U64_FORMAT,
  4686. cell_command_to_string(i),
  4687. U64_PRINTF_ARG(number_to_include[i]));
  4688. }
  4689. }
  4690. if (smartlist_len(key_value_strings) > 0) {
  4691. char *joined = smartlist_join_strings(key_value_strings, ",", 0, NULL);
  4692. smartlist_add_asprintf(event_parts, "%s=%s", key, joined);
  4693. SMARTLIST_FOREACH(key_value_strings, char *, cp, tor_free(cp));
  4694. tor_free(joined);
  4695. }
  4696. smartlist_free(key_value_strings);
  4697. }
  4698. /** Helper: format <b>cell_stats</b> for <b>circ</b> for inclusion in a
  4699. * CELL_STATS event and write result string to <b>event_string</b>. */
  4700. void
  4701. format_cell_stats(char **event_string, circuit_t *circ,
  4702. cell_stats_t *cell_stats)
  4703. {
  4704. smartlist_t *event_parts = smartlist_new();
  4705. if (CIRCUIT_IS_ORIGIN(circ)) {
  4706. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  4707. smartlist_add_asprintf(event_parts, "ID=%lu",
  4708. (unsigned long)ocirc->global_identifier);
  4709. } else if (TO_OR_CIRCUIT(circ)->p_chan) {
  4710. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  4711. smartlist_add_asprintf(event_parts, "InboundQueue=%lu",
  4712. (unsigned long)or_circ->p_circ_id);
  4713. smartlist_add_asprintf(event_parts, "InboundConn="U64_FORMAT,
  4714. U64_PRINTF_ARG(or_circ->p_chan->global_identifier));
  4715. append_cell_stats_by_command(event_parts, "InboundAdded",
  4716. cell_stats->added_cells_appward,
  4717. cell_stats->added_cells_appward);
  4718. append_cell_stats_by_command(event_parts, "InboundRemoved",
  4719. cell_stats->removed_cells_appward,
  4720. cell_stats->removed_cells_appward);
  4721. append_cell_stats_by_command(event_parts, "InboundTime",
  4722. cell_stats->removed_cells_appward,
  4723. cell_stats->total_time_appward);
  4724. }
  4725. if (circ->n_chan) {
  4726. smartlist_add_asprintf(event_parts, "OutboundQueue=%lu",
  4727. (unsigned long)circ->n_circ_id);
  4728. smartlist_add_asprintf(event_parts, "OutboundConn="U64_FORMAT,
  4729. U64_PRINTF_ARG(circ->n_chan->global_identifier));
  4730. append_cell_stats_by_command(event_parts, "OutboundAdded",
  4731. cell_stats->added_cells_exitward,
  4732. cell_stats->added_cells_exitward);
  4733. append_cell_stats_by_command(event_parts, "OutboundRemoved",
  4734. cell_stats->removed_cells_exitward,
  4735. cell_stats->removed_cells_exitward);
  4736. append_cell_stats_by_command(event_parts, "OutboundTime",
  4737. cell_stats->removed_cells_exitward,
  4738. cell_stats->total_time_exitward);
  4739. }
  4740. *event_string = smartlist_join_strings(event_parts, " ", 0, NULL);
  4741. SMARTLIST_FOREACH(event_parts, char *, cp, tor_free(cp));
  4742. smartlist_free(event_parts);
  4743. }
  4744. /** A second or more has elapsed: tell any interested control connection
  4745. * how many cells have been processed for a given circuit. */
  4746. int
  4747. control_event_circuit_cell_stats(void)
  4748. {
  4749. cell_stats_t *cell_stats;
  4750. char *event_string;
  4751. if (!get_options()->TestingEnableCellStatsEvent ||
  4752. !EVENT_IS_INTERESTING(EVENT_CELL_STATS))
  4753. return 0;
  4754. cell_stats = tor_malloc(sizeof(cell_stats_t));;
  4755. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  4756. if (!circ->testing_cell_stats)
  4757. continue;
  4758. sum_up_cell_stats_by_command(circ, cell_stats);
  4759. format_cell_stats(&event_string, circ, cell_stats);
  4760. send_control_event(EVENT_CELL_STATS,
  4761. "650 CELL_STATS %s\r\n", event_string);
  4762. tor_free(event_string);
  4763. }
  4764. SMARTLIST_FOREACH_END(circ);
  4765. tor_free(cell_stats);
  4766. return 0;
  4767. }
  4768. /** Tokens in <b>bucket</b> have been refilled: the read bucket was empty
  4769. * for <b>read_empty_time</b> millis, the write bucket was empty for
  4770. * <b>write_empty_time</b> millis, and buckets were last refilled
  4771. * <b>milliseconds_elapsed</b> millis ago. Only emit TB_EMPTY event if
  4772. * either read or write bucket have been empty before. */
  4773. int
  4774. control_event_tb_empty(const char *bucket, uint32_t read_empty_time,
  4775. uint32_t write_empty_time,
  4776. int milliseconds_elapsed)
  4777. {
  4778. if (get_options()->TestingEnableTbEmptyEvent &&
  4779. EVENT_IS_INTERESTING(EVENT_TB_EMPTY) &&
  4780. (read_empty_time > 0 || write_empty_time > 0)) {
  4781. send_control_event(EVENT_TB_EMPTY,
  4782. "650 TB_EMPTY %s READ=%d WRITTEN=%d "
  4783. "LAST=%d\r\n",
  4784. bucket, read_empty_time, write_empty_time,
  4785. milliseconds_elapsed);
  4786. }
  4787. return 0;
  4788. }
  4789. /* about 5 minutes worth. */
  4790. #define N_BW_EVENTS_TO_CACHE 300
  4791. /* Index into cached_bw_events to next write. */
  4792. static int next_measurement_idx = 0;
  4793. /* number of entries set in n_measurements */
  4794. static int n_measurements = 0;
  4795. static struct cached_bw_event_s {
  4796. uint32_t n_read;
  4797. uint32_t n_written;
  4798. } cached_bw_events[N_BW_EVENTS_TO_CACHE];
  4799. /** A second or more has elapsed: tell any interested control
  4800. * connections how much bandwidth we used. */
  4801. int
  4802. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  4803. {
  4804. cached_bw_events[next_measurement_idx].n_read = n_read;
  4805. cached_bw_events[next_measurement_idx].n_written = n_written;
  4806. if (++next_measurement_idx == N_BW_EVENTS_TO_CACHE)
  4807. next_measurement_idx = 0;
  4808. if (n_measurements < N_BW_EVENTS_TO_CACHE)
  4809. ++n_measurements;
  4810. if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
  4811. send_control_event(EVENT_BANDWIDTH_USED,
  4812. "650 BW %lu %lu\r\n",
  4813. (unsigned long)n_read,
  4814. (unsigned long)n_written);
  4815. }
  4816. return 0;
  4817. }
  4818. STATIC char *
  4819. get_bw_samples(void)
  4820. {
  4821. int i;
  4822. int idx = (next_measurement_idx + N_BW_EVENTS_TO_CACHE - n_measurements)
  4823. % N_BW_EVENTS_TO_CACHE;
  4824. tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
  4825. smartlist_t *elements = smartlist_new();
  4826. for (i = 0; i < n_measurements; ++i) {
  4827. tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
  4828. const struct cached_bw_event_s *bwe = &cached_bw_events[idx];
  4829. smartlist_add_asprintf(elements, "%u,%u",
  4830. (unsigned)bwe->n_read,
  4831. (unsigned)bwe->n_written);
  4832. idx = (idx + 1) % N_BW_EVENTS_TO_CACHE;
  4833. }
  4834. char *result = smartlist_join_strings(elements, " ", 0, NULL);
  4835. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  4836. smartlist_free(elements);
  4837. return result;
  4838. }
  4839. /** Called when we are sending a log message to the controllers: suspend
  4840. * sending further log messages to the controllers until we're done. Used by
  4841. * CONN_LOG_PROTECT. */
  4842. void
  4843. disable_control_logging(void)
  4844. {
  4845. ++disable_log_messages;
  4846. }
  4847. /** We're done sending a log message to the controllers: re-enable controller
  4848. * logging. Used by CONN_LOG_PROTECT. */
  4849. void
  4850. enable_control_logging(void)
  4851. {
  4852. if (--disable_log_messages < 0)
  4853. tor_assert(0);
  4854. }
  4855. /** We got a log message: tell any interested control connections. */
  4856. void
  4857. control_event_logmsg(int severity, uint32_t domain, const char *msg)
  4858. {
  4859. int event;
  4860. /* Don't even think of trying to add stuff to a buffer from a cpuworker
  4861. * thread. */
  4862. if (! in_main_thread())
  4863. return;
  4864. if (disable_log_messages)
  4865. return;
  4866. if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
  4867. severity <= LOG_NOTICE) {
  4868. char *esc = esc_for_log(msg);
  4869. ++disable_log_messages;
  4870. control_event_general_status(severity, "BUG REASON=%s", esc);
  4871. --disable_log_messages;
  4872. tor_free(esc);
  4873. }
  4874. event = log_severity_to_event(severity);
  4875. if (event >= 0 && EVENT_IS_INTERESTING(event)) {
  4876. char *b = NULL;
  4877. const char *s;
  4878. if (strchr(msg, '\n')) {
  4879. char *cp;
  4880. b = tor_strdup(msg);
  4881. for (cp = b; *cp; ++cp)
  4882. if (*cp == '\r' || *cp == '\n')
  4883. *cp = ' ';
  4884. }
  4885. switch (severity) {
  4886. case LOG_DEBUG: s = "DEBUG"; break;
  4887. case LOG_INFO: s = "INFO"; break;
  4888. case LOG_NOTICE: s = "NOTICE"; break;
  4889. case LOG_WARN: s = "WARN"; break;
  4890. case LOG_ERR: s = "ERR"; break;
  4891. default: s = "UnknownLogSeverity"; break;
  4892. }
  4893. ++disable_log_messages;
  4894. send_control_event(event, "650 %s %s\r\n", s, b?b:msg);
  4895. if (severity == LOG_ERR) {
  4896. /* Force a flush, since we may be about to die horribly */
  4897. queued_events_flush_all(1);
  4898. }
  4899. --disable_log_messages;
  4900. tor_free(b);
  4901. }
  4902. }
  4903. /** Called whenever we receive new router descriptors: tell any
  4904. * interested control connections. <b>routers</b> is a list of
  4905. * routerinfo_t's.
  4906. */
  4907. int
  4908. control_event_descriptors_changed(smartlist_t *routers)
  4909. {
  4910. char *msg;
  4911. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  4912. return 0;
  4913. {
  4914. smartlist_t *names = smartlist_new();
  4915. char *ids;
  4916. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  4917. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  4918. router_get_verbose_nickname(b, ri);
  4919. smartlist_add(names, b);
  4920. });
  4921. ids = smartlist_join_strings(names, " ", 0, NULL);
  4922. tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
  4923. send_control_event_string(EVENT_NEW_DESC, msg);
  4924. tor_free(ids);
  4925. tor_free(msg);
  4926. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  4927. smartlist_free(names);
  4928. }
  4929. return 0;
  4930. }
  4931. /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
  4932. * <b>expires</b> values less than 3 are special; see connection_edge.c. If
  4933. * <b>error</b> is non-NULL, it is an error code describing the failure
  4934. * mode of the mapping.
  4935. */
  4936. int
  4937. control_event_address_mapped(const char *from, const char *to, time_t expires,
  4938. const char *error, const int cached)
  4939. {
  4940. if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
  4941. return 0;
  4942. if (expires < 3 || expires == TIME_MAX)
  4943. send_control_event(EVENT_ADDRMAP,
  4944. "650 ADDRMAP %s %s NEVER %s%s"
  4945. "CACHED=\"%s\"\r\n",
  4946. from, to, error?error:"", error?" ":"",
  4947. cached?"YES":"NO");
  4948. else {
  4949. char buf[ISO_TIME_LEN+1];
  4950. char buf2[ISO_TIME_LEN+1];
  4951. format_local_iso_time(buf,expires);
  4952. format_iso_time(buf2,expires);
  4953. send_control_event(EVENT_ADDRMAP,
  4954. "650 ADDRMAP %s %s \"%s\""
  4955. " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
  4956. from, to, buf,
  4957. error?error:"", error?" ":"",
  4958. buf2, cached?"YES":"NO");
  4959. }
  4960. return 0;
  4961. }
  4962. /** The authoritative dirserver has received a new descriptor that
  4963. * has passed basic syntax checks and is properly self-signed.
  4964. *
  4965. * Notify any interested party of the new descriptor and what has
  4966. * been done with it, and also optionally give an explanation/reason. */
  4967. int
  4968. control_event_or_authdir_new_descriptor(const char *action,
  4969. const char *desc, size_t desclen,
  4970. const char *msg)
  4971. {
  4972. char firstline[1024];
  4973. char *buf;
  4974. size_t totallen;
  4975. char *esc = NULL;
  4976. size_t esclen;
  4977. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  4978. return 0;
  4979. tor_snprintf(firstline, sizeof(firstline),
  4980. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  4981. action,
  4982. msg ? msg : "");
  4983. /* Escape the server descriptor properly */
  4984. esclen = write_escaped_data(desc, desclen, &esc);
  4985. totallen = strlen(firstline) + esclen + 1;
  4986. buf = tor_malloc(totallen);
  4987. strlcpy(buf, firstline, totallen);
  4988. strlcpy(buf+strlen(firstline), esc, totallen);
  4989. send_control_event_string(EVENT_AUTHDIR_NEWDESCS,
  4990. buf);
  4991. send_control_event_string(EVENT_AUTHDIR_NEWDESCS,
  4992. "650 OK\r\n");
  4993. tor_free(esc);
  4994. tor_free(buf);
  4995. return 0;
  4996. }
  4997. /** Cached liveness for network liveness events and GETINFO
  4998. */
  4999. static int network_is_live = 0;
  5000. static int
  5001. get_cached_network_liveness(void)
  5002. {
  5003. return network_is_live;
  5004. }
  5005. static void
  5006. set_cached_network_liveness(int liveness)
  5007. {
  5008. network_is_live = liveness;
  5009. }
  5010. /** The network liveness has changed; this is called from circuitstats.c
  5011. * whenever we receive a cell, or when timeout expires and we assume the
  5012. * network is down. */
  5013. int
  5014. control_event_network_liveness_update(int liveness)
  5015. {
  5016. if (liveness > 0) {
  5017. if (get_cached_network_liveness() <= 0) {
  5018. /* Update cached liveness */
  5019. set_cached_network_liveness(1);
  5020. log_debug(LD_CONTROL, "Sending NETWORK_LIVENESS UP");
  5021. send_control_event_string(EVENT_NETWORK_LIVENESS,
  5022. "650 NETWORK_LIVENESS UP\r\n");
  5023. }
  5024. /* else was already live, no-op */
  5025. } else {
  5026. if (get_cached_network_liveness() > 0) {
  5027. /* Update cached liveness */
  5028. set_cached_network_liveness(0);
  5029. log_debug(LD_CONTROL, "Sending NETWORK_LIVENESS DOWN");
  5030. send_control_event_string(EVENT_NETWORK_LIVENESS,
  5031. "650 NETWORK_LIVENESS DOWN\r\n");
  5032. }
  5033. /* else was already dead, no-op */
  5034. }
  5035. return 0;
  5036. }
  5037. /** Helper function for NS-style events. Constructs and sends an event
  5038. * of type <b>event</b> with string <b>event_string</b> out of the set of
  5039. * networkstatuses <b>statuses</b>. Currently it is used for NS events
  5040. * and NEWCONSENSUS events. */
  5041. static int
  5042. control_event_networkstatus_changed_helper(smartlist_t *statuses,
  5043. uint16_t event,
  5044. const char *event_string)
  5045. {
  5046. smartlist_t *strs;
  5047. char *s, *esc = NULL;
  5048. if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
  5049. return 0;
  5050. strs = smartlist_new();
  5051. smartlist_add(strs, tor_strdup("650+"));
  5052. smartlist_add(strs, tor_strdup(event_string));
  5053. smartlist_add(strs, tor_strdup("\r\n"));
  5054. SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
  5055. {
  5056. s = networkstatus_getinfo_helper_single(rs);
  5057. if (!s) continue;
  5058. smartlist_add(strs, s);
  5059. });
  5060. s = smartlist_join_strings(strs, "", 0, NULL);
  5061. write_escaped_data(s, strlen(s), &esc);
  5062. SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
  5063. smartlist_free(strs);
  5064. tor_free(s);
  5065. send_control_event_string(event, esc);
  5066. send_control_event_string(event,
  5067. "650 OK\r\n");
  5068. tor_free(esc);
  5069. return 0;
  5070. }
  5071. /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
  5072. * an NS event to any controller that cares. */
  5073. int
  5074. control_event_networkstatus_changed(smartlist_t *statuses)
  5075. {
  5076. return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
  5077. }
  5078. /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
  5079. * event consisting of an NS-style line for each relay in the consensus. */
  5080. int
  5081. control_event_newconsensus(const networkstatus_t *consensus)
  5082. {
  5083. if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
  5084. return 0;
  5085. return control_event_networkstatus_changed_helper(
  5086. consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
  5087. }
  5088. /** Called when we compute a new circuitbuildtimeout */
  5089. int
  5090. control_event_buildtimeout_set(buildtimeout_set_event_t type,
  5091. const char *args)
  5092. {
  5093. const char *type_string = NULL;
  5094. if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
  5095. return 0;
  5096. switch (type) {
  5097. case BUILDTIMEOUT_SET_EVENT_COMPUTED:
  5098. type_string = "COMPUTED";
  5099. break;
  5100. case BUILDTIMEOUT_SET_EVENT_RESET:
  5101. type_string = "RESET";
  5102. break;
  5103. case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
  5104. type_string = "SUSPENDED";
  5105. break;
  5106. case BUILDTIMEOUT_SET_EVENT_DISCARD:
  5107. type_string = "DISCARD";
  5108. break;
  5109. case BUILDTIMEOUT_SET_EVENT_RESUME:
  5110. type_string = "RESUME";
  5111. break;
  5112. default:
  5113. type_string = "UNKNOWN";
  5114. break;
  5115. }
  5116. send_control_event(EVENT_BUILDTIMEOUT_SET,
  5117. "650 BUILDTIMEOUT_SET %s %s\r\n",
  5118. type_string, args);
  5119. return 0;
  5120. }
  5121. /** Called when a signal has been processed from signal_callback */
  5122. int
  5123. control_event_signal(uintptr_t signal)
  5124. {
  5125. const char *signal_string = NULL;
  5126. if (!control_event_is_interesting(EVENT_GOT_SIGNAL))
  5127. return 0;
  5128. switch (signal) {
  5129. case SIGHUP:
  5130. signal_string = "RELOAD";
  5131. break;
  5132. case SIGUSR1:
  5133. signal_string = "DUMP";
  5134. break;
  5135. case SIGUSR2:
  5136. signal_string = "DEBUG";
  5137. break;
  5138. case SIGNEWNYM:
  5139. signal_string = "NEWNYM";
  5140. break;
  5141. case SIGCLEARDNSCACHE:
  5142. signal_string = "CLEARDNSCACHE";
  5143. break;
  5144. case SIGHEARTBEAT:
  5145. signal_string = "HEARTBEAT";
  5146. break;
  5147. default:
  5148. log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
  5149. (unsigned long)signal);
  5150. return -1;
  5151. }
  5152. send_control_event(EVENT_GOT_SIGNAL, "650 SIGNAL %s\r\n",
  5153. signal_string);
  5154. return 0;
  5155. }
  5156. /** Called when a single local_routerstatus_t has changed: Sends an NS event
  5157. * to any controller that cares. */
  5158. int
  5159. control_event_networkstatus_changed_single(const routerstatus_t *rs)
  5160. {
  5161. smartlist_t *statuses;
  5162. int r;
  5163. if (!EVENT_IS_INTERESTING(EVENT_NS))
  5164. return 0;
  5165. statuses = smartlist_new();
  5166. smartlist_add(statuses, (void*)rs);
  5167. r = control_event_networkstatus_changed(statuses);
  5168. smartlist_free(statuses);
  5169. return r;
  5170. }
  5171. /** Our own router descriptor has changed; tell any controllers that care.
  5172. */
  5173. int
  5174. control_event_my_descriptor_changed(void)
  5175. {
  5176. send_control_event(EVENT_DESCCHANGED, "650 DESCCHANGED\r\n");
  5177. return 0;
  5178. }
  5179. /** Helper: sends a status event where <b>type</b> is one of
  5180. * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
  5181. * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
  5182. * string corresponding to <b>args</b>. */
  5183. static int
  5184. control_event_status(int type, int severity, const char *format, va_list args)
  5185. {
  5186. char *user_buf = NULL;
  5187. char format_buf[160];
  5188. const char *status, *sev;
  5189. switch (type) {
  5190. case EVENT_STATUS_GENERAL:
  5191. status = "STATUS_GENERAL";
  5192. break;
  5193. case EVENT_STATUS_CLIENT:
  5194. status = "STATUS_CLIENT";
  5195. break;
  5196. case EVENT_STATUS_SERVER:
  5197. status = "STATUS_SERVER";
  5198. break;
  5199. default:
  5200. log_warn(LD_BUG, "Unrecognized status type %d", type);
  5201. return -1;
  5202. }
  5203. switch (severity) {
  5204. case LOG_NOTICE:
  5205. sev = "NOTICE";
  5206. break;
  5207. case LOG_WARN:
  5208. sev = "WARN";
  5209. break;
  5210. case LOG_ERR:
  5211. sev = "ERR";
  5212. break;
  5213. default:
  5214. log_warn(LD_BUG, "Unrecognized status severity %d", severity);
  5215. return -1;
  5216. }
  5217. if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
  5218. status, sev)<0) {
  5219. log_warn(LD_BUG, "Format string too long.");
  5220. return -1;
  5221. }
  5222. tor_vasprintf(&user_buf, format, args);
  5223. send_control_event(type, "%s %s\r\n", format_buf, user_buf);
  5224. tor_free(user_buf);
  5225. return 0;
  5226. }
  5227. #define CONTROL_EVENT_STATUS_BODY(event, sev) \
  5228. int r; \
  5229. do { \
  5230. va_list ap; \
  5231. if (!EVENT_IS_INTERESTING(event)) \
  5232. return 0; \
  5233. \
  5234. va_start(ap, format); \
  5235. r = control_event_status((event), (sev), format, ap); \
  5236. va_end(ap); \
  5237. } while (0)
  5238. /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
  5239. * by formatting the arguments using the printf-style <b>format</b>. */
  5240. int
  5241. control_event_general_status(int severity, const char *format, ...)
  5242. {
  5243. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, severity);
  5244. return r;
  5245. }
  5246. /** Format and send an EVENT_STATUS_GENERAL LOG_ERR event, and flush it to the
  5247. * controller(s) immediately. */
  5248. int
  5249. control_event_general_error(const char *format, ...)
  5250. {
  5251. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, LOG_ERR);
  5252. /* Force a flush, since we may be about to die horribly */
  5253. queued_events_flush_all(1);
  5254. return r;
  5255. }
  5256. /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
  5257. * by formatting the arguments using the printf-style <b>format</b>. */
  5258. int
  5259. control_event_client_status(int severity, const char *format, ...)
  5260. {
  5261. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, severity);
  5262. return r;
  5263. }
  5264. /** Format and send an EVENT_STATUS_CLIENT LOG_ERR event, and flush it to the
  5265. * controller(s) immediately. */
  5266. int
  5267. control_event_client_error(const char *format, ...)
  5268. {
  5269. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, LOG_ERR);
  5270. /* Force a flush, since we may be about to die horribly */
  5271. queued_events_flush_all(1);
  5272. return r;
  5273. }
  5274. /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
  5275. * by formatting the arguments using the printf-style <b>format</b>. */
  5276. int
  5277. control_event_server_status(int severity, const char *format, ...)
  5278. {
  5279. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, severity);
  5280. return r;
  5281. }
  5282. /** Format and send an EVENT_STATUS_SERVER LOG_ERR event, and flush it to the
  5283. * controller(s) immediately. */
  5284. int
  5285. control_event_server_error(const char *format, ...)
  5286. {
  5287. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, LOG_ERR);
  5288. /* Force a flush, since we may be about to die horribly */
  5289. queued_events_flush_all(1);
  5290. return r;
  5291. }
  5292. /** Called when the status of an entry guard with the given <b>nickname</b>
  5293. * and identity <b>digest</b> has changed to <b>status</b>: tells any
  5294. * controllers that care. */
  5295. int
  5296. control_event_guard(const char *nickname, const char *digest,
  5297. const char *status)
  5298. {
  5299. char hbuf[HEX_DIGEST_LEN+1];
  5300. base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
  5301. if (!EVENT_IS_INTERESTING(EVENT_GUARD))
  5302. return 0;
  5303. {
  5304. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  5305. const node_t *node = node_get_by_id(digest);
  5306. if (node) {
  5307. node_get_verbose_nickname(node, buf);
  5308. } else {
  5309. tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
  5310. }
  5311. send_control_event(EVENT_GUARD,
  5312. "650 GUARD ENTRY %s %s\r\n", buf, status);
  5313. }
  5314. return 0;
  5315. }
  5316. /** Called when a configuration option changes. This is generally triggered
  5317. * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
  5318. * a smartlist_t containing (key, value, ...) pairs in sequence.
  5319. * <b>value</b> can be NULL. */
  5320. int
  5321. control_event_conf_changed(const smartlist_t *elements)
  5322. {
  5323. int i;
  5324. char *result;
  5325. smartlist_t *lines;
  5326. if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) ||
  5327. smartlist_len(elements) == 0) {
  5328. return 0;
  5329. }
  5330. lines = smartlist_new();
  5331. for (i = 0; i < smartlist_len(elements); i += 2) {
  5332. char *k = smartlist_get(elements, i);
  5333. char *v = smartlist_get(elements, i+1);
  5334. if (v == NULL) {
  5335. smartlist_add_asprintf(lines, "650-%s", k);
  5336. } else {
  5337. smartlist_add_asprintf(lines, "650-%s=%s", k, v);
  5338. }
  5339. }
  5340. result = smartlist_join_strings(lines, "\r\n", 0, NULL);
  5341. send_control_event(EVENT_CONF_CHANGED,
  5342. "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
  5343. tor_free(result);
  5344. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  5345. smartlist_free(lines);
  5346. return 0;
  5347. }
  5348. /** Helper: Return a newly allocated string containing a path to the
  5349. * file where we store our authentication cookie. */
  5350. char *
  5351. get_controller_cookie_file_name(void)
  5352. {
  5353. const or_options_t *options = get_options();
  5354. if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
  5355. return tor_strdup(options->CookieAuthFile);
  5356. } else {
  5357. return get_datadir_fname("control_auth_cookie");
  5358. }
  5359. }
  5360. /* Initialize the cookie-based authentication system of the
  5361. * ControlPort. If <b>enabled</b> is 0, then disable the cookie
  5362. * authentication system. */
  5363. int
  5364. init_control_cookie_authentication(int enabled)
  5365. {
  5366. char *fname = NULL;
  5367. int retval;
  5368. if (!enabled) {
  5369. authentication_cookie_is_set = 0;
  5370. return 0;
  5371. }
  5372. fname = get_controller_cookie_file_name();
  5373. retval = init_cookie_authentication(fname, "", /* no header */
  5374. AUTHENTICATION_COOKIE_LEN,
  5375. get_options()->CookieAuthFileGroupReadable,
  5376. &authentication_cookie,
  5377. &authentication_cookie_is_set);
  5378. tor_free(fname);
  5379. return retval;
  5380. }
  5381. /** A copy of the process specifier of Tor's owning controller, or
  5382. * NULL if this Tor instance is not currently owned by a process. */
  5383. static char *owning_controller_process_spec = NULL;
  5384. /** A process-termination monitor for Tor's owning controller, or NULL
  5385. * if this Tor instance is not currently owned by a process. */
  5386. static tor_process_monitor_t *owning_controller_process_monitor = NULL;
  5387. /** Process-termination monitor callback for Tor's owning controller
  5388. * process. */
  5389. static void
  5390. owning_controller_procmon_cb(void *unused)
  5391. {
  5392. (void)unused;
  5393. lost_owning_controller("process", "vanished");
  5394. }
  5395. /** Set <b>process_spec</b> as Tor's owning controller process.
  5396. * Exit on failure. */
  5397. void
  5398. monitor_owning_controller_process(const char *process_spec)
  5399. {
  5400. const char *msg;
  5401. tor_assert((owning_controller_process_spec == NULL) ==
  5402. (owning_controller_process_monitor == NULL));
  5403. if (owning_controller_process_spec != NULL) {
  5404. if ((process_spec != NULL) && !strcmp(process_spec,
  5405. owning_controller_process_spec)) {
  5406. /* Same process -- return now, instead of disposing of and
  5407. * recreating the process-termination monitor. */
  5408. return;
  5409. }
  5410. /* We are currently owned by a process, and we should no longer be
  5411. * owned by it. Free the process-termination monitor. */
  5412. tor_process_monitor_free(owning_controller_process_monitor);
  5413. owning_controller_process_monitor = NULL;
  5414. tor_free(owning_controller_process_spec);
  5415. owning_controller_process_spec = NULL;
  5416. }
  5417. tor_assert((owning_controller_process_spec == NULL) &&
  5418. (owning_controller_process_monitor == NULL));
  5419. if (process_spec == NULL)
  5420. return;
  5421. owning_controller_process_spec = tor_strdup(process_spec);
  5422. owning_controller_process_monitor =
  5423. tor_process_monitor_new(tor_libevent_get_base(),
  5424. owning_controller_process_spec,
  5425. LD_CONTROL,
  5426. owning_controller_procmon_cb, NULL,
  5427. &msg);
  5428. if (owning_controller_process_monitor == NULL) {
  5429. log_err(LD_BUG, "Couldn't create process-termination monitor for "
  5430. "owning controller: %s. Exiting.",
  5431. msg);
  5432. owning_controller_process_spec = NULL;
  5433. tor_cleanup();
  5434. exit(0);
  5435. }
  5436. }
  5437. /** Convert the name of a bootstrapping phase <b>s</b> into strings
  5438. * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
  5439. static int
  5440. bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
  5441. const char **summary)
  5442. {
  5443. switch (s) {
  5444. case BOOTSTRAP_STATUS_UNDEF:
  5445. *tag = "undef";
  5446. *summary = "Undefined";
  5447. break;
  5448. case BOOTSTRAP_STATUS_STARTING:
  5449. *tag = "starting";
  5450. *summary = "Starting";
  5451. break;
  5452. case BOOTSTRAP_STATUS_CONN_DIR:
  5453. *tag = "conn_dir";
  5454. *summary = "Connecting to directory server";
  5455. break;
  5456. case BOOTSTRAP_STATUS_HANDSHAKE:
  5457. *tag = "status_handshake";
  5458. *summary = "Finishing handshake";
  5459. break;
  5460. case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
  5461. *tag = "handshake_dir";
  5462. *summary = "Finishing handshake with directory server";
  5463. break;
  5464. case BOOTSTRAP_STATUS_ONEHOP_CREATE:
  5465. *tag = "onehop_create";
  5466. *summary = "Establishing an encrypted directory connection";
  5467. break;
  5468. case BOOTSTRAP_STATUS_REQUESTING_STATUS:
  5469. *tag = "requesting_status";
  5470. *summary = "Asking for networkstatus consensus";
  5471. break;
  5472. case BOOTSTRAP_STATUS_LOADING_STATUS:
  5473. *tag = "loading_status";
  5474. *summary = "Loading networkstatus consensus";
  5475. break;
  5476. case BOOTSTRAP_STATUS_LOADING_KEYS:
  5477. *tag = "loading_keys";
  5478. *summary = "Loading authority key certs";
  5479. break;
  5480. case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
  5481. *tag = "requesting_descriptors";
  5482. /* XXXX this appears to incorrectly report internal on most loads */
  5483. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  5484. "Asking for relay descriptors for internal paths" :
  5485. "Asking for relay descriptors";
  5486. break;
  5487. /* If we're sure there are no exits in the consensus,
  5488. * inform the controller by adding "internal"
  5489. * to the status summaries.
  5490. * (We only check this while loading descriptors,
  5491. * so we may not know in the earlier stages.)
  5492. * But if there are exits, we can't be sure whether
  5493. * we're creating internal or exit paths/circuits.
  5494. * XXXX Or should be use different tags or statuses
  5495. * for internal and exit/all? */
  5496. case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
  5497. *tag = "loading_descriptors";
  5498. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  5499. "Loading relay descriptors for internal paths" :
  5500. "Loading relay descriptors";
  5501. break;
  5502. case BOOTSTRAP_STATUS_CONN_OR:
  5503. *tag = "conn_or";
  5504. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  5505. "Connecting to the Tor network internally" :
  5506. "Connecting to the Tor network";
  5507. break;
  5508. case BOOTSTRAP_STATUS_HANDSHAKE_OR:
  5509. *tag = "handshake_or";
  5510. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  5511. "Finishing handshake with first hop of internal circuit" :
  5512. "Finishing handshake with first hop";
  5513. break;
  5514. case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
  5515. *tag = "circuit_create";
  5516. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  5517. "Establishing an internal Tor circuit" :
  5518. "Establishing a Tor circuit";
  5519. break;
  5520. case BOOTSTRAP_STATUS_DONE:
  5521. *tag = "done";
  5522. *summary = "Done";
  5523. break;
  5524. default:
  5525. // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
  5526. *tag = *summary = "unknown";
  5527. return -1;
  5528. }
  5529. return 0;
  5530. }
  5531. /** What percentage through the bootstrap process are we? We remember
  5532. * this so we can avoid sending redundant bootstrap status events, and
  5533. * so we can guess context for the bootstrap messages which are
  5534. * ambiguous. It starts at 'undef', but gets set to 'starting' while
  5535. * Tor initializes. */
  5536. static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
  5537. /** As bootstrap_percent, but holds the bootstrapping level at which we last
  5538. * logged a NOTICE-level message. We use this, plus BOOTSTRAP_PCT_INCREMENT,
  5539. * to avoid flooding the log with a new message every time we get a few more
  5540. * microdescriptors */
  5541. static int notice_bootstrap_percent = 0;
  5542. /** How many problems have we had getting to the next bootstrapping phase?
  5543. * These include failure to establish a connection to a Tor relay,
  5544. * failures to finish the TLS handshake, failures to validate the
  5545. * consensus document, etc. */
  5546. static int bootstrap_problems = 0;
  5547. /** We only tell the controller once we've hit a threshold of problems
  5548. * for the current phase. */
  5549. #define BOOTSTRAP_PROBLEM_THRESHOLD 10
  5550. /** When our bootstrapping progress level changes, but our bootstrapping
  5551. * status has not advanced, we only log at NOTICE when we have made at least
  5552. * this much progress.
  5553. */
  5554. #define BOOTSTRAP_PCT_INCREMENT 5
  5555. /** Called when Tor has made progress at bootstrapping its directory
  5556. * information and initial circuits.
  5557. *
  5558. * <b>status</b> is the new status, that is, what task we will be doing
  5559. * next. <b>progress</b> is zero if we just started this task, else it
  5560. * represents progress on the task.
  5561. *
  5562. * Return true if we logged a message at level NOTICE, and false otherwise.
  5563. */
  5564. int
  5565. control_event_bootstrap(bootstrap_status_t status, int progress)
  5566. {
  5567. const char *tag, *summary;
  5568. char buf[BOOTSTRAP_MSG_LEN];
  5569. if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
  5570. return 0; /* already bootstrapped; nothing to be done here. */
  5571. /* special case for handshaking status, since our TLS handshaking code
  5572. * can't distinguish what the connection is going to be for. */
  5573. if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
  5574. if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
  5575. status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
  5576. } else {
  5577. status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
  5578. }
  5579. }
  5580. if (status > bootstrap_percent ||
  5581. (progress && progress > bootstrap_percent)) {
  5582. int loglevel = LOG_NOTICE;
  5583. bootstrap_status_to_string(status, &tag, &summary);
  5584. if (status <= bootstrap_percent &&
  5585. (progress < notice_bootstrap_percent + BOOTSTRAP_PCT_INCREMENT)) {
  5586. /* We log the message at info if the status hasn't advanced, and if less
  5587. * than BOOTSTRAP_PCT_INCREMENT progress has been made.
  5588. */
  5589. loglevel = LOG_INFO;
  5590. }
  5591. tor_log(loglevel, LD_CONTROL,
  5592. "Bootstrapped %d%%: %s", progress ? progress : status, summary);
  5593. tor_snprintf(buf, sizeof(buf),
  5594. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
  5595. progress ? progress : status, tag, summary);
  5596. tor_snprintf(last_sent_bootstrap_message,
  5597. sizeof(last_sent_bootstrap_message),
  5598. "NOTICE %s", buf);
  5599. control_event_client_status(LOG_NOTICE, "%s", buf);
  5600. if (status > bootstrap_percent) {
  5601. bootstrap_percent = status; /* new milestone reached */
  5602. }
  5603. if (progress > bootstrap_percent) {
  5604. /* incremental progress within a milestone */
  5605. bootstrap_percent = progress;
  5606. bootstrap_problems = 0; /* Progress! Reset our problem counter. */
  5607. }
  5608. if (loglevel == LOG_NOTICE &&
  5609. bootstrap_percent > notice_bootstrap_percent) {
  5610. /* Remember that we gave a notice at this level. */
  5611. notice_bootstrap_percent = bootstrap_percent;
  5612. }
  5613. return loglevel == LOG_NOTICE;
  5614. }
  5615. return 0;
  5616. }
  5617. /** Called when Tor has failed to make bootstrapping progress in a way
  5618. * that indicates a problem. <b>warn</b> gives a hint as to why, and
  5619. * <b>reason</b> provides an "or_conn_end_reason" tag. <b>or_conn</b>
  5620. * is the connection that caused this problem.
  5621. */
  5622. MOCK_IMPL(void,
  5623. control_event_bootstrap_problem, (const char *warn, int reason,
  5624. or_connection_t *or_conn))
  5625. {
  5626. int status = bootstrap_percent;
  5627. const char *tag = "", *summary = "";
  5628. char buf[BOOTSTRAP_MSG_LEN];
  5629. const char *recommendation = "ignore";
  5630. int severity;
  5631. /* bootstrap_percent must not be in "undefined" state here. */
  5632. tor_assert(status >= 0);
  5633. if (or_conn->have_noted_bootstrap_problem)
  5634. return;
  5635. or_conn->have_noted_bootstrap_problem = 1;
  5636. if (bootstrap_percent == 100)
  5637. return; /* already bootstrapped; nothing to be done here. */
  5638. bootstrap_problems++;
  5639. if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
  5640. recommendation = "warn";
  5641. if (reason == END_OR_CONN_REASON_NO_ROUTE)
  5642. recommendation = "warn";
  5643. /* If we are using bridges and all our OR connections are now
  5644. closed, it means that we totally failed to connect to our
  5645. bridges. Throw a warning. */
  5646. if (get_options()->UseBridges && !any_other_active_or_conns(or_conn))
  5647. recommendation = "warn";
  5648. if (we_are_hibernating())
  5649. recommendation = "ignore";
  5650. while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
  5651. status--; /* find a recognized status string based on current progress */
  5652. status = bootstrap_percent; /* set status back to the actual number */
  5653. severity = !strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO;
  5654. log_fn(severity,
  5655. LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
  5656. "count %d; recommendation %s; host %s at %s:%d)",
  5657. status, summary, warn,
  5658. orconn_end_reason_to_control_string(reason),
  5659. bootstrap_problems, recommendation,
  5660. hex_str(or_conn->identity_digest, DIGEST_LEN),
  5661. or_conn->base_.address,
  5662. or_conn->base_.port);
  5663. connection_or_report_broken_states(severity, LD_HANDSHAKE);
  5664. tor_snprintf(buf, sizeof(buf),
  5665. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
  5666. "COUNT=%d RECOMMENDATION=%s HOSTID=\"%s\" HOSTADDR=\"%s:%d\"",
  5667. bootstrap_percent, tag, summary, warn,
  5668. orconn_end_reason_to_control_string(reason), bootstrap_problems,
  5669. recommendation,
  5670. hex_str(or_conn->identity_digest, DIGEST_LEN),
  5671. or_conn->base_.address,
  5672. (int)or_conn->base_.port);
  5673. tor_snprintf(last_sent_bootstrap_message,
  5674. sizeof(last_sent_bootstrap_message),
  5675. "WARN %s", buf);
  5676. control_event_client_status(LOG_WARN, "%s", buf);
  5677. }
  5678. /** We just generated a new summary of which countries we've seen clients
  5679. * from recently. Send a copy to the controller in case it wants to
  5680. * display it for the user. */
  5681. void
  5682. control_event_clients_seen(const char *controller_str)
  5683. {
  5684. send_control_event(EVENT_CLIENTS_SEEN,
  5685. "650 CLIENTS_SEEN %s\r\n", controller_str);
  5686. }
  5687. /** A new pluggable transport called <b>transport_name</b> was
  5688. * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
  5689. * "server" or "client" depending on the mode of the pluggable
  5690. * transport.
  5691. * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
  5692. */
  5693. void
  5694. control_event_transport_launched(const char *mode, const char *transport_name,
  5695. tor_addr_t *addr, uint16_t port)
  5696. {
  5697. send_control_event(EVENT_TRANSPORT_LAUNCHED,
  5698. "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
  5699. mode, transport_name, fmt_addr(addr), port);
  5700. }
  5701. /** Convert rendezvous auth type to string for HS_DESC control events
  5702. */
  5703. const char *
  5704. rend_auth_type_to_string(rend_auth_type_t auth_type)
  5705. {
  5706. const char *str;
  5707. switch (auth_type) {
  5708. case REND_NO_AUTH:
  5709. str = "NO_AUTH";
  5710. break;
  5711. case REND_BASIC_AUTH:
  5712. str = "BASIC_AUTH";
  5713. break;
  5714. case REND_STEALTH_AUTH:
  5715. str = "STEALTH_AUTH";
  5716. break;
  5717. default:
  5718. str = "UNKNOWN";
  5719. }
  5720. return str;
  5721. }
  5722. /** Return a longname the node whose identity is <b>id_digest</b>. If
  5723. * node_get_by_id() returns NULL, base 16 encoding of <b>id_digest</b> is
  5724. * returned instead.
  5725. *
  5726. * This function is not thread-safe. Each call to this function invalidates
  5727. * previous values returned by this function.
  5728. */
  5729. MOCK_IMPL(const char *,
  5730. node_describe_longname_by_id,(const char *id_digest))
  5731. {
  5732. static char longname[MAX_VERBOSE_NICKNAME_LEN+1];
  5733. node_get_verbose_nickname_by_id(id_digest, longname);
  5734. return longname;
  5735. }
  5736. /** Return either the onion address if the given pointer is a non empty
  5737. * string else the unknown string. */
  5738. static const char *
  5739. rend_hsaddress_str_or_unknown(const char *onion_address)
  5740. {
  5741. static const char *str_unknown = "UNKNOWN";
  5742. const char *str_ret = str_unknown;
  5743. /* No valid pointer, unknown it is. */
  5744. if (!onion_address) {
  5745. goto end;
  5746. }
  5747. /* Empty onion address thus we don't know, unknown it is. */
  5748. if (onion_address[0] == '\0') {
  5749. goto end;
  5750. }
  5751. /* All checks are good so return the given onion address. */
  5752. str_ret = onion_address;
  5753. end:
  5754. return str_ret;
  5755. }
  5756. /** send HS_DESC requested event.
  5757. *
  5758. * <b>rend_query</b> is used to fetch requested onion address and auth type.
  5759. * <b>hs_dir</b> is the description of contacting hs directory.
  5760. * <b>desc_id_base32</b> is the ID of requested hs descriptor.
  5761. */
  5762. void
  5763. control_event_hs_descriptor_requested(const rend_data_t *rend_query,
  5764. const char *id_digest,
  5765. const char *desc_id_base32)
  5766. {
  5767. if (!id_digest || !rend_query || !desc_id_base32) {
  5768. log_warn(LD_BUG, "Called with rend_query==%p, "
  5769. "id_digest==%p, desc_id_base32==%p",
  5770. rend_query, id_digest, desc_id_base32);
  5771. return;
  5772. }
  5773. send_control_event(EVENT_HS_DESC,
  5774. "650 HS_DESC REQUESTED %s %s %s %s\r\n",
  5775. rend_hsaddress_str_or_unknown(rend_query->onion_address),
  5776. rend_auth_type_to_string(rend_query->auth_type),
  5777. node_describe_longname_by_id(id_digest),
  5778. desc_id_base32);
  5779. }
  5780. /** For an HS descriptor query <b>rend_data</b>, using the
  5781. * <b>onion_address</b> and HSDir fingerprint <b>hsdir_fp</b>, find out
  5782. * which descriptor ID in the query is the right one.
  5783. *
  5784. * Return a pointer of the binary descriptor ID found in the query's object
  5785. * or NULL if not found. */
  5786. static const char *
  5787. get_desc_id_from_query(const rend_data_t *rend_data, const char *hsdir_fp)
  5788. {
  5789. int replica;
  5790. const char *desc_id = NULL;
  5791. /* Possible if the fetch was done using a descriptor ID. This means that
  5792. * the HSFETCH command was used. */
  5793. if (!tor_digest_is_zero(rend_data->desc_id_fetch)) {
  5794. desc_id = rend_data->desc_id_fetch;
  5795. goto end;
  5796. }
  5797. /* OK, we have an onion address so now let's find which descriptor ID
  5798. * is the one associated with the HSDir fingerprint. */
  5799. for (replica = 0; replica < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
  5800. replica++) {
  5801. const char *digest = rend_data->descriptor_id[replica];
  5802. SMARTLIST_FOREACH_BEGIN(rend_data->hsdirs_fp, char *, fingerprint) {
  5803. if (tor_memcmp(fingerprint, hsdir_fp, DIGEST_LEN) == 0) {
  5804. /* Found it! This descriptor ID is the right one. */
  5805. desc_id = digest;
  5806. goto end;
  5807. }
  5808. } SMARTLIST_FOREACH_END(fingerprint);
  5809. }
  5810. end:
  5811. return desc_id;
  5812. }
  5813. /** send HS_DESC CREATED event when a local service generates a descriptor.
  5814. *
  5815. * <b>service_id</b> is the descriptor onion address.
  5816. * <b>desc_id_base32</b> is the descriptor ID.
  5817. * <b>replica</b> is the the descriptor replica number.
  5818. */
  5819. void
  5820. control_event_hs_descriptor_created(const char *service_id,
  5821. const char *desc_id_base32,
  5822. int replica)
  5823. {
  5824. if (!service_id || !desc_id_base32) {
  5825. log_warn(LD_BUG, "Called with service_digest==%p, "
  5826. "desc_id_base32==%p", service_id, desc_id_base32);
  5827. return;
  5828. }
  5829. send_control_event(EVENT_HS_DESC,
  5830. "650 HS_DESC CREATED %s UNKNOWN UNKNOWN %s "
  5831. "REPLICA=%d\r\n",
  5832. service_id,
  5833. desc_id_base32,
  5834. replica);
  5835. }
  5836. /** send HS_DESC upload event.
  5837. *
  5838. * <b>service_id</b> is the descriptor onion address.
  5839. * <b>hs_dir</b> is the description of contacting hs directory.
  5840. * <b>desc_id_base32</b> is the ID of requested hs descriptor.
  5841. */
  5842. void
  5843. control_event_hs_descriptor_upload(const char *service_id,
  5844. const char *id_digest,
  5845. const char *desc_id_base32)
  5846. {
  5847. if (!service_id || !id_digest || !desc_id_base32) {
  5848. log_warn(LD_BUG, "Called with service_digest==%p, "
  5849. "desc_id_base32==%p, id_digest==%p", service_id,
  5850. desc_id_base32, id_digest);
  5851. return;
  5852. }
  5853. send_control_event(EVENT_HS_DESC,
  5854. "650 HS_DESC UPLOAD %s UNKNOWN %s %s\r\n",
  5855. service_id,
  5856. node_describe_longname_by_id(id_digest),
  5857. desc_id_base32);
  5858. }
  5859. /** send HS_DESC event after got response from hs directory.
  5860. *
  5861. * NOTE: this is an internal function used by following functions:
  5862. * control_event_hs_descriptor_received
  5863. * control_event_hs_descriptor_failed
  5864. *
  5865. * So do not call this function directly.
  5866. */
  5867. void
  5868. control_event_hs_descriptor_receive_end(const char *action,
  5869. const char *onion_address,
  5870. const rend_data_t *rend_data,
  5871. const char *id_digest,
  5872. const char *reason)
  5873. {
  5874. char *desc_id_field = NULL;
  5875. char *reason_field = NULL;
  5876. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  5877. const char *desc_id = NULL;
  5878. if (!action || !id_digest || !rend_data || !onion_address) {
  5879. log_warn(LD_BUG, "Called with action==%p, id_digest==%p, "
  5880. "rend_data==%p, onion_address==%p", action, id_digest,
  5881. rend_data, onion_address);
  5882. return;
  5883. }
  5884. desc_id = get_desc_id_from_query(rend_data, id_digest);
  5885. if (desc_id != NULL) {
  5886. /* Set the descriptor ID digest to base32 so we can send it. */
  5887. base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_id,
  5888. DIGEST_LEN);
  5889. /* Extra whitespace is needed before the value. */
  5890. tor_asprintf(&desc_id_field, " %s", desc_id_base32);
  5891. }
  5892. if (reason) {
  5893. tor_asprintf(&reason_field, " REASON=%s", reason);
  5894. }
  5895. send_control_event(EVENT_HS_DESC,
  5896. "650 HS_DESC %s %s %s %s%s%s\r\n",
  5897. action,
  5898. rend_hsaddress_str_or_unknown(onion_address),
  5899. rend_auth_type_to_string(rend_data->auth_type),
  5900. node_describe_longname_by_id(id_digest),
  5901. desc_id_field ? desc_id_field : "",
  5902. reason_field ? reason_field : "");
  5903. tor_free(desc_id_field);
  5904. tor_free(reason_field);
  5905. }
  5906. /** send HS_DESC event after got response from hs directory.
  5907. *
  5908. * NOTE: this is an internal function used by following functions:
  5909. * control_event_hs_descriptor_uploaded
  5910. * control_event_hs_descriptor_upload_failed
  5911. *
  5912. * So do not call this function directly.
  5913. */
  5914. void
  5915. control_event_hs_descriptor_upload_end(const char *action,
  5916. const char *onion_address,
  5917. const char *id_digest,
  5918. const char *reason)
  5919. {
  5920. char *reason_field = NULL;
  5921. if (!action || !id_digest) {
  5922. log_warn(LD_BUG, "Called with action==%p, id_digest==%p", action,
  5923. id_digest);
  5924. return;
  5925. }
  5926. if (reason) {
  5927. tor_asprintf(&reason_field, " REASON=%s", reason);
  5928. }
  5929. send_control_event(EVENT_HS_DESC,
  5930. "650 HS_DESC %s %s UNKNOWN %s%s\r\n",
  5931. action,
  5932. rend_hsaddress_str_or_unknown(onion_address),
  5933. node_describe_longname_by_id(id_digest),
  5934. reason_field ? reason_field : "");
  5935. tor_free(reason_field);
  5936. }
  5937. /** send HS_DESC RECEIVED event
  5938. *
  5939. * called when we successfully received a hidden service descriptor.
  5940. */
  5941. void
  5942. control_event_hs_descriptor_received(const char *onion_address,
  5943. const rend_data_t *rend_data,
  5944. const char *id_digest)
  5945. {
  5946. if (!rend_data || !id_digest || !onion_address) {
  5947. log_warn(LD_BUG, "Called with rend_data==%p, id_digest==%p, "
  5948. "onion_address==%p", rend_data, id_digest, onion_address);
  5949. return;
  5950. }
  5951. control_event_hs_descriptor_receive_end("RECEIVED", onion_address,
  5952. rend_data, id_digest, NULL);
  5953. }
  5954. /** send HS_DESC UPLOADED event
  5955. *
  5956. * called when we successfully uploaded a hidden service descriptor.
  5957. */
  5958. void
  5959. control_event_hs_descriptor_uploaded(const char *id_digest,
  5960. const char *onion_address)
  5961. {
  5962. if (!id_digest) {
  5963. log_warn(LD_BUG, "Called with id_digest==%p",
  5964. id_digest);
  5965. return;
  5966. }
  5967. control_event_hs_descriptor_upload_end("UPLOADED", onion_address,
  5968. id_digest, NULL);
  5969. }
  5970. /** Send HS_DESC event to inform controller that query <b>rend_query</b>
  5971. * failed to retrieve hidden service descriptor identified by
  5972. * <b>id_digest</b>. If <b>reason</b> is not NULL, add it to REASON=
  5973. * field.
  5974. */
  5975. void
  5976. control_event_hs_descriptor_failed(const rend_data_t *rend_data,
  5977. const char *id_digest,
  5978. const char *reason)
  5979. {
  5980. if (!rend_data || !id_digest) {
  5981. log_warn(LD_BUG, "Called with rend_data==%p, id_digest==%p",
  5982. rend_data, id_digest);
  5983. return;
  5984. }
  5985. control_event_hs_descriptor_receive_end("FAILED",
  5986. rend_data->onion_address,
  5987. rend_data, id_digest, reason);
  5988. }
  5989. /** send HS_DESC_CONTENT event after completion of a successful fetch from
  5990. * hs directory. */
  5991. void
  5992. control_event_hs_descriptor_content(const char *onion_address,
  5993. const char *desc_id,
  5994. const char *hsdir_id_digest,
  5995. const char *content)
  5996. {
  5997. static const char *event_name = "HS_DESC_CONTENT";
  5998. char *esc_content = NULL;
  5999. if (!onion_address || !desc_id || !hsdir_id_digest) {
  6000. log_warn(LD_BUG, "Called with onion_address==%p, desc_id==%p, "
  6001. "hsdir_id_digest==%p", onion_address, desc_id, hsdir_id_digest);
  6002. return;
  6003. }
  6004. if (content == NULL) {
  6005. /* Point it to empty content so it can still be escaped. */
  6006. content = "";
  6007. }
  6008. write_escaped_data(content, strlen(content), &esc_content);
  6009. send_control_event(EVENT_HS_DESC_CONTENT,
  6010. "650+%s %s %s %s\r\n%s650 OK\r\n",
  6011. event_name,
  6012. rend_hsaddress_str_or_unknown(onion_address),
  6013. desc_id,
  6014. node_describe_longname_by_id(hsdir_id_digest),
  6015. esc_content);
  6016. tor_free(esc_content);
  6017. }
  6018. /** Send HS_DESC event to inform controller upload of hidden service
  6019. * descriptor identified by <b>id_digest</b> failed. If <b>reason</b>
  6020. * is not NULL, add it to REASON= field.
  6021. */
  6022. void
  6023. control_event_hs_descriptor_upload_failed(const char *id_digest,
  6024. const char *onion_address,
  6025. const char *reason)
  6026. {
  6027. if (!id_digest) {
  6028. log_warn(LD_BUG, "Called with id_digest==%p",
  6029. id_digest);
  6030. return;
  6031. }
  6032. control_event_hs_descriptor_upload_end("UPLOAD_FAILED", onion_address,
  6033. id_digest, reason);
  6034. }
  6035. /** Free any leftover allocated memory of the control.c subsystem. */
  6036. void
  6037. control_free_all(void)
  6038. {
  6039. if (authentication_cookie) /* Free the auth cookie */
  6040. tor_free(authentication_cookie);
  6041. if (detached_onion_services) { /* Free the detached onion services */
  6042. SMARTLIST_FOREACH(detached_onion_services, char *, cp, tor_free(cp));
  6043. smartlist_free(detached_onion_services);
  6044. }
  6045. if (queued_control_events) {
  6046. SMARTLIST_FOREACH(queued_control_events, queued_event_t *, ev,
  6047. queued_event_free(ev));
  6048. smartlist_free(queued_control_events);
  6049. queued_control_events = NULL;
  6050. }
  6051. if (flush_queued_events_event) {
  6052. tor_event_free(flush_queued_events_event);
  6053. flush_queued_events_event = NULL;
  6054. }
  6055. }
  6056. #ifdef TOR_UNIT_TESTS
  6057. /* For testing: change the value of global_event_mask */
  6058. void
  6059. control_testing_set_global_event_mask(uint64_t mask)
  6060. {
  6061. global_event_mask = mask;
  6062. }
  6063. #endif