control.c 264 KB

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