control.c 264 KB

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