control.c 261 KB

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