control.c 259 KB

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