control.c 259 KB

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