control.c 264 KB

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