control.c 259 KB

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