control.c 217 KB

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