control.c 240 KB

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