control.c 255 KB

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