control.c 260 KB

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