control.c 244 KB

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