control.c 255 KB

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