control.c 221 KB

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