control.c 237 KB

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