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