control.c 255 KB

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