control.c 197 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2015, 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. * See doc/spec/control-spec.txt for full details on protocol.
  8. **/
  9. #define CONTROL_PRIVATE
  10. #include "or.h"
  11. #include "addressmap.h"
  12. #include "buffers.h"
  13. #include "channel.h"
  14. #include "channeltls.h"
  15. #include "circuitbuild.h"
  16. #include "circuitlist.h"
  17. #include "circuitstats.h"
  18. #include "circuituse.h"
  19. #include "command.h"
  20. #include "config.h"
  21. #include "confparse.h"
  22. #include "connection.h"
  23. #include "connection_edge.h"
  24. #include "connection_or.h"
  25. #include "control.h"
  26. #include "directory.h"
  27. #include "dirserv.h"
  28. #include "dnsserv.h"
  29. #include "entrynodes.h"
  30. #include "geoip.h"
  31. #include "hibernate.h"
  32. #include "main.h"
  33. #include "networkstatus.h"
  34. #include "nodelist.h"
  35. #include "policies.h"
  36. #include "rendcommon.h"
  37. #include "rendservice.h"
  38. #include "reasons.h"
  39. #include "rendclient.h"
  40. #include "rendcommon.h"
  41. #include "rephist.h"
  42. #include "router.h"
  43. #include "routerlist.h"
  44. #include "routerparse.h"
  45. #include "rendclient.h"
  46. #include "rendcommon.h"
  47. #ifndef _WIN32
  48. #include <pwd.h>
  49. #include <sys/resource.h>
  50. #endif
  51. #include "crypto_s2k.h"
  52. #include "procmon.h"
  53. /** Yield true iff <b>s</b> is the state of a control_connection_t that has
  54. * finished authentication and is accepting commands. */
  55. #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
  56. /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
  57. * connection is interested in events of type <b>e</b>. We use this
  58. * so that we can decide to skip generating event messages that nobody
  59. * has interest in without having to walk over the global connection
  60. * list to find out.
  61. **/
  62. typedef uint64_t event_mask_t;
  63. /** An event mask of all the events that any controller is interested in
  64. * receiving. */
  65. static event_mask_t global_event_mask = 0;
  66. /** True iff we have disabled log messages from being sent to the controller */
  67. static int disable_log_messages = 0;
  68. /** Macro: true if any control connection is interested in events of type
  69. * <b>e</b>. */
  70. #define EVENT_IS_INTERESTING(e) \
  71. (!! (global_event_mask & EVENT_MASK_(e)))
  72. /** If we're using cookie-type authentication, how long should our cookies be?
  73. */
  74. #define AUTHENTICATION_COOKIE_LEN 32
  75. /** If true, we've set authentication_cookie to a secret code and
  76. * stored it to disk. */
  77. static int authentication_cookie_is_set = 0;
  78. /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
  79. * and which we're using to authenticate controllers. (If the controller can
  80. * read it off disk, it has permission to connect.) */
  81. static uint8_t *authentication_cookie = NULL;
  82. #define SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT \
  83. "Tor safe cookie authentication server-to-controller hash"
  84. #define SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT \
  85. "Tor safe cookie authentication controller-to-server hash"
  86. #define SAFECOOKIE_SERVER_NONCE_LEN DIGEST256_LEN
  87. /** The list of onion services that have been added via ADD_ONION that do not
  88. * belong to any particular control connection.
  89. */
  90. static smartlist_t *detached_onion_services = NULL;
  91. /** A sufficiently large size to record the last bootstrap phase string. */
  92. #define BOOTSTRAP_MSG_LEN 1024
  93. /** What was the last bootstrap phase message we sent? We keep track
  94. * of this so we can respond to getinfo status/bootstrap-phase queries. */
  95. static char last_sent_bootstrap_message[BOOTSTRAP_MSG_LEN];
  96. static void connection_printf_to_buf(control_connection_t *conn,
  97. const char *format, ...)
  98. CHECK_PRINTF(2,3);
  99. static void send_control_event_impl(uint16_t event, event_format_t which,
  100. const char *format, va_list ap)
  101. CHECK_PRINTF(3,0);
  102. static int control_event_status(int type, int severity, const char *format,
  103. va_list args)
  104. CHECK_PRINTF(3,0);
  105. static void send_control_done(control_connection_t *conn);
  106. static void send_control_event(uint16_t event, event_format_t which,
  107. const char *format, ...)
  108. CHECK_PRINTF(3,4);
  109. static int handle_control_setconf(control_connection_t *conn, uint32_t len,
  110. char *body);
  111. static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
  112. char *body);
  113. static int handle_control_getconf(control_connection_t *conn, uint32_t len,
  114. const char *body);
  115. static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
  116. const char *body);
  117. static int handle_control_setevents(control_connection_t *conn, uint32_t len,
  118. const char *body);
  119. static int handle_control_authenticate(control_connection_t *conn,
  120. uint32_t len,
  121. const char *body);
  122. static int handle_control_signal(control_connection_t *conn, uint32_t len,
  123. const char *body);
  124. static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  125. const char *body);
  126. static char *list_getinfo_options(void);
  127. static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
  128. const char *body);
  129. static int handle_control_extendcircuit(control_connection_t *conn,
  130. uint32_t len,
  131. const char *body);
  132. static int handle_control_setcircuitpurpose(control_connection_t *conn,
  133. uint32_t len, const char *body);
  134. static int handle_control_attachstream(control_connection_t *conn,
  135. uint32_t len,
  136. const char *body);
  137. static int handle_control_postdescriptor(control_connection_t *conn,
  138. uint32_t len,
  139. const char *body);
  140. static int handle_control_redirectstream(control_connection_t *conn,
  141. uint32_t len,
  142. const char *body);
  143. static int handle_control_closestream(control_connection_t *conn, uint32_t len,
  144. const char *body);
  145. static int handle_control_closecircuit(control_connection_t *conn,
  146. uint32_t len,
  147. const char *body);
  148. static int handle_control_resolve(control_connection_t *conn, uint32_t len,
  149. const char *body);
  150. static int handle_control_usefeature(control_connection_t *conn,
  151. uint32_t len,
  152. const char *body);
  153. static int handle_control_hsfetch(control_connection_t *conn, uint32_t len,
  154. const char *body);
  155. static int handle_control_add_onion(control_connection_t *conn, uint32_t len,
  156. const char *body);
  157. static int handle_control_del_onion(control_connection_t *conn, uint32_t len,
  158. const char *body);
  159. static int write_stream_target_to_buf(entry_connection_t *conn, char *buf,
  160. size_t len);
  161. static void orconn_target_get_name(char *buf, size_t len,
  162. or_connection_t *conn);
  163. /** Given a control event code for a message event, return the corresponding
  164. * log severity. */
  165. static INLINE int
  166. event_to_log_severity(int event)
  167. {
  168. switch (event) {
  169. case EVENT_DEBUG_MSG: return LOG_DEBUG;
  170. case EVENT_INFO_MSG: return LOG_INFO;
  171. case EVENT_NOTICE_MSG: return LOG_NOTICE;
  172. case EVENT_WARN_MSG: return LOG_WARN;
  173. case EVENT_ERR_MSG: return LOG_ERR;
  174. default: return -1;
  175. }
  176. }
  177. /** Given a log severity, return the corresponding control event code. */
  178. static INLINE int
  179. log_severity_to_event(int severity)
  180. {
  181. switch (severity) {
  182. case LOG_DEBUG: return EVENT_DEBUG_MSG;
  183. case LOG_INFO: return EVENT_INFO_MSG;
  184. case LOG_NOTICE: return EVENT_NOTICE_MSG;
  185. case LOG_WARN: return EVENT_WARN_MSG;
  186. case LOG_ERR: return EVENT_ERR_MSG;
  187. default: return -1;
  188. }
  189. }
  190. /** Helper: clear bandwidth counters of all origin circuits. */
  191. static void
  192. clear_circ_bw_fields(void)
  193. {
  194. origin_circuit_t *ocirc;
  195. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  196. if (!CIRCUIT_IS_ORIGIN(circ))
  197. continue;
  198. ocirc = TO_ORIGIN_CIRCUIT(circ);
  199. ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
  200. }
  201. SMARTLIST_FOREACH_END(circ);
  202. }
  203. /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
  204. * connection's event_mask field. */
  205. void
  206. control_update_global_event_mask(void)
  207. {
  208. smartlist_t *conns = get_connection_array();
  209. event_mask_t old_mask, new_mask;
  210. old_mask = global_event_mask;
  211. global_event_mask = 0;
  212. SMARTLIST_FOREACH(conns, connection_t *, _conn,
  213. {
  214. if (_conn->type == CONN_TYPE_CONTROL &&
  215. STATE_IS_OPEN(_conn->state)) {
  216. control_connection_t *conn = TO_CONTROL_CONN(_conn);
  217. global_event_mask |= conn->event_mask;
  218. }
  219. });
  220. new_mask = global_event_mask;
  221. /* Handle the aftermath. Set up the log callback to tell us only what
  222. * we want to hear...*/
  223. control_adjust_event_log_severity();
  224. /* ...then, if we've started logging stream or circ bw, clear the
  225. * appropriate fields. */
  226. if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
  227. (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
  228. SMARTLIST_FOREACH(conns, connection_t *, conn,
  229. {
  230. if (conn->type == CONN_TYPE_AP) {
  231. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  232. edge_conn->n_written = edge_conn->n_read = 0;
  233. }
  234. });
  235. }
  236. if (! (old_mask & EVENT_CIRC_BANDWIDTH_USED) &&
  237. (new_mask & EVENT_CIRC_BANDWIDTH_USED)) {
  238. clear_circ_bw_fields();
  239. }
  240. }
  241. /** Adjust the log severities that result in control_event_logmsg being called
  242. * to match the severity of log messages that any controllers are interested
  243. * in. */
  244. void
  245. control_adjust_event_log_severity(void)
  246. {
  247. int i;
  248. int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
  249. for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
  250. if (EVENT_IS_INTERESTING(i)) {
  251. min_log_event = i;
  252. break;
  253. }
  254. }
  255. for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
  256. if (EVENT_IS_INTERESTING(i)) {
  257. max_log_event = i;
  258. break;
  259. }
  260. }
  261. if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
  262. if (min_log_event > EVENT_NOTICE_MSG)
  263. min_log_event = EVENT_NOTICE_MSG;
  264. if (max_log_event < EVENT_ERR_MSG)
  265. max_log_event = EVENT_ERR_MSG;
  266. }
  267. if (min_log_event <= max_log_event)
  268. change_callback_log_severity(event_to_log_severity(min_log_event),
  269. event_to_log_severity(max_log_event),
  270. control_event_logmsg);
  271. else
  272. change_callback_log_severity(LOG_ERR, LOG_ERR,
  273. control_event_logmsg);
  274. }
  275. /** Return true iff the event with code <b>c</b> is being sent to any current
  276. * control connection. This is useful if the amount of work needed to prepare
  277. * to call the appropriate control_event_...() function is high.
  278. */
  279. int
  280. control_event_is_interesting(int event)
  281. {
  282. return EVENT_IS_INTERESTING(event);
  283. }
  284. /** Append a NUL-terminated string <b>s</b> to the end of
  285. * <b>conn</b>-\>outbuf.
  286. */
  287. static INLINE void
  288. connection_write_str_to_buf(const char *s, control_connection_t *conn)
  289. {
  290. size_t len = strlen(s);
  291. connection_write_to_buf(s, len, TO_CONN(conn));
  292. }
  293. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  294. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
  295. * contents of <b>data</b> into *<b>out</b>, adding a period before any period
  296. * that appears at the start of a line, and adding a period-CRLF line at
  297. * the end. Replace all LF characters sequences with CRLF. Return the number
  298. * of bytes in *<b>out</b>.
  299. */
  300. STATIC size_t
  301. write_escaped_data(const char *data, size_t len, char **out)
  302. {
  303. size_t sz_out = len+8;
  304. char *outp;
  305. const char *start = data, *end;
  306. int i;
  307. int start_of_line;
  308. for (i=0; i<(int)len; ++i) {
  309. if (data[i]== '\n')
  310. sz_out += 2; /* Maybe add a CR; maybe add a dot. */
  311. }
  312. *out = outp = tor_malloc(sz_out+1);
  313. end = data+len;
  314. start_of_line = 1;
  315. while (data < end) {
  316. if (*data == '\n') {
  317. if (data > start && data[-1] != '\r')
  318. *outp++ = '\r';
  319. start_of_line = 1;
  320. } else if (*data == '.') {
  321. if (start_of_line) {
  322. start_of_line = 0;
  323. *outp++ = '.';
  324. }
  325. } else {
  326. start_of_line = 0;
  327. }
  328. *outp++ = *data++;
  329. }
  330. if (outp < *out+2 || fast_memcmp(outp-2, "\r\n", 2)) {
  331. *outp++ = '\r';
  332. *outp++ = '\n';
  333. }
  334. *outp++ = '.';
  335. *outp++ = '\r';
  336. *outp++ = '\n';
  337. *outp = '\0'; /* NUL-terminate just in case. */
  338. tor_assert((outp - *out) <= (int)sz_out);
  339. return outp - *out;
  340. }
  341. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  342. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  343. * the contents of <b>data</b> into *<b>out</b>, removing any period
  344. * that appears at the start of a line, and replacing all CRLF sequences
  345. * with LF. Return the number of
  346. * bytes in *<b>out</b>. */
  347. STATIC size_t
  348. read_escaped_data(const char *data, size_t len, char **out)
  349. {
  350. char *outp;
  351. const char *next;
  352. const char *end;
  353. *out = outp = tor_malloc(len+1);
  354. end = data+len;
  355. while (data < end) {
  356. /* we're at the start of a line. */
  357. if (*data == '.')
  358. ++data;
  359. next = memchr(data, '\n', end-data);
  360. if (next) {
  361. size_t n_to_copy = next-data;
  362. /* Don't copy a CR that precedes this LF. */
  363. if (n_to_copy && *(next-1) == '\r')
  364. --n_to_copy;
  365. memcpy(outp, data, n_to_copy);
  366. outp += n_to_copy;
  367. data = next+1; /* This will point at the start of the next line,
  368. * or the end of the string, or a period. */
  369. } else {
  370. memcpy(outp, data, end-data);
  371. outp += (end-data);
  372. *outp = '\0';
  373. return outp - *out;
  374. }
  375. *outp++ = '\n';
  376. }
  377. *outp = '\0';
  378. return outp - *out;
  379. }
  380. /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
  381. * double-quoted string with escaped characters, return the length of that
  382. * string (as encoded, including quotes). Otherwise return -1. */
  383. static INLINE int
  384. get_escaped_string_length(const char *start, size_t in_len_max,
  385. int *chars_out)
  386. {
  387. const char *cp, *end;
  388. int chars = 0;
  389. if (*start != '\"')
  390. return -1;
  391. cp = start+1;
  392. end = start+in_len_max;
  393. /* Calculate length. */
  394. while (1) {
  395. if (cp >= end) {
  396. return -1; /* Too long. */
  397. } else if (*cp == '\\') {
  398. if (++cp == end)
  399. return -1; /* Can't escape EOS. */
  400. ++cp;
  401. ++chars;
  402. } else if (*cp == '\"') {
  403. break;
  404. } else {
  405. ++cp;
  406. ++chars;
  407. }
  408. }
  409. if (chars_out)
  410. *chars_out = chars;
  411. return (int)(cp - start+1);
  412. }
  413. /** As decode_escaped_string, but does not decode the string: copies the
  414. * entire thing, including quotation marks. */
  415. static const char *
  416. extract_escaped_string(const char *start, size_t in_len_max,
  417. char **out, size_t *out_len)
  418. {
  419. int length = get_escaped_string_length(start, in_len_max, NULL);
  420. if (length<0)
  421. return NULL;
  422. *out_len = length;
  423. *out = tor_strndup(start, *out_len);
  424. return start+length;
  425. }
  426. /** Given a pointer to a string starting at <b>start</b> containing
  427. * <b>in_len_max</b> characters, decode a string beginning with one double
  428. * quote, containing any number of non-quote characters or characters escaped
  429. * with a backslash, and ending with a final double quote. Place the resulting
  430. * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
  431. * store its length in <b>out_len</b>. On success, return a pointer to the
  432. * character immediately following the escaped string. On failure, return
  433. * NULL. */
  434. static const char *
  435. decode_escaped_string(const char *start, size_t in_len_max,
  436. char **out, size_t *out_len)
  437. {
  438. const char *cp, *end;
  439. char *outp;
  440. int len, n_chars = 0;
  441. len = get_escaped_string_length(start, in_len_max, &n_chars);
  442. if (len<0)
  443. return NULL;
  444. end = start+len-1; /* Index of last quote. */
  445. tor_assert(*end == '\"');
  446. outp = *out = tor_malloc(len+1);
  447. *out_len = n_chars;
  448. cp = start+1;
  449. while (cp < end) {
  450. if (*cp == '\\')
  451. ++cp;
  452. *outp++ = *cp++;
  453. }
  454. *outp = '\0';
  455. tor_assert((outp - *out) == (int)*out_len);
  456. return end+1;
  457. }
  458. /** Acts like sprintf, but writes its formatted string to the end of
  459. * <b>conn</b>-\>outbuf. */
  460. static void
  461. connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
  462. {
  463. va_list ap;
  464. char *buf = NULL;
  465. int len;
  466. va_start(ap,format);
  467. len = tor_vasprintf(&buf, format, ap);
  468. va_end(ap);
  469. if (len < 0) {
  470. log_err(LD_BUG, "Unable to format string for controller.");
  471. tor_assert(0);
  472. }
  473. connection_write_to_buf(buf, (size_t)len, TO_CONN(conn));
  474. tor_free(buf);
  475. }
  476. /** Write all of the open control ports to ControlPortWriteToFile */
  477. void
  478. control_ports_write_to_file(void)
  479. {
  480. smartlist_t *lines;
  481. char *joined = NULL;
  482. const or_options_t *options = get_options();
  483. if (!options->ControlPortWriteToFile)
  484. return;
  485. lines = smartlist_new();
  486. SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t *, conn) {
  487. if (conn->type != CONN_TYPE_CONTROL_LISTENER || conn->marked_for_close)
  488. continue;
  489. #ifdef AF_UNIX
  490. if (conn->socket_family == AF_UNIX) {
  491. smartlist_add_asprintf(lines, "UNIX_PORT=%s\n", conn->address);
  492. continue;
  493. }
  494. #endif
  495. smartlist_add_asprintf(lines, "PORT=%s:%d\n", conn->address, conn->port);
  496. } SMARTLIST_FOREACH_END(conn);
  497. joined = smartlist_join_strings(lines, "", 0, NULL);
  498. if (write_str_to_file(options->ControlPortWriteToFile, joined, 0) < 0) {
  499. log_warn(LD_CONTROL, "Writing %s failed: %s",
  500. options->ControlPortWriteToFile, strerror(errno));
  501. }
  502. #ifndef _WIN32
  503. if (options->ControlPortFileGroupReadable) {
  504. if (chmod(options->ControlPortWriteToFile, 0640)) {
  505. log_warn(LD_FS,"Unable to make %s group-readable.",
  506. options->ControlPortWriteToFile);
  507. }
  508. }
  509. #endif
  510. tor_free(joined);
  511. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  512. smartlist_free(lines);
  513. }
  514. /** Send a "DONE" message down the control connection <b>conn</b>. */
  515. static void
  516. send_control_done(control_connection_t *conn)
  517. {
  518. connection_write_str_to_buf("250 OK\r\n", conn);
  519. }
  520. /** Send an event to all v1 controllers that are listening for code
  521. * <b>event</b>. The event's body is given by <b>msg</b>.
  522. *
  523. * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
  524. * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
  525. * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
  526. * to controllers that <em>have</em> enabled VERBOSE_NAMES.
  527. *
  528. * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
  529. * respect to the EXTENDED_EVENTS feature. */
  530. MOCK_IMPL(STATIC void,
  531. send_control_event_string,(uint16_t event, event_format_t which,
  532. const char *msg))
  533. {
  534. smartlist_t *conns = get_connection_array();
  535. (void)which;
  536. tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
  537. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  538. if (conn->type == CONN_TYPE_CONTROL &&
  539. !conn->marked_for_close &&
  540. conn->state == CONTROL_CONN_STATE_OPEN) {
  541. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  542. if (control_conn->event_mask & (((event_mask_t)1)<<event)) {
  543. int is_err = 0;
  544. connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
  545. if (event == EVENT_ERR_MSG)
  546. is_err = 1;
  547. else if (event == EVENT_STATUS_GENERAL)
  548. is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
  549. else if (event == EVENT_STATUS_CLIENT)
  550. is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
  551. else if (event == EVENT_STATUS_SERVER)
  552. is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
  553. if (is_err)
  554. connection_flush(TO_CONN(control_conn));
  555. }
  556. }
  557. } SMARTLIST_FOREACH_END(conn);
  558. }
  559. /** Helper for send_control_event and control_event_status:
  560. * Send an event to all v1 controllers that are listening for code
  561. * <b>event</b>. The event's body is created by the printf-style format in
  562. * <b>format</b>, and other arguments as provided. */
  563. static void
  564. send_control_event_impl(uint16_t event, event_format_t which,
  565. const char *format, va_list ap)
  566. {
  567. char *buf = NULL;
  568. int len;
  569. len = tor_vasprintf(&buf, format, ap);
  570. if (len < 0) {
  571. log_warn(LD_BUG, "Unable to format event for controller.");
  572. return;
  573. }
  574. send_control_event_string(event, which|ALL_FORMATS, buf);
  575. tor_free(buf);
  576. }
  577. /** Send an event to all v1 controllers that are listening for code
  578. * <b>event</b>. The event's body is created by the printf-style format in
  579. * <b>format</b>, and other arguments as provided. */
  580. static void
  581. send_control_event(uint16_t event, event_format_t which,
  582. const char *format, ...)
  583. {
  584. va_list ap;
  585. va_start(ap, format);
  586. send_control_event_impl(event, which, format, ap);
  587. va_end(ap);
  588. }
  589. /** Given a text circuit <b>id</b>, return the corresponding circuit. */
  590. static origin_circuit_t *
  591. get_circ(const char *id)
  592. {
  593. uint32_t n_id;
  594. int ok;
  595. n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
  596. if (!ok)
  597. return NULL;
  598. return circuit_get_by_global_id(n_id);
  599. }
  600. /** Given a text stream <b>id</b>, return the corresponding AP connection. */
  601. static entry_connection_t *
  602. get_stream(const char *id)
  603. {
  604. uint64_t n_id;
  605. int ok;
  606. connection_t *conn;
  607. n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
  608. if (!ok)
  609. return NULL;
  610. conn = connection_get_by_global_id(n_id);
  611. if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
  612. return NULL;
  613. return TO_ENTRY_CONN(conn);
  614. }
  615. /** Helper for setconf and resetconf. Acts like setconf, except
  616. * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
  617. * contents of body.
  618. */
  619. static int
  620. control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
  621. int use_defaults)
  622. {
  623. setopt_err_t opt_err;
  624. config_line_t *lines=NULL;
  625. char *start = body;
  626. char *errstring = NULL;
  627. const int clear_first = 1;
  628. char *config;
  629. smartlist_t *entries = smartlist_new();
  630. /* We have a string, "body", of the format '(key(=val|="val")?)' entries
  631. * separated by space. break it into a list of configuration entries. */
  632. while (*body) {
  633. char *eq = body;
  634. char *key;
  635. char *entry;
  636. while (!TOR_ISSPACE(*eq) && *eq != '=')
  637. ++eq;
  638. key = tor_strndup(body, eq-body);
  639. body = eq+1;
  640. if (*eq == '=') {
  641. char *val=NULL;
  642. size_t val_len=0;
  643. if (*body != '\"') {
  644. char *val_start = body;
  645. while (!TOR_ISSPACE(*body))
  646. body++;
  647. val = tor_strndup(val_start, body-val_start);
  648. val_len = strlen(val);
  649. } else {
  650. body = (char*)extract_escaped_string(body, (len - (body-start)),
  651. &val, &val_len);
  652. if (!body) {
  653. connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
  654. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  655. smartlist_free(entries);
  656. tor_free(key);
  657. return 0;
  658. }
  659. }
  660. tor_asprintf(&entry, "%s %s", key, val);
  661. tor_free(key);
  662. tor_free(val);
  663. } else {
  664. entry = key;
  665. }
  666. smartlist_add(entries, entry);
  667. while (TOR_ISSPACE(*body))
  668. ++body;
  669. }
  670. smartlist_add(entries, tor_strdup(""));
  671. config = smartlist_join_strings(entries, "\n", 0, NULL);
  672. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  673. smartlist_free(entries);
  674. if (config_get_lines(config, &lines, 0) < 0) {
  675. log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
  676. connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
  677. conn);
  678. tor_free(config);
  679. return 0;
  680. }
  681. tor_free(config);
  682. opt_err = options_trial_assign(lines, use_defaults, clear_first, &errstring);
  683. {
  684. const char *msg;
  685. switch (opt_err) {
  686. case SETOPT_ERR_MISC:
  687. msg = "552 Unrecognized option";
  688. break;
  689. case SETOPT_ERR_PARSE:
  690. msg = "513 Unacceptable option value";
  691. break;
  692. case SETOPT_ERR_TRANSITION:
  693. msg = "553 Transition not allowed";
  694. break;
  695. case SETOPT_ERR_SETTING:
  696. default:
  697. msg = "553 Unable to set option";
  698. break;
  699. case SETOPT_OK:
  700. config_free_lines(lines);
  701. send_control_done(conn);
  702. return 0;
  703. }
  704. log_warn(LD_CONTROL,
  705. "Controller gave us config lines that didn't validate: %s",
  706. errstring);
  707. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  708. config_free_lines(lines);
  709. tor_free(errstring);
  710. return 0;
  711. }
  712. }
  713. /** Called when we receive a SETCONF message: parse the body and try
  714. * to update our configuration. Reply with a DONE or ERROR message.
  715. * Modifies the contents of body.*/
  716. static int
  717. handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
  718. {
  719. return control_setconf_helper(conn, len, body, 0);
  720. }
  721. /** Called when we receive a RESETCONF message: parse the body and try
  722. * to update our configuration. Reply with a DONE or ERROR message.
  723. * Modifies the contents of body. */
  724. static int
  725. handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
  726. {
  727. return control_setconf_helper(conn, len, body, 1);
  728. }
  729. /** Called when we receive a GETCONF message. Parse the request, and
  730. * reply with a CONFVALUE or an ERROR message */
  731. static int
  732. handle_control_getconf(control_connection_t *conn, uint32_t body_len,
  733. const char *body)
  734. {
  735. smartlist_t *questions = smartlist_new();
  736. smartlist_t *answers = smartlist_new();
  737. smartlist_t *unrecognized = smartlist_new();
  738. char *msg = NULL;
  739. size_t msg_len;
  740. const or_options_t *options = get_options();
  741. int i, len;
  742. (void) body_len; /* body is NUL-terminated; so we can ignore len. */
  743. smartlist_split_string(questions, body, " ",
  744. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  745. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  746. if (!option_is_recognized(q)) {
  747. smartlist_add(unrecognized, (char*) q);
  748. } else {
  749. config_line_t *answer = option_get_assignment(options,q);
  750. if (!answer) {
  751. const char *name = option_get_canonical_name(q);
  752. smartlist_add_asprintf(answers, "250-%s\r\n", name);
  753. }
  754. while (answer) {
  755. config_line_t *next;
  756. smartlist_add_asprintf(answers, "250-%s=%s\r\n",
  757. answer->key, answer->value);
  758. next = answer->next;
  759. tor_free(answer->key);
  760. tor_free(answer->value);
  761. tor_free(answer);
  762. answer = next;
  763. }
  764. }
  765. } SMARTLIST_FOREACH_END(q);
  766. if ((len = smartlist_len(unrecognized))) {
  767. for (i=0; i < len-1; ++i)
  768. connection_printf_to_buf(conn,
  769. "552-Unrecognized configuration key \"%s\"\r\n",
  770. (char*)smartlist_get(unrecognized, i));
  771. connection_printf_to_buf(conn,
  772. "552 Unrecognized configuration key \"%s\"\r\n",
  773. (char*)smartlist_get(unrecognized, len-1));
  774. } else if ((len = smartlist_len(answers))) {
  775. char *tmp = smartlist_get(answers, len-1);
  776. tor_assert(strlen(tmp)>4);
  777. tmp[3] = ' ';
  778. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  779. connection_write_to_buf(msg, msg_len, TO_CONN(conn));
  780. } else {
  781. connection_write_str_to_buf("250 OK\r\n", conn);
  782. }
  783. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  784. smartlist_free(answers);
  785. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  786. smartlist_free(questions);
  787. smartlist_free(unrecognized);
  788. tor_free(msg);
  789. return 0;
  790. }
  791. /** Called when we get a +LOADCONF message. */
  792. static int
  793. handle_control_loadconf(control_connection_t *conn, uint32_t len,
  794. const char *body)
  795. {
  796. setopt_err_t retval;
  797. char *errstring = NULL;
  798. const char *msg = NULL;
  799. (void) len;
  800. retval = options_init_from_string(NULL, body, CMD_RUN_TOR, NULL, &errstring);
  801. if (retval != SETOPT_OK)
  802. log_warn(LD_CONTROL,
  803. "Controller gave us config file that didn't validate: %s",
  804. errstring);
  805. switch (retval) {
  806. case SETOPT_ERR_PARSE:
  807. msg = "552 Invalid config file";
  808. break;
  809. case SETOPT_ERR_TRANSITION:
  810. msg = "553 Transition not allowed";
  811. break;
  812. case SETOPT_ERR_SETTING:
  813. msg = "553 Unable to set option";
  814. break;
  815. case SETOPT_ERR_MISC:
  816. default:
  817. msg = "550 Unable to load config";
  818. break;
  819. case SETOPT_OK:
  820. break;
  821. }
  822. if (msg) {
  823. if (errstring)
  824. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  825. else
  826. connection_printf_to_buf(conn, "%s\r\n", msg);
  827. } else {
  828. send_control_done(conn);
  829. }
  830. tor_free(errstring);
  831. return 0;
  832. }
  833. /** Helper structure: maps event values to their names. */
  834. struct control_event_t {
  835. uint16_t event_code;
  836. const char *event_name;
  837. };
  838. /** Table mapping event values to their names. Used to implement SETEVENTS
  839. * and GETINFO events/names, and to keep they in sync. */
  840. static const struct control_event_t control_event_table[] = {
  841. { EVENT_CIRCUIT_STATUS, "CIRC" },
  842. { EVENT_CIRCUIT_STATUS_MINOR, "CIRC_MINOR" },
  843. { EVENT_STREAM_STATUS, "STREAM" },
  844. { EVENT_OR_CONN_STATUS, "ORCONN" },
  845. { EVENT_BANDWIDTH_USED, "BW" },
  846. { EVENT_DEBUG_MSG, "DEBUG" },
  847. { EVENT_INFO_MSG, "INFO" },
  848. { EVENT_NOTICE_MSG, "NOTICE" },
  849. { EVENT_WARN_MSG, "WARN" },
  850. { EVENT_ERR_MSG, "ERR" },
  851. { EVENT_NEW_DESC, "NEWDESC" },
  852. { EVENT_ADDRMAP, "ADDRMAP" },
  853. { EVENT_AUTHDIR_NEWDESCS, "AUTHDIR_NEWDESCS" },
  854. { EVENT_DESCCHANGED, "DESCCHANGED" },
  855. { EVENT_NS, "NS" },
  856. { EVENT_STATUS_GENERAL, "STATUS_GENERAL" },
  857. { EVENT_STATUS_CLIENT, "STATUS_CLIENT" },
  858. { EVENT_STATUS_SERVER, "STATUS_SERVER" },
  859. { EVENT_GUARD, "GUARD" },
  860. { EVENT_STREAM_BANDWIDTH_USED, "STREAM_BW" },
  861. { EVENT_CLIENTS_SEEN, "CLIENTS_SEEN" },
  862. { EVENT_NEWCONSENSUS, "NEWCONSENSUS" },
  863. { EVENT_BUILDTIMEOUT_SET, "BUILDTIMEOUT_SET" },
  864. { EVENT_SIGNAL, "SIGNAL" },
  865. { EVENT_CONF_CHANGED, "CONF_CHANGED"},
  866. { EVENT_CONN_BW, "CONN_BW" },
  867. { EVENT_CELL_STATS, "CELL_STATS" },
  868. { EVENT_TB_EMPTY, "TB_EMPTY" },
  869. { EVENT_CIRC_BANDWIDTH_USED, "CIRC_BW" },
  870. { EVENT_TRANSPORT_LAUNCHED, "TRANSPORT_LAUNCHED" },
  871. { EVENT_HS_DESC, "HS_DESC" },
  872. { EVENT_HS_DESC_CONTENT, "HS_DESC_CONTENT" },
  873. { 0, NULL },
  874. };
  875. /** Called when we get a SETEVENTS message: update conn->event_mask,
  876. * and reply with DONE or ERROR. */
  877. static int
  878. handle_control_setevents(control_connection_t *conn, uint32_t len,
  879. const char *body)
  880. {
  881. int event_code;
  882. event_mask_t event_mask = 0;
  883. smartlist_t *events = smartlist_new();
  884. (void) len;
  885. smartlist_split_string(events, body, " ",
  886. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  887. SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
  888. {
  889. if (!strcasecmp(ev, "EXTENDED")) {
  890. continue;
  891. } else {
  892. int i;
  893. event_code = -1;
  894. for (i = 0; control_event_table[i].event_name != NULL; ++i) {
  895. if (!strcasecmp(ev, control_event_table[i].event_name)) {
  896. event_code = control_event_table[i].event_code;
  897. break;
  898. }
  899. }
  900. if (event_code == -1) {
  901. connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
  902. ev);
  903. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  904. smartlist_free(events);
  905. return 0;
  906. }
  907. }
  908. event_mask |= (((event_mask_t)1) << event_code);
  909. }
  910. SMARTLIST_FOREACH_END(ev);
  911. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  912. smartlist_free(events);
  913. conn->event_mask = event_mask;
  914. control_update_global_event_mask();
  915. send_control_done(conn);
  916. return 0;
  917. }
  918. /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
  919. * Return a smartlist of acceptable passwords (unterminated strings of
  920. * length S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on
  921. * failure.
  922. */
  923. smartlist_t *
  924. decode_hashed_passwords(config_line_t *passwords)
  925. {
  926. char decoded[64];
  927. config_line_t *cl;
  928. smartlist_t *sl = smartlist_new();
  929. tor_assert(passwords);
  930. for (cl = passwords; cl; cl = cl->next) {
  931. const char *hashed = cl->value;
  932. if (!strcmpstart(hashed, "16:")) {
  933. if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
  934. || strlen(hashed+3) != (S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN)*2) {
  935. goto err;
  936. }
  937. } else {
  938. if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
  939. != S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN) {
  940. goto err;
  941. }
  942. }
  943. smartlist_add(sl,
  944. tor_memdup(decoded, S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN));
  945. }
  946. return sl;
  947. err:
  948. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  949. smartlist_free(sl);
  950. return NULL;
  951. }
  952. /** Called when we get an AUTHENTICATE message. Check whether the
  953. * authentication is valid, and if so, update the connection's state to
  954. * OPEN. Reply with DONE or ERROR.
  955. */
  956. static int
  957. handle_control_authenticate(control_connection_t *conn, uint32_t len,
  958. const char *body)
  959. {
  960. int used_quoted_string = 0;
  961. const or_options_t *options = get_options();
  962. const char *errstr = "Unknown error";
  963. char *password;
  964. size_t password_len;
  965. const char *cp;
  966. int i;
  967. int bad_cookie=0, bad_password=0;
  968. smartlist_t *sl = NULL;
  969. if (!len) {
  970. password = tor_strdup("");
  971. password_len = 0;
  972. } else if (TOR_ISXDIGIT(body[0])) {
  973. cp = body;
  974. while (TOR_ISXDIGIT(*cp))
  975. ++cp;
  976. i = (int)(cp - body);
  977. tor_assert(i>0);
  978. password_len = i/2;
  979. password = tor_malloc(password_len + 1);
  980. if (base16_decode(password, password_len+1, body, i)<0) {
  981. connection_write_str_to_buf(
  982. "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
  983. "password? If so, the standard requires that you put it in "
  984. "double quotes.\r\n", conn);
  985. connection_mark_for_close(TO_CONN(conn));
  986. tor_free(password);
  987. return 0;
  988. }
  989. } else {
  990. if (!decode_escaped_string(body, len, &password, &password_len)) {
  991. connection_write_str_to_buf("551 Invalid quoted string. You need "
  992. "to put the password in double quotes.\r\n", conn);
  993. connection_mark_for_close(TO_CONN(conn));
  994. return 0;
  995. }
  996. used_quoted_string = 1;
  997. }
  998. if (conn->safecookie_client_hash != NULL) {
  999. /* The controller has chosen safe cookie authentication; the only
  1000. * acceptable authentication value is the controller-to-server
  1001. * response. */
  1002. tor_assert(authentication_cookie_is_set);
  1003. if (password_len != DIGEST256_LEN) {
  1004. log_warn(LD_CONTROL,
  1005. "Got safe cookie authentication response with wrong length "
  1006. "(%d)", (int)password_len);
  1007. errstr = "Wrong length for safe cookie response.";
  1008. goto err;
  1009. }
  1010. if (tor_memneq(conn->safecookie_client_hash, password, DIGEST256_LEN)) {
  1011. log_warn(LD_CONTROL,
  1012. "Got incorrect safe cookie authentication response");
  1013. errstr = "Safe cookie response did not match expected value.";
  1014. goto err;
  1015. }
  1016. tor_free(conn->safecookie_client_hash);
  1017. goto ok;
  1018. }
  1019. if (!options->CookieAuthentication && !options->HashedControlPassword &&
  1020. !options->HashedControlSessionPassword) {
  1021. /* if Tor doesn't demand any stronger authentication, then
  1022. * the controller can get in with anything. */
  1023. goto ok;
  1024. }
  1025. if (options->CookieAuthentication) {
  1026. int also_password = options->HashedControlPassword != NULL ||
  1027. options->HashedControlSessionPassword != NULL;
  1028. if (password_len != AUTHENTICATION_COOKIE_LEN) {
  1029. if (!also_password) {
  1030. log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
  1031. "(%d)", (int)password_len);
  1032. errstr = "Wrong length on authentication cookie.";
  1033. goto err;
  1034. }
  1035. bad_cookie = 1;
  1036. } else if (tor_memneq(authentication_cookie, password, password_len)) {
  1037. if (!also_password) {
  1038. log_warn(LD_CONTROL, "Got mismatched authentication cookie");
  1039. errstr = "Authentication cookie did not match expected value.";
  1040. goto err;
  1041. }
  1042. bad_cookie = 1;
  1043. } else {
  1044. goto ok;
  1045. }
  1046. }
  1047. if (options->HashedControlPassword ||
  1048. options->HashedControlSessionPassword) {
  1049. int bad = 0;
  1050. smartlist_t *sl_tmp;
  1051. char received[DIGEST_LEN];
  1052. int also_cookie = options->CookieAuthentication;
  1053. sl = smartlist_new();
  1054. if (options->HashedControlPassword) {
  1055. sl_tmp = decode_hashed_passwords(options->HashedControlPassword);
  1056. if (!sl_tmp)
  1057. bad = 1;
  1058. else {
  1059. smartlist_add_all(sl, sl_tmp);
  1060. smartlist_free(sl_tmp);
  1061. }
  1062. }
  1063. if (options->HashedControlSessionPassword) {
  1064. sl_tmp = decode_hashed_passwords(options->HashedControlSessionPassword);
  1065. if (!sl_tmp)
  1066. bad = 1;
  1067. else {
  1068. smartlist_add_all(sl, sl_tmp);
  1069. smartlist_free(sl_tmp);
  1070. }
  1071. }
  1072. if (bad) {
  1073. if (!also_cookie) {
  1074. log_warn(LD_BUG,
  1075. "Couldn't decode HashedControlPassword: invalid base16");
  1076. errstr="Couldn't decode HashedControlPassword value in configuration.";
  1077. goto err;
  1078. }
  1079. bad_password = 1;
  1080. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1081. smartlist_free(sl);
  1082. sl = NULL;
  1083. } else {
  1084. SMARTLIST_FOREACH(sl, char *, expected,
  1085. {
  1086. secret_to_key_rfc2440(received,DIGEST_LEN,
  1087. password,password_len,expected);
  1088. if (tor_memeq(expected + S2K_RFC2440_SPECIFIER_LEN,
  1089. received, DIGEST_LEN))
  1090. goto ok;
  1091. });
  1092. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1093. smartlist_free(sl);
  1094. sl = NULL;
  1095. if (used_quoted_string)
  1096. errstr = "Password did not match HashedControlPassword value from "
  1097. "configuration";
  1098. else
  1099. errstr = "Password did not match HashedControlPassword value from "
  1100. "configuration. Maybe you tried a plain text password? "
  1101. "If so, the standard requires that you put it in double quotes.";
  1102. bad_password = 1;
  1103. if (!also_cookie)
  1104. goto err;
  1105. }
  1106. }
  1107. /** We only get here if both kinds of authentication failed. */
  1108. tor_assert(bad_password && bad_cookie);
  1109. log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
  1110. errstr = "Password did not match HashedControlPassword *or* authentication "
  1111. "cookie.";
  1112. err:
  1113. tor_free(password);
  1114. connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n", errstr);
  1115. connection_mark_for_close(TO_CONN(conn));
  1116. if (sl) { /* clean up */
  1117. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1118. smartlist_free(sl);
  1119. }
  1120. return 0;
  1121. ok:
  1122. log_info(LD_CONTROL, "Authenticated control connection ("TOR_SOCKET_T_FORMAT
  1123. ")", conn->base_.s);
  1124. send_control_done(conn);
  1125. conn->base_.state = CONTROL_CONN_STATE_OPEN;
  1126. tor_free(password);
  1127. if (sl) { /* clean up */
  1128. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1129. smartlist_free(sl);
  1130. }
  1131. return 0;
  1132. }
  1133. /** Called when we get a SAVECONF command. Try to flush the current options to
  1134. * disk, and report success or failure. */
  1135. static int
  1136. handle_control_saveconf(control_connection_t *conn, uint32_t len,
  1137. const char *body)
  1138. {
  1139. (void) len;
  1140. (void) body;
  1141. if (options_save_current()<0) {
  1142. connection_write_str_to_buf(
  1143. "551 Unable to write configuration to disk.\r\n", conn);
  1144. } else {
  1145. send_control_done(conn);
  1146. }
  1147. return 0;
  1148. }
  1149. struct signal_t {
  1150. int sig;
  1151. const char *signal_name;
  1152. };
  1153. static const struct signal_t signal_table[] = {
  1154. { SIGHUP, "RELOAD" },
  1155. { SIGHUP, "HUP" },
  1156. { SIGINT, "SHUTDOWN" },
  1157. { SIGUSR1, "DUMP" },
  1158. { SIGUSR1, "USR1" },
  1159. { SIGUSR2, "DEBUG" },
  1160. { SIGUSR2, "USR2" },
  1161. { SIGTERM, "HALT" },
  1162. { SIGTERM, "TERM" },
  1163. { SIGTERM, "INT" },
  1164. { SIGNEWNYM, "NEWNYM" },
  1165. { SIGCLEARDNSCACHE, "CLEARDNSCACHE"},
  1166. { SIGHEARTBEAT, "HEARTBEAT"},
  1167. { 0, NULL },
  1168. };
  1169. /** Called when we get a SIGNAL command. React to the provided signal, and
  1170. * report success or failure. (If the signal results in a shutdown, success
  1171. * may not be reported.) */
  1172. static int
  1173. handle_control_signal(control_connection_t *conn, uint32_t len,
  1174. const char *body)
  1175. {
  1176. int sig = -1;
  1177. int i;
  1178. int n = 0;
  1179. char *s;
  1180. (void) len;
  1181. while (body[n] && ! TOR_ISSPACE(body[n]))
  1182. ++n;
  1183. s = tor_strndup(body, n);
  1184. for (i = 0; signal_table[i].signal_name != NULL; ++i) {
  1185. if (!strcasecmp(s, signal_table[i].signal_name)) {
  1186. sig = signal_table[i].sig;
  1187. break;
  1188. }
  1189. }
  1190. if (sig < 0)
  1191. connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
  1192. s);
  1193. tor_free(s);
  1194. if (sig < 0)
  1195. return 0;
  1196. send_control_done(conn);
  1197. /* Flush the "done" first if the signal might make us shut down. */
  1198. if (sig == SIGTERM || sig == SIGINT)
  1199. connection_flush(TO_CONN(conn));
  1200. process_signal(sig);
  1201. return 0;
  1202. }
  1203. /** Called when we get a TAKEOWNERSHIP command. Mark this connection
  1204. * as an owning connection, so that we will exit if the connection
  1205. * closes. */
  1206. static int
  1207. handle_control_takeownership(control_connection_t *conn, uint32_t len,
  1208. const char *body)
  1209. {
  1210. (void)len;
  1211. (void)body;
  1212. conn->is_owning_control_connection = 1;
  1213. log_info(LD_CONTROL, "Control connection %d has taken ownership of this "
  1214. "Tor instance.",
  1215. (int)(conn->base_.s));
  1216. send_control_done(conn);
  1217. return 0;
  1218. }
  1219. /** Return true iff <b>addr</b> is unusable as a mapaddress target because of
  1220. * containing funny characters. */
  1221. static int
  1222. address_is_invalid_mapaddress_target(const char *addr)
  1223. {
  1224. if (!strcmpstart(addr, "*."))
  1225. return address_is_invalid_destination(addr+2, 1);
  1226. else
  1227. return address_is_invalid_destination(addr, 1);
  1228. }
  1229. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  1230. * and report success or failure. */
  1231. static int
  1232. handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  1233. const char *body)
  1234. {
  1235. smartlist_t *elts;
  1236. smartlist_t *lines;
  1237. smartlist_t *reply;
  1238. char *r;
  1239. size_t sz;
  1240. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  1241. lines = smartlist_new();
  1242. elts = smartlist_new();
  1243. reply = smartlist_new();
  1244. smartlist_split_string(lines, body, " ",
  1245. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1246. SMARTLIST_FOREACH_BEGIN(lines, char *, line) {
  1247. tor_strlower(line);
  1248. smartlist_split_string(elts, line, "=", 0, 2);
  1249. if (smartlist_len(elts) == 2) {
  1250. const char *from = smartlist_get(elts,0);
  1251. const char *to = smartlist_get(elts,1);
  1252. if (address_is_invalid_mapaddress_target(to)) {
  1253. smartlist_add_asprintf(reply,
  1254. "512-syntax error: invalid address '%s'", to);
  1255. log_warn(LD_CONTROL,
  1256. "Skipping invalid argument '%s' in MapAddress msg", to);
  1257. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0") ||
  1258. !strcmp(from, "::")) {
  1259. const char type =
  1260. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME :
  1261. (!strcmp(from, "0.0.0.0") ? RESOLVED_TYPE_IPV4 : RESOLVED_TYPE_IPV6);
  1262. const char *address = addressmap_register_virtual_address(
  1263. type, tor_strdup(to));
  1264. if (!address) {
  1265. smartlist_add_asprintf(reply,
  1266. "451-resource exhausted: skipping '%s'", line);
  1267. log_warn(LD_CONTROL,
  1268. "Unable to allocate address for '%s' in MapAddress msg",
  1269. safe_str_client(line));
  1270. } else {
  1271. smartlist_add_asprintf(reply, "250-%s=%s", address, to);
  1272. }
  1273. } else {
  1274. const char *msg;
  1275. if (addressmap_register_auto(from, to, 1,
  1276. ADDRMAPSRC_CONTROLLER, &msg) < 0) {
  1277. smartlist_add_asprintf(reply,
  1278. "512-syntax error: invalid address mapping "
  1279. " '%s': %s", line, msg);
  1280. log_warn(LD_CONTROL,
  1281. "Skipping invalid argument '%s' in MapAddress msg: %s",
  1282. line, msg);
  1283. } else {
  1284. smartlist_add_asprintf(reply, "250-%s", line);
  1285. }
  1286. }
  1287. } else {
  1288. smartlist_add_asprintf(reply, "512-syntax error: mapping '%s' is "
  1289. "not of expected form 'foo=bar'.", line);
  1290. log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
  1291. "number of items.",
  1292. safe_str_client(line));
  1293. }
  1294. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1295. smartlist_clear(elts);
  1296. } SMARTLIST_FOREACH_END(line);
  1297. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1298. smartlist_free(lines);
  1299. smartlist_free(elts);
  1300. if (smartlist_len(reply)) {
  1301. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1302. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1303. connection_write_to_buf(r, sz, TO_CONN(conn));
  1304. tor_free(r);
  1305. } else {
  1306. const char *response =
  1307. "512 syntax error: not enough arguments to mapaddress.\r\n";
  1308. connection_write_to_buf(response, strlen(response), TO_CONN(conn));
  1309. }
  1310. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1311. smartlist_free(reply);
  1312. return 0;
  1313. }
  1314. /** Implementation helper for GETINFO: knows the answers for various
  1315. * trivial-to-implement questions. */
  1316. static int
  1317. getinfo_helper_misc(control_connection_t *conn, const char *question,
  1318. char **answer, const char **errmsg)
  1319. {
  1320. (void) conn;
  1321. if (!strcmp(question, "version")) {
  1322. *answer = tor_strdup(get_version());
  1323. } else if (!strcmp(question, "bw-event-cache")) {
  1324. *answer = get_bw_samples();
  1325. } else if (!strcmp(question, "config-file")) {
  1326. const char *a = get_torrc_fname(0);
  1327. if (a)
  1328. *answer = tor_strdup(a);
  1329. } else if (!strcmp(question, "config-defaults-file")) {
  1330. const char *a = get_torrc_fname(1);
  1331. if (a)
  1332. *answer = tor_strdup(a);
  1333. } else if (!strcmp(question, "config-text")) {
  1334. *answer = options_dump(get_options(), OPTIONS_DUMP_MINIMAL);
  1335. } else if (!strcmp(question, "info/names")) {
  1336. *answer = list_getinfo_options();
  1337. } else if (!strcmp(question, "dormant")) {
  1338. int dormant = rep_hist_circbuilding_dormant(time(NULL));
  1339. *answer = tor_strdup(dormant ? "1" : "0");
  1340. } else if (!strcmp(question, "events/names")) {
  1341. int i;
  1342. smartlist_t *event_names = smartlist_new();
  1343. for (i = 0; control_event_table[i].event_name != NULL; ++i) {
  1344. smartlist_add(event_names, (char *)control_event_table[i].event_name);
  1345. }
  1346. *answer = smartlist_join_strings(event_names, " ", 0, NULL);
  1347. smartlist_free(event_names);
  1348. } else if (!strcmp(question, "signal/names")) {
  1349. smartlist_t *signal_names = smartlist_new();
  1350. int j;
  1351. for (j = 0; signal_table[j].signal_name != NULL; ++j) {
  1352. smartlist_add(signal_names, (char*)signal_table[j].signal_name);
  1353. }
  1354. *answer = smartlist_join_strings(signal_names, " ", 0, NULL);
  1355. smartlist_free(signal_names);
  1356. } else if (!strcmp(question, "features/names")) {
  1357. *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
  1358. } else if (!strcmp(question, "address")) {
  1359. uint32_t addr;
  1360. if (router_pick_published_address(get_options(), &addr) < 0) {
  1361. *errmsg = "Address unknown";
  1362. return -1;
  1363. }
  1364. *answer = tor_dup_ip(addr);
  1365. } else if (!strcmp(question, "traffic/read")) {
  1366. tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_read()));
  1367. } else if (!strcmp(question, "traffic/written")) {
  1368. tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_written()));
  1369. } else if (!strcmp(question, "process/pid")) {
  1370. int myPid = -1;
  1371. #ifdef _WIN32
  1372. myPid = _getpid();
  1373. #else
  1374. myPid = getpid();
  1375. #endif
  1376. tor_asprintf(answer, "%d", myPid);
  1377. } else if (!strcmp(question, "process/uid")) {
  1378. #ifdef _WIN32
  1379. *answer = tor_strdup("-1");
  1380. #else
  1381. int myUid = geteuid();
  1382. tor_asprintf(answer, "%d", myUid);
  1383. #endif
  1384. } else if (!strcmp(question, "process/user")) {
  1385. #ifdef _WIN32
  1386. *answer = tor_strdup("");
  1387. #else
  1388. int myUid = geteuid();
  1389. const struct passwd *myPwEntry = tor_getpwuid(myUid);
  1390. if (myPwEntry) {
  1391. *answer = tor_strdup(myPwEntry->pw_name);
  1392. } else {
  1393. *answer = tor_strdup("");
  1394. }
  1395. #endif
  1396. } else if (!strcmp(question, "process/descriptor-limit")) {
  1397. int max_fds=-1;
  1398. set_max_file_descriptors(0, &max_fds);
  1399. tor_asprintf(answer, "%d", max_fds);
  1400. } else if (!strcmp(question, "limits/max-mem-in-queues")) {
  1401. tor_asprintf(answer, U64_FORMAT,
  1402. U64_PRINTF_ARG(get_options()->MaxMemInQueues));
  1403. } else if (!strcmp(question, "dir-usage")) {
  1404. *answer = directory_dump_request_log();
  1405. } else if (!strcmp(question, "fingerprint")) {
  1406. crypto_pk_t *server_key;
  1407. if (!server_mode(get_options())) {
  1408. *errmsg = "Not running in server mode";
  1409. return -1;
  1410. }
  1411. server_key = get_server_identity_key();
  1412. *answer = tor_malloc(HEX_DIGEST_LEN+1);
  1413. crypto_pk_get_fingerprint(server_key, *answer, 0);
  1414. }
  1415. return 0;
  1416. }
  1417. /** Awful hack: return a newly allocated string based on a routerinfo and
  1418. * (possibly) an extrainfo, sticking the read-history and write-history from
  1419. * <b>ei</b> into the resulting string. The thing you get back won't
  1420. * necessarily have a valid signature.
  1421. *
  1422. * New code should never use this; it's for backward compatibility.
  1423. *
  1424. * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
  1425. * not be NUL-terminated. */
  1426. static char *
  1427. munge_extrainfo_into_routerinfo(const char *ri_body,
  1428. const signed_descriptor_t *ri,
  1429. const signed_descriptor_t *ei)
  1430. {
  1431. char *out = NULL, *outp;
  1432. int i;
  1433. const char *router_sig;
  1434. const char *ei_body = signed_descriptor_get_body(ei);
  1435. size_t ri_len = ri->signed_descriptor_len;
  1436. size_t ei_len = ei->signed_descriptor_len;
  1437. if (!ei_body)
  1438. goto bail;
  1439. outp = out = tor_malloc(ri_len+ei_len+1);
  1440. if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
  1441. goto bail;
  1442. ++router_sig;
  1443. memcpy(out, ri_body, router_sig-ri_body);
  1444. outp += router_sig-ri_body;
  1445. for (i=0; i < 2; ++i) {
  1446. const char *kwd = i ? "\nwrite-history " : "\nread-history ";
  1447. const char *cp, *eol;
  1448. if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
  1449. continue;
  1450. ++cp;
  1451. if (!(eol = memchr(cp, '\n', ei_len - (cp-ei_body))))
  1452. continue;
  1453. memcpy(outp, cp, eol-cp+1);
  1454. outp += eol-cp+1;
  1455. }
  1456. memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
  1457. *outp++ = '\0';
  1458. tor_assert(outp-out < (int)(ri_len+ei_len+1));
  1459. return out;
  1460. bail:
  1461. tor_free(out);
  1462. return tor_strndup(ri_body, ri->signed_descriptor_len);
  1463. }
  1464. /** Implementation helper for GETINFO: answers requests for information about
  1465. * which ports are bound. */
  1466. static int
  1467. getinfo_helper_listeners(control_connection_t *control_conn,
  1468. const char *question,
  1469. char **answer, const char **errmsg)
  1470. {
  1471. int type;
  1472. smartlist_t *res;
  1473. (void)control_conn;
  1474. (void)errmsg;
  1475. if (!strcmp(question, "net/listeners/or"))
  1476. type = CONN_TYPE_OR_LISTENER;
  1477. else if (!strcmp(question, "net/listeners/dir"))
  1478. type = CONN_TYPE_DIR_LISTENER;
  1479. else if (!strcmp(question, "net/listeners/socks"))
  1480. type = CONN_TYPE_AP_LISTENER;
  1481. else if (!strcmp(question, "net/listeners/trans"))
  1482. type = CONN_TYPE_AP_TRANS_LISTENER;
  1483. else if (!strcmp(question, "net/listeners/natd"))
  1484. type = CONN_TYPE_AP_NATD_LISTENER;
  1485. else if (!strcmp(question, "net/listeners/dns"))
  1486. type = CONN_TYPE_AP_DNS_LISTENER;
  1487. else if (!strcmp(question, "net/listeners/control"))
  1488. type = CONN_TYPE_CONTROL_LISTENER;
  1489. else
  1490. return 0; /* unknown key */
  1491. res = smartlist_new();
  1492. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  1493. struct sockaddr_storage ss;
  1494. socklen_t ss_len = sizeof(ss);
  1495. if (conn->type != type || conn->marked_for_close || !SOCKET_OK(conn->s))
  1496. continue;
  1497. if (getsockname(conn->s, (struct sockaddr *)&ss, &ss_len) < 0) {
  1498. smartlist_add_asprintf(res, "%s:%d", conn->address, (int)conn->port);
  1499. } else {
  1500. char *tmp = tor_sockaddr_to_str((struct sockaddr *)&ss);
  1501. smartlist_add(res, esc_for_log(tmp));
  1502. tor_free(tmp);
  1503. }
  1504. } SMARTLIST_FOREACH_END(conn);
  1505. *answer = smartlist_join_strings(res, " ", 0, NULL);
  1506. SMARTLIST_FOREACH(res, char *, cp, tor_free(cp));
  1507. smartlist_free(res);
  1508. return 0;
  1509. }
  1510. /** Implementation helper for GETINFO: knows the answers for questions about
  1511. * directory information. */
  1512. static int
  1513. getinfo_helper_dir(control_connection_t *control_conn,
  1514. const char *question, char **answer,
  1515. const char **errmsg)
  1516. {
  1517. const node_t *node;
  1518. const routerinfo_t *ri = NULL;
  1519. (void) control_conn;
  1520. if (!strcmpstart(question, "desc/id/")) {
  1521. node = node_get_by_hex_id(question+strlen("desc/id/"));
  1522. if (node)
  1523. ri = node->ri;
  1524. if (ri) {
  1525. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1526. if (body)
  1527. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1528. }
  1529. } else if (!strcmpstart(question, "desc/name/")) {
  1530. /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
  1531. * warning goes to the user, not to the controller. */
  1532. node = node_get_by_nickname(question+strlen("desc/name/"), 1);
  1533. if (node)
  1534. ri = node->ri;
  1535. if (ri) {
  1536. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1537. if (body)
  1538. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1539. }
  1540. } else if (!strcmp(question, "desc/all-recent")) {
  1541. routerlist_t *routerlist = router_get_routerlist();
  1542. smartlist_t *sl = smartlist_new();
  1543. if (routerlist && routerlist->routers) {
  1544. SMARTLIST_FOREACH(routerlist->routers, const routerinfo_t *, ri,
  1545. {
  1546. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1547. if (body)
  1548. smartlist_add(sl,
  1549. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1550. });
  1551. }
  1552. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1553. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1554. smartlist_free(sl);
  1555. } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
  1556. /* XXXX Remove this once Torstat asks for extrainfos. */
  1557. routerlist_t *routerlist = router_get_routerlist();
  1558. smartlist_t *sl = smartlist_new();
  1559. if (routerlist && routerlist->routers) {
  1560. SMARTLIST_FOREACH_BEGIN(routerlist->routers, const routerinfo_t *, ri) {
  1561. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1562. signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
  1563. ri->cache_info.extra_info_digest);
  1564. if (ei && body) {
  1565. smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
  1566. &ri->cache_info, ei));
  1567. } else if (body) {
  1568. smartlist_add(sl,
  1569. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1570. }
  1571. } SMARTLIST_FOREACH_END(ri);
  1572. }
  1573. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1574. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1575. smartlist_free(sl);
  1576. } else if (!strcmpstart(question, "hs/client/desc/id/")) {
  1577. rend_cache_entry_t *e = NULL;
  1578. question += strlen("hs/client/desc/id/");
  1579. if (strlen(question) != REND_SERVICE_ID_LEN_BASE32) {
  1580. *errmsg = "Invalid address";
  1581. return -1;
  1582. }
  1583. if (rend_cache_lookup_entry(question, -1, &e) > 0) {
  1584. /* Descriptor found in cache */
  1585. *answer = tor_strdup(e->desc);
  1586. } else {
  1587. *errmsg = "Not found in cache";
  1588. return -1;
  1589. }
  1590. } else if (!strcmpstart(question, "md/id/")) {
  1591. const node_t *node = node_get_by_hex_id(question+strlen("md/id/"));
  1592. const microdesc_t *md = NULL;
  1593. if (node) md = node->md;
  1594. if (md && md->body) {
  1595. *answer = tor_strndup(md->body, md->bodylen);
  1596. }
  1597. } else if (!strcmpstart(question, "md/name/")) {
  1598. /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
  1599. * warning goes to the user, not to the controller. */
  1600. const node_t *node = node_get_by_nickname(question+strlen("md/name/"), 1);
  1601. /* XXXX duplicated code */
  1602. const microdesc_t *md = NULL;
  1603. if (node) md = node->md;
  1604. if (md && md->body) {
  1605. *answer = tor_strndup(md->body, md->bodylen);
  1606. }
  1607. } else if (!strcmpstart(question, "desc-annotations/id/")) {
  1608. node = node_get_by_hex_id(question+strlen("desc-annotations/id/"));
  1609. if (node)
  1610. ri = node->ri;
  1611. if (ri) {
  1612. const char *annotations =
  1613. signed_descriptor_get_annotations(&ri->cache_info);
  1614. if (annotations)
  1615. *answer = tor_strndup(annotations,
  1616. ri->cache_info.annotations_len);
  1617. }
  1618. } else if (!strcmpstart(question, "dir/server/")) {
  1619. size_t answer_len = 0;
  1620. char *url = NULL;
  1621. smartlist_t *descs = smartlist_new();
  1622. const char *msg;
  1623. int res;
  1624. char *cp;
  1625. tor_asprintf(&url, "/tor/%s", question+4);
  1626. res = dirserv_get_routerdescs(descs, url, &msg);
  1627. if (res) {
  1628. log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
  1629. smartlist_free(descs);
  1630. tor_free(url);
  1631. *errmsg = msg;
  1632. return -1;
  1633. }
  1634. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1635. answer_len += sd->signed_descriptor_len);
  1636. cp = *answer = tor_malloc(answer_len+1);
  1637. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1638. {
  1639. memcpy(cp, signed_descriptor_get_body(sd),
  1640. sd->signed_descriptor_len);
  1641. cp += sd->signed_descriptor_len;
  1642. });
  1643. *cp = '\0';
  1644. tor_free(url);
  1645. smartlist_free(descs);
  1646. } else if (!strcmpstart(question, "dir/status/")) {
  1647. *answer = tor_strdup("");
  1648. } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
  1649. if (directory_caches_dir_info(get_options())) {
  1650. const cached_dir_t *consensus = dirserv_get_consensus("ns");
  1651. if (consensus)
  1652. *answer = tor_strdup(consensus->dir);
  1653. }
  1654. if (!*answer) { /* try loading it from disk */
  1655. char *filename = get_datadir_fname("cached-consensus");
  1656. *answer = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  1657. tor_free(filename);
  1658. }
  1659. } else if (!strcmp(question, "network-status")) { /* v1 */
  1660. routerlist_t *routerlist = router_get_routerlist();
  1661. if (!routerlist || !routerlist->routers ||
  1662. list_server_status_v1(routerlist->routers, answer, 1) < 0) {
  1663. return -1;
  1664. }
  1665. } else if (!strcmpstart(question, "extra-info/digest/")) {
  1666. question += strlen("extra-info/digest/");
  1667. if (strlen(question) == HEX_DIGEST_LEN) {
  1668. char d[DIGEST_LEN];
  1669. signed_descriptor_t *sd = NULL;
  1670. if (base16_decode(d, sizeof(d), question, strlen(question))==0) {
  1671. /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
  1672. * but I don't want to risk affecting other parts of the code,
  1673. * especially since the rules for using our own extrainfo (including
  1674. * when it might be freed) are different from those for using one
  1675. * we have downloaded. */
  1676. if (router_extrainfo_digest_is_me(d))
  1677. sd = &(router_get_my_extrainfo()->cache_info);
  1678. else
  1679. sd = extrainfo_get_by_descriptor_digest(d);
  1680. }
  1681. if (sd) {
  1682. const char *body = signed_descriptor_get_body(sd);
  1683. if (body)
  1684. *answer = tor_strndup(body, sd->signed_descriptor_len);
  1685. }
  1686. }
  1687. }
  1688. return 0;
  1689. }
  1690. /** Allocate and return a description of <b>circ</b>'s current status,
  1691. * including its path (if any). */
  1692. static char *
  1693. circuit_describe_status_for_controller(origin_circuit_t *circ)
  1694. {
  1695. char *rv;
  1696. smartlist_t *descparts = smartlist_new();
  1697. {
  1698. char *vpath = circuit_list_path_for_controller(circ);
  1699. if (*vpath) {
  1700. smartlist_add(descparts, vpath);
  1701. } else {
  1702. tor_free(vpath); /* empty path; don't put an extra space in the result */
  1703. }
  1704. }
  1705. {
  1706. cpath_build_state_t *build_state = circ->build_state;
  1707. smartlist_t *flaglist = smartlist_new();
  1708. char *flaglist_joined;
  1709. if (build_state->onehop_tunnel)
  1710. smartlist_add(flaglist, (void *)"ONEHOP_TUNNEL");
  1711. if (build_state->is_internal)
  1712. smartlist_add(flaglist, (void *)"IS_INTERNAL");
  1713. if (build_state->need_capacity)
  1714. smartlist_add(flaglist, (void *)"NEED_CAPACITY");
  1715. if (build_state->need_uptime)
  1716. smartlist_add(flaglist, (void *)"NEED_UPTIME");
  1717. /* Only emit a BUILD_FLAGS argument if it will have a non-empty value. */
  1718. if (smartlist_len(flaglist)) {
  1719. flaglist_joined = smartlist_join_strings(flaglist, ",", 0, NULL);
  1720. smartlist_add_asprintf(descparts, "BUILD_FLAGS=%s", flaglist_joined);
  1721. tor_free(flaglist_joined);
  1722. }
  1723. smartlist_free(flaglist);
  1724. }
  1725. smartlist_add_asprintf(descparts, "PURPOSE=%s",
  1726. circuit_purpose_to_controller_string(circ->base_.purpose));
  1727. {
  1728. const char *hs_state =
  1729. circuit_purpose_to_controller_hs_state_string(circ->base_.purpose);
  1730. if (hs_state != NULL) {
  1731. smartlist_add_asprintf(descparts, "HS_STATE=%s", hs_state);
  1732. }
  1733. }
  1734. if (circ->rend_data != NULL) {
  1735. smartlist_add_asprintf(descparts, "REND_QUERY=%s",
  1736. circ->rend_data->onion_address);
  1737. }
  1738. {
  1739. char tbuf[ISO_TIME_USEC_LEN+1];
  1740. format_iso_time_nospace_usec(tbuf, &circ->base_.timestamp_created);
  1741. smartlist_add_asprintf(descparts, "TIME_CREATED=%s", tbuf);
  1742. }
  1743. // Show username and/or password if available.
  1744. if (circ->socks_username_len > 0) {
  1745. char* socks_username_escaped = esc_for_log_len(circ->socks_username,
  1746. (size_t) circ->socks_username_len);
  1747. smartlist_add_asprintf(descparts, "SOCKS_USERNAME=%s",
  1748. socks_username_escaped);
  1749. tor_free(socks_username_escaped);
  1750. }
  1751. if (circ->socks_password_len > 0) {
  1752. char* socks_password_escaped = esc_for_log_len(circ->socks_password,
  1753. (size_t) circ->socks_password_len);
  1754. smartlist_add_asprintf(descparts, "SOCKS_PASSWORD=%s",
  1755. socks_password_escaped);
  1756. tor_free(socks_password_escaped);
  1757. }
  1758. rv = smartlist_join_strings(descparts, " ", 0, NULL);
  1759. SMARTLIST_FOREACH(descparts, char *, cp, tor_free(cp));
  1760. smartlist_free(descparts);
  1761. return rv;
  1762. }
  1763. /** Implementation helper for GETINFO: knows how to generate summaries of the
  1764. * current states of things we send events about. */
  1765. static int
  1766. getinfo_helper_events(control_connection_t *control_conn,
  1767. const char *question, char **answer,
  1768. const char **errmsg)
  1769. {
  1770. (void) control_conn;
  1771. if (!strcmp(question, "circuit-status")) {
  1772. smartlist_t *status = smartlist_new();
  1773. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ_) {
  1774. origin_circuit_t *circ;
  1775. char *circdesc;
  1776. const char *state;
  1777. if (! CIRCUIT_IS_ORIGIN(circ_) || circ_->marked_for_close)
  1778. continue;
  1779. circ = TO_ORIGIN_CIRCUIT(circ_);
  1780. if (circ->base_.state == CIRCUIT_STATE_OPEN)
  1781. state = "BUILT";
  1782. else if (circ->cpath)
  1783. state = "EXTENDED";
  1784. else
  1785. state = "LAUNCHED";
  1786. circdesc = circuit_describe_status_for_controller(circ);
  1787. smartlist_add_asprintf(status, "%lu %s%s%s",
  1788. (unsigned long)circ->global_identifier,
  1789. state, *circdesc ? " " : "", circdesc);
  1790. tor_free(circdesc);
  1791. }
  1792. SMARTLIST_FOREACH_END(circ_);
  1793. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1794. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1795. smartlist_free(status);
  1796. } else if (!strcmp(question, "stream-status")) {
  1797. smartlist_t *conns = get_connection_array();
  1798. smartlist_t *status = smartlist_new();
  1799. char buf[256];
  1800. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1801. const char *state;
  1802. entry_connection_t *conn;
  1803. circuit_t *circ;
  1804. origin_circuit_t *origin_circ = NULL;
  1805. if (base_conn->type != CONN_TYPE_AP ||
  1806. base_conn->marked_for_close ||
  1807. base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
  1808. base_conn->state == AP_CONN_STATE_NATD_WAIT)
  1809. continue;
  1810. conn = TO_ENTRY_CONN(base_conn);
  1811. switch (base_conn->state)
  1812. {
  1813. case AP_CONN_STATE_CONTROLLER_WAIT:
  1814. case AP_CONN_STATE_CIRCUIT_WAIT:
  1815. if (conn->socks_request &&
  1816. SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  1817. state = "NEWRESOLVE";
  1818. else
  1819. state = "NEW";
  1820. break;
  1821. case AP_CONN_STATE_RENDDESC_WAIT:
  1822. case AP_CONN_STATE_CONNECT_WAIT:
  1823. state = "SENTCONNECT"; break;
  1824. case AP_CONN_STATE_RESOLVE_WAIT:
  1825. state = "SENTRESOLVE"; break;
  1826. case AP_CONN_STATE_OPEN:
  1827. state = "SUCCEEDED"; break;
  1828. default:
  1829. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  1830. base_conn->state);
  1831. continue;
  1832. }
  1833. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  1834. if (circ && CIRCUIT_IS_ORIGIN(circ))
  1835. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1836. write_stream_target_to_buf(conn, buf, sizeof(buf));
  1837. smartlist_add_asprintf(status, "%lu %s %lu %s",
  1838. (unsigned long) base_conn->global_identifier,state,
  1839. origin_circ?
  1840. (unsigned long)origin_circ->global_identifier : 0ul,
  1841. buf);
  1842. } SMARTLIST_FOREACH_END(base_conn);
  1843. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1844. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1845. smartlist_free(status);
  1846. } else if (!strcmp(question, "orconn-status")) {
  1847. smartlist_t *conns = get_connection_array();
  1848. smartlist_t *status = smartlist_new();
  1849. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1850. const char *state;
  1851. char name[128];
  1852. or_connection_t *conn;
  1853. if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
  1854. continue;
  1855. conn = TO_OR_CONN(base_conn);
  1856. if (conn->base_.state == OR_CONN_STATE_OPEN)
  1857. state = "CONNECTED";
  1858. else if (conn->nickname)
  1859. state = "LAUNCHED";
  1860. else
  1861. state = "NEW";
  1862. orconn_target_get_name(name, sizeof(name), conn);
  1863. smartlist_add_asprintf(status, "%s %s", name, state);
  1864. } SMARTLIST_FOREACH_END(base_conn);
  1865. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1866. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1867. smartlist_free(status);
  1868. } else if (!strcmpstart(question, "address-mappings/")) {
  1869. time_t min_e, max_e;
  1870. smartlist_t *mappings;
  1871. question += strlen("address-mappings/");
  1872. if (!strcmp(question, "all")) {
  1873. min_e = 0; max_e = TIME_MAX;
  1874. } else if (!strcmp(question, "cache")) {
  1875. min_e = 2; max_e = TIME_MAX;
  1876. } else if (!strcmp(question, "config")) {
  1877. min_e = 0; max_e = 0;
  1878. } else if (!strcmp(question, "control")) {
  1879. min_e = 1; max_e = 1;
  1880. } else {
  1881. return 0;
  1882. }
  1883. mappings = smartlist_new();
  1884. addressmap_get_mappings(mappings, min_e, max_e, 1);
  1885. *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
  1886. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  1887. smartlist_free(mappings);
  1888. } else if (!strcmpstart(question, "status/")) {
  1889. /* Note that status/ is not a catch-all for events; there's only supposed
  1890. * to be a status GETINFO if there's a corresponding STATUS event. */
  1891. if (!strcmp(question, "status/circuit-established")) {
  1892. *answer = tor_strdup(have_completed_a_circuit() ? "1" : "0");
  1893. } else if (!strcmp(question, "status/enough-dir-info")) {
  1894. *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
  1895. } else if (!strcmp(question, "status/good-server-descriptor") ||
  1896. !strcmp(question, "status/accepted-server-descriptor")) {
  1897. /* They're equivalent for now, until we can figure out how to make
  1898. * good-server-descriptor be what we want. See comment in
  1899. * control-spec.txt. */
  1900. *answer = tor_strdup(directories_have_accepted_server_descriptor()
  1901. ? "1" : "0");
  1902. } else if (!strcmp(question, "status/reachability-succeeded/or")) {
  1903. *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
  1904. } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
  1905. *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
  1906. } else if (!strcmp(question, "status/reachability-succeeded")) {
  1907. tor_asprintf(answer, "OR=%d DIR=%d",
  1908. check_whether_orport_reachable() ? 1 : 0,
  1909. check_whether_dirport_reachable() ? 1 : 0);
  1910. } else if (!strcmp(question, "status/bootstrap-phase")) {
  1911. *answer = tor_strdup(last_sent_bootstrap_message);
  1912. } else if (!strcmpstart(question, "status/version/")) {
  1913. int is_server = server_mode(get_options());
  1914. networkstatus_t *c = networkstatus_get_latest_consensus();
  1915. version_status_t status;
  1916. const char *recommended;
  1917. if (c) {
  1918. recommended = is_server ? c->server_versions : c->client_versions;
  1919. status = tor_version_is_obsolete(VERSION, recommended);
  1920. } else {
  1921. recommended = "?";
  1922. status = VS_UNKNOWN;
  1923. }
  1924. if (!strcmp(question, "status/version/recommended")) {
  1925. *answer = tor_strdup(recommended);
  1926. return 0;
  1927. }
  1928. if (!strcmp(question, "status/version/current")) {
  1929. switch (status)
  1930. {
  1931. case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
  1932. case VS_OLD: *answer = tor_strdup("obsolete"); break;
  1933. case VS_NEW: *answer = tor_strdup("new"); break;
  1934. case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
  1935. case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
  1936. case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
  1937. case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
  1938. default: tor_fragile_assert();
  1939. }
  1940. } else if (!strcmp(question, "status/version/num-versioning") ||
  1941. !strcmp(question, "status/version/num-concurring")) {
  1942. tor_asprintf(answer, "%d", get_n_authorities(V3_DIRINFO));
  1943. log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
  1944. "information", question);
  1945. }
  1946. } else if (!strcmp(question, "status/clients-seen")) {
  1947. char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
  1948. if (!bridge_stats) {
  1949. *errmsg = "No bridge-client stats available";
  1950. return -1;
  1951. }
  1952. *answer = bridge_stats;
  1953. } else if (!strcmp(question, "status/fresh-relay-descs")) {
  1954. if (!server_mode(get_options())) {
  1955. *errmsg = "Only relays have descriptors";
  1956. return -1;
  1957. }
  1958. routerinfo_t *r;
  1959. extrainfo_t *e;
  1960. if (router_build_fresh_descriptor(&r, &e) < 0) {
  1961. *errmsg = "Error generating descriptor";
  1962. return -1;
  1963. }
  1964. size_t size = r->cache_info.signed_descriptor_len + 1;
  1965. if (e) {
  1966. size += e->cache_info.signed_descriptor_len + 1;
  1967. }
  1968. tor_assert(r->cache_info.signed_descriptor_len);
  1969. char *descs = tor_malloc(size);
  1970. char *cp = descs;
  1971. memcpy(cp, signed_descriptor_get_body(&r->cache_info),
  1972. r->cache_info.signed_descriptor_len);
  1973. cp += r->cache_info.signed_descriptor_len - 1;
  1974. if (e) {
  1975. if (cp[0] == '\0') {
  1976. cp[0] = '\n';
  1977. } else if (cp[0] != '\n') {
  1978. cp[1] = '\n';
  1979. cp++;
  1980. }
  1981. memcpy(cp, signed_descriptor_get_body(&e->cache_info),
  1982. e->cache_info.signed_descriptor_len);
  1983. cp += e->cache_info.signed_descriptor_len - 1;
  1984. }
  1985. if (cp[0] == '\n') {
  1986. cp[0] = '\0';
  1987. } else if (cp[0] != '\0') {
  1988. cp[1] = '\0';
  1989. }
  1990. *answer = descs;
  1991. routerinfo_free(r);
  1992. extrainfo_free(e);
  1993. } else {
  1994. return 0;
  1995. }
  1996. }
  1997. return 0;
  1998. }
  1999. /** Implementation helper for GETINFO: knows how to enumerate hidden services
  2000. * created via the control port. */
  2001. static int
  2002. getinfo_helper_onions(control_connection_t *control_conn,
  2003. const char *question, char **answer,
  2004. const char **errmsg)
  2005. {
  2006. smartlist_t *onion_list = NULL;
  2007. if (!strcmp(question, "onions/current")) {
  2008. onion_list = control_conn->ephemeral_onion_services;
  2009. } else if (!strcmp(question, "onions/detached")) {
  2010. onion_list = detached_onion_services;
  2011. } else {
  2012. return 0;
  2013. }
  2014. if (!onion_list || smartlist_len(onion_list) == 0) {
  2015. *errmsg = "No onion services of the specified type.";
  2016. return -1;
  2017. }
  2018. *answer = smartlist_join_strings(onion_list, "\r\n", 0, NULL);
  2019. return 0;
  2020. }
  2021. /** Callback function for GETINFO: on a given control connection, try to
  2022. * answer the question <b>q</b> and store the newly-allocated answer in
  2023. * *<b>a</b>. If an internal error occurs, return -1 and optionally set
  2024. * *<b>error_out</b> to point to an error message to be delivered to the
  2025. * controller. On success, _or if the key is not recognized_, return 0. Do not
  2026. * set <b>a</b> if the key is not recognized.
  2027. */
  2028. typedef int (*getinfo_helper_t)(control_connection_t *,
  2029. const char *q, char **a,
  2030. const char **error_out);
  2031. /** A single item for the GETINFO question-to-answer-function table. */
  2032. typedef struct getinfo_item_t {
  2033. const char *varname; /**< The value (or prefix) of the question. */
  2034. getinfo_helper_t fn; /**< The function that knows the answer: NULL if
  2035. * this entry is documentation-only. */
  2036. const char *desc; /**< Description of the variable. */
  2037. int is_prefix; /** Must varname match exactly, or must it be a prefix? */
  2038. } getinfo_item_t;
  2039. #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
  2040. #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
  2041. #define DOC(name, desc) { name, NULL, desc, 0 }
  2042. /** Table mapping questions accepted by GETINFO to the functions that know how
  2043. * to answer them. */
  2044. static const getinfo_item_t getinfo_items[] = {
  2045. ITEM("version", misc, "The current version of Tor."),
  2046. ITEM("bw-event-cache", misc, "Cached BW events for a short interval."),
  2047. ITEM("config-file", misc, "Current location of the \"torrc\" file."),
  2048. ITEM("config-defaults-file", misc, "Current location of the defaults file."),
  2049. ITEM("config-text", misc,
  2050. "Return the string that would be written by a saveconf command."),
  2051. ITEM("accounting/bytes", accounting,
  2052. "Number of bytes read/written so far in the accounting interval."),
  2053. ITEM("accounting/bytes-left", accounting,
  2054. "Number of bytes left to write/read so far in the accounting interval."),
  2055. ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
  2056. ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
  2057. ITEM("accounting/interval-start", accounting,
  2058. "Time when the accounting period starts."),
  2059. ITEM("accounting/interval-end", accounting,
  2060. "Time when the accounting period ends."),
  2061. ITEM("accounting/interval-wake", accounting,
  2062. "Time to wake up in this accounting period."),
  2063. ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
  2064. ITEM("entry-guards", entry_guards,
  2065. "Which nodes are we using as entry guards?"),
  2066. ITEM("fingerprint", misc, NULL),
  2067. PREFIX("config/", config, "Current configuration values."),
  2068. DOC("config/names",
  2069. "List of configuration options, types, and documentation."),
  2070. DOC("config/defaults",
  2071. "List of default values for configuration options. "
  2072. "See also config/names"),
  2073. ITEM("info/names", misc,
  2074. "List of GETINFO options, types, and documentation."),
  2075. ITEM("events/names", misc,
  2076. "Events that the controller can ask for with SETEVENTS."),
  2077. ITEM("signal/names", misc, "Signal names recognized by the SIGNAL command"),
  2078. ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
  2079. PREFIX("desc/id/", dir, "Router descriptors by ID."),
  2080. PREFIX("desc/name/", dir, "Router descriptors by nickname."),
  2081. ITEM("desc/all-recent", dir,
  2082. "All non-expired, non-superseded router descriptors."),
  2083. ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
  2084. PREFIX("md/id/", dir, "Microdescriptors by ID"),
  2085. PREFIX("md/name/", dir, "Microdescriptors by name"),
  2086. PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
  2087. PREFIX("hs/client/desc/id", dir,
  2088. "Hidden Service descriptor in client's cache by onion."),
  2089. PREFIX("net/listeners/", listeners, "Bound addresses by type"),
  2090. ITEM("ns/all", networkstatus,
  2091. "Brief summary of router status (v2 directory format)"),
  2092. PREFIX("ns/id/", networkstatus,
  2093. "Brief summary of router status by ID (v2 directory format)."),
  2094. PREFIX("ns/name/", networkstatus,
  2095. "Brief summary of router status by nickname (v2 directory format)."),
  2096. PREFIX("ns/purpose/", networkstatus,
  2097. "Brief summary of router status by purpose (v2 directory format)."),
  2098. PREFIX("consensus/", networkstatus,
  2099. "Information about and from the ns consensus."),
  2100. ITEM("network-status", dir,
  2101. "Brief summary of router status (v1 directory format)"),
  2102. ITEM("circuit-status", events, "List of current circuits originating here."),
  2103. ITEM("stream-status", events,"List of current streams."),
  2104. ITEM("orconn-status", events, "A list of current OR connections."),
  2105. ITEM("dormant", misc,
  2106. "Is Tor dormant (not building circuits because it's idle)?"),
  2107. PREFIX("address-mappings/", events, NULL),
  2108. DOC("address-mappings/all", "Current address mappings."),
  2109. DOC("address-mappings/cache", "Current cached DNS replies."),
  2110. DOC("address-mappings/config",
  2111. "Current address mappings from configuration."),
  2112. DOC("address-mappings/control", "Current address mappings from controller."),
  2113. PREFIX("status/", events, NULL),
  2114. DOC("status/circuit-established",
  2115. "Whether we think client functionality is working."),
  2116. DOC("status/enough-dir-info",
  2117. "Whether we have enough up-to-date directory information to build "
  2118. "circuits."),
  2119. DOC("status/bootstrap-phase",
  2120. "The last bootstrap phase status event that Tor sent."),
  2121. DOC("status/clients-seen",
  2122. "Breakdown of client countries seen by a bridge."),
  2123. DOC("status/fresh-relay-descs",
  2124. "A fresh relay/ei descriptor pair for Tor's current state. Not stored."),
  2125. DOC("status/version/recommended", "List of currently recommended versions."),
  2126. DOC("status/version/current", "Status of the current version."),
  2127. DOC("status/version/num-versioning", "Number of versioning authorities."),
  2128. DOC("status/version/num-concurring",
  2129. "Number of versioning authorities agreeing on the status of the "
  2130. "current version"),
  2131. ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
  2132. ITEM("traffic/read", misc,"Bytes read since the process was started."),
  2133. ITEM("traffic/written", misc,
  2134. "Bytes written since the process was started."),
  2135. ITEM("process/pid", misc, "Process id belonging to the main tor process."),
  2136. ITEM("process/uid", misc, "User id running the tor process."),
  2137. ITEM("process/user", misc,
  2138. "Username under which the tor process is running."),
  2139. ITEM("process/descriptor-limit", misc, "File descriptor limit."),
  2140. ITEM("limits/max-mem-in-queues", misc, "Actual limit on memory in queues"),
  2141. ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
  2142. PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
  2143. PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
  2144. PREFIX("dir/status/", dir,
  2145. "v2 networkstatus docs as retrieved from a DirPort."),
  2146. ITEM("dir/status-vote/current/consensus", dir,
  2147. "v3 Networkstatus consensus as retrieved from a DirPort."),
  2148. ITEM("exit-policy/default", policies,
  2149. "The default value appended to the configured exit policy."),
  2150. ITEM("exit-policy/full", policies, "The entire exit policy of onion router"),
  2151. ITEM("exit-policy/ipv4", policies, "IPv4 parts of exit policy"),
  2152. ITEM("exit-policy/ipv6", policies, "IPv6 parts of exit policy"),
  2153. PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
  2154. ITEM("onions/current", onions,
  2155. "Onion services owned by the current control connection."),
  2156. ITEM("onions/detached", onions,
  2157. "Onion services detached from the control connection."),
  2158. { NULL, NULL, NULL, 0 }
  2159. };
  2160. /** Allocate and return a list of recognized GETINFO options. */
  2161. static char *
  2162. list_getinfo_options(void)
  2163. {
  2164. int i;
  2165. smartlist_t *lines = smartlist_new();
  2166. char *ans;
  2167. for (i = 0; getinfo_items[i].varname; ++i) {
  2168. if (!getinfo_items[i].desc)
  2169. continue;
  2170. smartlist_add_asprintf(lines, "%s%s -- %s\n",
  2171. getinfo_items[i].varname,
  2172. getinfo_items[i].is_prefix ? "*" : "",
  2173. getinfo_items[i].desc);
  2174. }
  2175. smartlist_sort_strings(lines);
  2176. ans = smartlist_join_strings(lines, "", 0, NULL);
  2177. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  2178. smartlist_free(lines);
  2179. return ans;
  2180. }
  2181. /** Lookup the 'getinfo' entry <b>question</b>, and return
  2182. * the answer in <b>*answer</b> (or NULL if key not recognized).
  2183. * Return 0 if success or unrecognized, or -1 if recognized but
  2184. * internal error. */
  2185. static int
  2186. handle_getinfo_helper(control_connection_t *control_conn,
  2187. const char *question, char **answer,
  2188. const char **err_out)
  2189. {
  2190. int i;
  2191. *answer = NULL; /* unrecognized key by default */
  2192. for (i = 0; getinfo_items[i].varname; ++i) {
  2193. int match;
  2194. if (getinfo_items[i].is_prefix)
  2195. match = !strcmpstart(question, getinfo_items[i].varname);
  2196. else
  2197. match = !strcmp(question, getinfo_items[i].varname);
  2198. if (match) {
  2199. tor_assert(getinfo_items[i].fn);
  2200. return getinfo_items[i].fn(control_conn, question, answer, err_out);
  2201. }
  2202. }
  2203. return 0; /* unrecognized */
  2204. }
  2205. /** Called when we receive a GETINFO command. Try to fetch all requested
  2206. * information, and reply with information or error message. */
  2207. static int
  2208. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  2209. const char *body)
  2210. {
  2211. smartlist_t *questions = smartlist_new();
  2212. smartlist_t *answers = smartlist_new();
  2213. smartlist_t *unrecognized = smartlist_new();
  2214. char *msg = NULL, *ans = NULL;
  2215. int i;
  2216. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2217. smartlist_split_string(questions, body, " ",
  2218. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2219. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  2220. const char *errmsg = NULL;
  2221. if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
  2222. if (!errmsg)
  2223. errmsg = "Internal error";
  2224. connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
  2225. goto done;
  2226. }
  2227. if (!ans) {
  2228. smartlist_add(unrecognized, (char*)q);
  2229. } else {
  2230. smartlist_add(answers, tor_strdup(q));
  2231. smartlist_add(answers, ans);
  2232. }
  2233. } SMARTLIST_FOREACH_END(q);
  2234. if (smartlist_len(unrecognized)) {
  2235. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  2236. connection_printf_to_buf(conn,
  2237. "552-Unrecognized key \"%s\"\r\n",
  2238. (char*)smartlist_get(unrecognized, i));
  2239. connection_printf_to_buf(conn,
  2240. "552 Unrecognized key \"%s\"\r\n",
  2241. (char*)smartlist_get(unrecognized, i));
  2242. goto done;
  2243. }
  2244. for (i = 0; i < smartlist_len(answers); i += 2) {
  2245. char *k = smartlist_get(answers, i);
  2246. char *v = smartlist_get(answers, i+1);
  2247. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  2248. connection_printf_to_buf(conn, "250-%s=", k);
  2249. connection_write_str_to_buf(v, conn);
  2250. connection_write_str_to_buf("\r\n", conn);
  2251. } else {
  2252. char *esc = NULL;
  2253. size_t esc_len;
  2254. esc_len = write_escaped_data(v, strlen(v), &esc);
  2255. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  2256. connection_write_to_buf(esc, esc_len, TO_CONN(conn));
  2257. tor_free(esc);
  2258. }
  2259. }
  2260. connection_write_str_to_buf("250 OK\r\n", conn);
  2261. done:
  2262. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  2263. smartlist_free(answers);
  2264. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  2265. smartlist_free(questions);
  2266. smartlist_free(unrecognized);
  2267. tor_free(msg);
  2268. return 0;
  2269. }
  2270. /** Given a string, convert it to a circuit purpose. */
  2271. static uint8_t
  2272. circuit_purpose_from_string(const char *string)
  2273. {
  2274. if (!strcasecmpstart(string, "purpose="))
  2275. string += strlen("purpose=");
  2276. if (!strcasecmp(string, "general"))
  2277. return CIRCUIT_PURPOSE_C_GENERAL;
  2278. else if (!strcasecmp(string, "controller"))
  2279. return CIRCUIT_PURPOSE_CONTROLLER;
  2280. else
  2281. return CIRCUIT_PURPOSE_UNKNOWN;
  2282. }
  2283. /** Return a newly allocated smartlist containing the arguments to the command
  2284. * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
  2285. * or if <b>max_args</b> is nonnegative and there are more than
  2286. * <b>max_args</b> arguments, send a 512 error to the controller, using
  2287. * <b>command</b> as the command name in the error message. */
  2288. static smartlist_t *
  2289. getargs_helper(const char *command, control_connection_t *conn,
  2290. const char *body, int min_args, int max_args)
  2291. {
  2292. smartlist_t *args = smartlist_new();
  2293. smartlist_split_string(args, body, " ",
  2294. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2295. if (smartlist_len(args) < min_args) {
  2296. connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
  2297. goto err;
  2298. } else if (max_args >= 0 && smartlist_len(args) > max_args) {
  2299. connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
  2300. goto err;
  2301. }
  2302. return args;
  2303. err:
  2304. SMARTLIST_FOREACH(args, char *, s, tor_free(s));
  2305. smartlist_free(args);
  2306. return NULL;
  2307. }
  2308. /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
  2309. * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
  2310. * such element exists. */
  2311. static const char *
  2312. find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
  2313. {
  2314. int i;
  2315. for (i = start_at; i < smartlist_len(sl); ++i) {
  2316. const char *elt = smartlist_get(sl, i);
  2317. if (!strcasecmpstart(elt, prefix))
  2318. return elt;
  2319. }
  2320. return NULL;
  2321. }
  2322. /** Helper. Return true iff s is an argument that we should treat as a
  2323. * key-value pair. */
  2324. static int
  2325. is_keyval_pair(const char *s)
  2326. {
  2327. /* An argument is a key-value pair if it has an =, and it isn't of the form
  2328. * $fingeprint=name */
  2329. return strchr(s, '=') && s[0] != '$';
  2330. }
  2331. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  2332. * circuit, and report success or failure. */
  2333. static int
  2334. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  2335. const char *body)
  2336. {
  2337. smartlist_t *router_nicknames=NULL, *nodes=NULL;
  2338. origin_circuit_t *circ = NULL;
  2339. int zero_circ;
  2340. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  2341. smartlist_t *args;
  2342. (void) len;
  2343. router_nicknames = smartlist_new();
  2344. args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
  2345. if (!args)
  2346. goto done;
  2347. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  2348. if (zero_circ) {
  2349. const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
  2350. if (purp) {
  2351. intended_purpose = circuit_purpose_from_string(purp);
  2352. if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2353. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2354. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2355. smartlist_free(args);
  2356. goto done;
  2357. }
  2358. }
  2359. if ((smartlist_len(args) == 1) ||
  2360. (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
  2361. // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
  2362. circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
  2363. if (!circ) {
  2364. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2365. } else {
  2366. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2367. (unsigned long)circ->global_identifier);
  2368. }
  2369. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2370. smartlist_free(args);
  2371. goto done;
  2372. }
  2373. // "EXTENDCIRCUIT 0 router1,router2" ||
  2374. // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
  2375. }
  2376. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  2377. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2378. (char*)smartlist_get(args, 0));
  2379. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2380. smartlist_free(args);
  2381. goto done;
  2382. }
  2383. if (smartlist_len(args) < 2) {
  2384. connection_printf_to_buf(conn,
  2385. "512 syntax error: not enough arguments.\r\n");
  2386. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2387. smartlist_free(args);
  2388. goto done;
  2389. }
  2390. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  2391. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2392. smartlist_free(args);
  2393. nodes = smartlist_new();
  2394. SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
  2395. const node_t *node = node_get_by_nickname(n, 1);
  2396. if (!node) {
  2397. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  2398. goto done;
  2399. }
  2400. if (!node_has_descriptor(node)) {
  2401. connection_printf_to_buf(conn, "552 No descriptor for \"%s\"\r\n", n);
  2402. goto done;
  2403. }
  2404. smartlist_add(nodes, (void*)node);
  2405. } SMARTLIST_FOREACH_END(n);
  2406. if (!smartlist_len(nodes)) {
  2407. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  2408. goto done;
  2409. }
  2410. if (zero_circ) {
  2411. /* start a new circuit */
  2412. circ = origin_circuit_init(intended_purpose, 0);
  2413. }
  2414. /* now circ refers to something that is ready to be extended */
  2415. SMARTLIST_FOREACH(nodes, const node_t *, node,
  2416. {
  2417. extend_info_t *info = extend_info_from_node(node, 0);
  2418. tor_assert(info); /* True, since node_has_descriptor(node) == true */
  2419. circuit_append_new_exit(circ, info);
  2420. extend_info_free(info);
  2421. });
  2422. /* now that we've populated the cpath, start extending */
  2423. if (zero_circ) {
  2424. int err_reason = 0;
  2425. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  2426. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2427. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2428. goto done;
  2429. }
  2430. } else {
  2431. if (circ->base_.state == CIRCUIT_STATE_OPEN) {
  2432. int err_reason = 0;
  2433. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2434. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  2435. log_info(LD_CONTROL,
  2436. "send_next_onion_skin failed; circuit marked for closing.");
  2437. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2438. connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
  2439. goto done;
  2440. }
  2441. }
  2442. }
  2443. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2444. (unsigned long)circ->global_identifier);
  2445. if (zero_circ) /* send a 'launched' event, for completeness */
  2446. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  2447. done:
  2448. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  2449. smartlist_free(router_nicknames);
  2450. smartlist_free(nodes);
  2451. return 0;
  2452. }
  2453. /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
  2454. * circuit and it's a valid purpose, change it. */
  2455. static int
  2456. handle_control_setcircuitpurpose(control_connection_t *conn,
  2457. uint32_t len, const char *body)
  2458. {
  2459. origin_circuit_t *circ = NULL;
  2460. uint8_t new_purpose;
  2461. smartlist_t *args;
  2462. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2463. args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
  2464. if (!args)
  2465. goto done;
  2466. if (!(circ = get_circ(smartlist_get(args,0)))) {
  2467. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2468. (char*)smartlist_get(args, 0));
  2469. goto done;
  2470. }
  2471. {
  2472. const char *purp = find_element_starting_with(args,1,"PURPOSE=");
  2473. if (!purp) {
  2474. connection_write_str_to_buf("552 No purpose given\r\n", conn);
  2475. goto done;
  2476. }
  2477. new_purpose = circuit_purpose_from_string(purp);
  2478. if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2479. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2480. goto done;
  2481. }
  2482. }
  2483. circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
  2484. connection_write_str_to_buf("250 OK\r\n", conn);
  2485. done:
  2486. if (args) {
  2487. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2488. smartlist_free(args);
  2489. }
  2490. return 0;
  2491. }
  2492. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  2493. * stream, and report success or failure. */
  2494. static int
  2495. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  2496. const char *body)
  2497. {
  2498. entry_connection_t *ap_conn = NULL;
  2499. origin_circuit_t *circ = NULL;
  2500. int zero_circ;
  2501. smartlist_t *args;
  2502. crypt_path_t *cpath=NULL;
  2503. int hop=0, hop_line_ok=1;
  2504. (void) len;
  2505. args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
  2506. if (!args)
  2507. return 0;
  2508. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  2509. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  2510. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2511. (char*)smartlist_get(args, 0));
  2512. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  2513. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2514. (char*)smartlist_get(args, 1));
  2515. } else if (circ) {
  2516. const char *hopstring = find_element_starting_with(args,2,"HOP=");
  2517. if (hopstring) {
  2518. hopstring += strlen("HOP=");
  2519. hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
  2520. &hop_line_ok, NULL);
  2521. if (!hop_line_ok) { /* broken hop line */
  2522. connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
  2523. }
  2524. }
  2525. }
  2526. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2527. smartlist_free(args);
  2528. if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
  2529. return 0;
  2530. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
  2531. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
  2532. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
  2533. connection_write_str_to_buf(
  2534. "555 Connection is not managed by controller.\r\n",
  2535. conn);
  2536. return 0;
  2537. }
  2538. /* Do we need to detach it first? */
  2539. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
  2540. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2541. circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
  2542. connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
  2543. /* Un-mark it as ending, since we're going to reuse it. */
  2544. edge_conn->edge_has_sent_end = 0;
  2545. edge_conn->end_reason = 0;
  2546. if (tmpcirc)
  2547. circuit_detach_stream(tmpcirc, edge_conn);
  2548. TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  2549. }
  2550. if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
  2551. connection_write_str_to_buf(
  2552. "551 Can't attach stream to non-open origin circuit\r\n",
  2553. conn);
  2554. return 0;
  2555. }
  2556. /* Is this a single hop circuit? */
  2557. if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
  2558. const node_t *node = NULL;
  2559. char *exit_digest = NULL;
  2560. if (circ->build_state &&
  2561. circ->build_state->chosen_exit &&
  2562. !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
  2563. exit_digest = circ->build_state->chosen_exit->identity_digest;
  2564. node = node_get_by_id(exit_digest);
  2565. }
  2566. /* Do both the client and relay allow one-hop exit circuits? */
  2567. if (!node ||
  2568. !node_allows_single_hop_exits(node) ||
  2569. !get_options()->AllowSingleHopCircuits) {
  2570. connection_write_str_to_buf(
  2571. "551 Can't attach stream to this one-hop circuit.\r\n", conn);
  2572. return 0;
  2573. }
  2574. tor_assert(exit_digest);
  2575. ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
  2576. }
  2577. if (circ && hop>0) {
  2578. /* find this hop in the circuit, and set cpath */
  2579. cpath = circuit_get_cpath_hop(circ, hop);
  2580. if (!cpath) {
  2581. connection_printf_to_buf(conn,
  2582. "551 Circuit doesn't have %d hops.\r\n", hop);
  2583. return 0;
  2584. }
  2585. }
  2586. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
  2587. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  2588. return 0;
  2589. }
  2590. send_control_done(conn);
  2591. return 0;
  2592. }
  2593. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  2594. * descriptor, and report success or failure. */
  2595. static int
  2596. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  2597. const char *body)
  2598. {
  2599. char *desc;
  2600. const char *msg=NULL;
  2601. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  2602. int cache = 0; /* eventually, we may switch this to 1 */
  2603. const char *cp = memchr(body, '\n', len);
  2604. smartlist_t *args = smartlist_new();
  2605. tor_assert(cp);
  2606. ++cp;
  2607. char *cmdline = tor_memdup_nulterm(body, cp-body);
  2608. smartlist_split_string(args, cmdline, " ",
  2609. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2610. SMARTLIST_FOREACH_BEGIN(args, char *, option) {
  2611. if (!strcasecmpstart(option, "purpose=")) {
  2612. option += strlen("purpose=");
  2613. purpose = router_purpose_from_string(option);
  2614. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  2615. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  2616. option);
  2617. goto done;
  2618. }
  2619. } else if (!strcasecmpstart(option, "cache=")) {
  2620. option += strlen("cache=");
  2621. if (!strcasecmp(option, "no"))
  2622. cache = 0;
  2623. else if (!strcasecmp(option, "yes"))
  2624. cache = 1;
  2625. else {
  2626. connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
  2627. option);
  2628. goto done;
  2629. }
  2630. } else { /* unrecognized argument? */
  2631. connection_printf_to_buf(conn,
  2632. "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
  2633. goto done;
  2634. }
  2635. } SMARTLIST_FOREACH_END(option);
  2636. read_escaped_data(cp, len-(cp-body), &desc);
  2637. switch (router_load_single_router(desc, purpose, cache, &msg)) {
  2638. case -1:
  2639. if (!msg) msg = "Could not parse descriptor";
  2640. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  2641. break;
  2642. case 0:
  2643. if (!msg) msg = "Descriptor not added";
  2644. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  2645. break;
  2646. case 1:
  2647. send_control_done(conn);
  2648. break;
  2649. }
  2650. tor_free(desc);
  2651. done:
  2652. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  2653. smartlist_free(args);
  2654. tor_free(cmdline);
  2655. return 0;
  2656. }
  2657. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  2658. * address of the named AP stream, and report success or failure. */
  2659. static int
  2660. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  2661. const char *body)
  2662. {
  2663. entry_connection_t *ap_conn = NULL;
  2664. char *new_addr = NULL;
  2665. uint16_t new_port = 0;
  2666. smartlist_t *args;
  2667. (void) len;
  2668. args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
  2669. if (!args)
  2670. return 0;
  2671. if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  2672. || !ap_conn->socks_request) {
  2673. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2674. (char*)smartlist_get(args, 0));
  2675. } else {
  2676. int ok = 1;
  2677. if (smartlist_len(args) > 2) { /* they included a port too */
  2678. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  2679. 10, 1, 65535, &ok, NULL);
  2680. }
  2681. if (!ok) {
  2682. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  2683. (char*)smartlist_get(args, 2));
  2684. } else {
  2685. new_addr = tor_strdup(smartlist_get(args, 1));
  2686. }
  2687. }
  2688. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2689. smartlist_free(args);
  2690. if (!new_addr)
  2691. return 0;
  2692. strlcpy(ap_conn->socks_request->address, new_addr,
  2693. sizeof(ap_conn->socks_request->address));
  2694. if (new_port)
  2695. ap_conn->socks_request->port = new_port;
  2696. tor_free(new_addr);
  2697. send_control_done(conn);
  2698. return 0;
  2699. }
  2700. /** Called when we get a CLOSESTREAM command; try to close the named stream
  2701. * and report success or failure. */
  2702. static int
  2703. handle_control_closestream(control_connection_t *conn, uint32_t len,
  2704. const char *body)
  2705. {
  2706. entry_connection_t *ap_conn=NULL;
  2707. uint8_t reason=0;
  2708. smartlist_t *args;
  2709. int ok;
  2710. (void) len;
  2711. args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
  2712. if (!args)
  2713. return 0;
  2714. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  2715. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2716. (char*)smartlist_get(args, 0));
  2717. else {
  2718. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  2719. &ok, NULL);
  2720. if (!ok) {
  2721. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  2722. (char*)smartlist_get(args, 1));
  2723. ap_conn = NULL;
  2724. }
  2725. }
  2726. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2727. smartlist_free(args);
  2728. if (!ap_conn)
  2729. return 0;
  2730. connection_mark_unattached_ap(ap_conn, reason);
  2731. send_control_done(conn);
  2732. return 0;
  2733. }
  2734. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  2735. * and report success or failure. */
  2736. static int
  2737. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  2738. const char *body)
  2739. {
  2740. origin_circuit_t *circ = NULL;
  2741. int safe = 0;
  2742. smartlist_t *args;
  2743. (void) len;
  2744. args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
  2745. if (!args)
  2746. return 0;
  2747. if (!(circ=get_circ(smartlist_get(args, 0))))
  2748. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2749. (char*)smartlist_get(args, 0));
  2750. else {
  2751. int i;
  2752. for (i=1; i < smartlist_len(args); ++i) {
  2753. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  2754. safe = 1;
  2755. else
  2756. log_info(LD_CONTROL, "Skipping unknown option %s",
  2757. (char*)smartlist_get(args,i));
  2758. }
  2759. }
  2760. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2761. smartlist_free(args);
  2762. if (!circ)
  2763. return 0;
  2764. if (!safe || !circ->p_streams) {
  2765. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
  2766. }
  2767. send_control_done(conn);
  2768. return 0;
  2769. }
  2770. /** Called when we get a RESOLVE command: start trying to resolve
  2771. * the listed addresses. */
  2772. static int
  2773. handle_control_resolve(control_connection_t *conn, uint32_t len,
  2774. const char *body)
  2775. {
  2776. smartlist_t *args, *failed;
  2777. int is_reverse = 0;
  2778. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2779. if (!(conn->event_mask & (((event_mask_t)1)<<EVENT_ADDRMAP))) {
  2780. log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
  2781. "isn't listening for ADDRMAP events. It probably won't see "
  2782. "the answer.");
  2783. }
  2784. args = smartlist_new();
  2785. smartlist_split_string(args, body, " ",
  2786. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2787. {
  2788. const char *modearg = find_element_starting_with(args, 0, "mode=");
  2789. if (modearg && !strcasecmp(modearg, "mode=reverse"))
  2790. is_reverse = 1;
  2791. }
  2792. failed = smartlist_new();
  2793. SMARTLIST_FOREACH(args, const char *, arg, {
  2794. if (!is_keyval_pair(arg)) {
  2795. if (dnsserv_launch_request(arg, is_reverse, conn)<0)
  2796. smartlist_add(failed, (char*)arg);
  2797. }
  2798. });
  2799. send_control_done(conn);
  2800. SMARTLIST_FOREACH(failed, const char *, arg, {
  2801. control_event_address_mapped(arg, arg, time(NULL),
  2802. "internal", 0);
  2803. });
  2804. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2805. smartlist_free(args);
  2806. smartlist_free(failed);
  2807. return 0;
  2808. }
  2809. /** Called when we get a PROTOCOLINFO command: send back a reply. */
  2810. static int
  2811. handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
  2812. const char *body)
  2813. {
  2814. const char *bad_arg = NULL;
  2815. smartlist_t *args;
  2816. (void)len;
  2817. conn->have_sent_protocolinfo = 1;
  2818. args = smartlist_new();
  2819. smartlist_split_string(args, body, " ",
  2820. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2821. SMARTLIST_FOREACH(args, const char *, arg, {
  2822. int ok;
  2823. tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
  2824. if (!ok) {
  2825. bad_arg = arg;
  2826. break;
  2827. }
  2828. });
  2829. if (bad_arg) {
  2830. connection_printf_to_buf(conn, "513 No such version %s\r\n",
  2831. escaped(bad_arg));
  2832. /* Don't tolerate bad arguments when not authenticated. */
  2833. if (!STATE_IS_OPEN(TO_CONN(conn)->state))
  2834. connection_mark_for_close(TO_CONN(conn));
  2835. goto done;
  2836. } else {
  2837. const or_options_t *options = get_options();
  2838. int cookies = options->CookieAuthentication;
  2839. char *cfile = get_controller_cookie_file_name();
  2840. char *abs_cfile;
  2841. char *esc_cfile;
  2842. char *methods;
  2843. abs_cfile = make_path_absolute(cfile);
  2844. esc_cfile = esc_for_log(abs_cfile);
  2845. {
  2846. int passwd = (options->HashedControlPassword != NULL ||
  2847. options->HashedControlSessionPassword != NULL);
  2848. smartlist_t *mlist = smartlist_new();
  2849. if (cookies) {
  2850. smartlist_add(mlist, (char*)"COOKIE");
  2851. smartlist_add(mlist, (char*)"SAFECOOKIE");
  2852. }
  2853. if (passwd)
  2854. smartlist_add(mlist, (char*)"HASHEDPASSWORD");
  2855. if (!cookies && !passwd)
  2856. smartlist_add(mlist, (char*)"NULL");
  2857. methods = smartlist_join_strings(mlist, ",", 0, NULL);
  2858. smartlist_free(mlist);
  2859. }
  2860. connection_printf_to_buf(conn,
  2861. "250-PROTOCOLINFO 1\r\n"
  2862. "250-AUTH METHODS=%s%s%s\r\n"
  2863. "250-VERSION Tor=%s\r\n"
  2864. "250 OK\r\n",
  2865. methods,
  2866. cookies?" COOKIEFILE=":"",
  2867. cookies?esc_cfile:"",
  2868. escaped(VERSION));
  2869. tor_free(methods);
  2870. tor_free(cfile);
  2871. tor_free(abs_cfile);
  2872. tor_free(esc_cfile);
  2873. }
  2874. done:
  2875. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2876. smartlist_free(args);
  2877. return 0;
  2878. }
  2879. /** Called when we get an AUTHCHALLENGE command. */
  2880. static int
  2881. handle_control_authchallenge(control_connection_t *conn, uint32_t len,
  2882. const char *body)
  2883. {
  2884. const char *cp = body;
  2885. char *client_nonce;
  2886. size_t client_nonce_len;
  2887. char server_hash[DIGEST256_LEN];
  2888. char server_hash_encoded[HEX_DIGEST256_LEN+1];
  2889. char server_nonce[SAFECOOKIE_SERVER_NONCE_LEN];
  2890. char server_nonce_encoded[(2*SAFECOOKIE_SERVER_NONCE_LEN) + 1];
  2891. cp += strspn(cp, " \t\n\r");
  2892. if (!strcasecmpstart(cp, "SAFECOOKIE")) {
  2893. cp += strlen("SAFECOOKIE");
  2894. } else {
  2895. connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
  2896. "authentication\r\n", conn);
  2897. connection_mark_for_close(TO_CONN(conn));
  2898. return -1;
  2899. }
  2900. if (!authentication_cookie_is_set) {
  2901. connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
  2902. conn);
  2903. connection_mark_for_close(TO_CONN(conn));
  2904. return -1;
  2905. }
  2906. cp += strspn(cp, " \t\n\r");
  2907. if (*cp == '"') {
  2908. const char *newcp =
  2909. decode_escaped_string(cp, len - (cp - body),
  2910. &client_nonce, &client_nonce_len);
  2911. if (newcp == NULL) {
  2912. connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
  2913. conn);
  2914. connection_mark_for_close(TO_CONN(conn));
  2915. return -1;
  2916. }
  2917. cp = newcp;
  2918. } else {
  2919. size_t client_nonce_encoded_len = strspn(cp, "0123456789ABCDEFabcdef");
  2920. client_nonce_len = client_nonce_encoded_len / 2;
  2921. client_nonce = tor_malloc_zero(client_nonce_len);
  2922. if (base16_decode(client_nonce, client_nonce_len,
  2923. cp, client_nonce_encoded_len) < 0) {
  2924. connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
  2925. conn);
  2926. connection_mark_for_close(TO_CONN(conn));
  2927. tor_free(client_nonce);
  2928. return -1;
  2929. }
  2930. cp += client_nonce_encoded_len;
  2931. }
  2932. cp += strspn(cp, " \t\n\r");
  2933. if (*cp != '\0' ||
  2934. cp != body + len) {
  2935. connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
  2936. conn);
  2937. connection_mark_for_close(TO_CONN(conn));
  2938. tor_free(client_nonce);
  2939. return -1;
  2940. }
  2941. const int fail = crypto_rand(server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
  2942. tor_assert(!fail);
  2943. /* Now compute and send the server-to-controller response, and the
  2944. * server's nonce. */
  2945. tor_assert(authentication_cookie != NULL);
  2946. {
  2947. size_t tmp_len = (AUTHENTICATION_COOKIE_LEN +
  2948. client_nonce_len +
  2949. SAFECOOKIE_SERVER_NONCE_LEN);
  2950. char *tmp = tor_malloc_zero(tmp_len);
  2951. char *client_hash = tor_malloc_zero(DIGEST256_LEN);
  2952. memcpy(tmp, authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  2953. memcpy(tmp + AUTHENTICATION_COOKIE_LEN, client_nonce, client_nonce_len);
  2954. memcpy(tmp + AUTHENTICATION_COOKIE_LEN + client_nonce_len,
  2955. server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
  2956. crypto_hmac_sha256(server_hash,
  2957. SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT,
  2958. strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT),
  2959. tmp,
  2960. tmp_len);
  2961. crypto_hmac_sha256(client_hash,
  2962. SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT,
  2963. strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT),
  2964. tmp,
  2965. tmp_len);
  2966. conn->safecookie_client_hash = client_hash;
  2967. tor_free(tmp);
  2968. }
  2969. base16_encode(server_hash_encoded, sizeof(server_hash_encoded),
  2970. server_hash, sizeof(server_hash));
  2971. base16_encode(server_nonce_encoded, sizeof(server_nonce_encoded),
  2972. server_nonce, sizeof(server_nonce));
  2973. connection_printf_to_buf(conn,
  2974. "250 AUTHCHALLENGE SERVERHASH=%s "
  2975. "SERVERNONCE=%s\r\n",
  2976. server_hash_encoded,
  2977. server_nonce_encoded);
  2978. tor_free(client_nonce);
  2979. return 0;
  2980. }
  2981. /** Called when we get a USEFEATURE command: parse the feature list, and
  2982. * set up the control_connection's options properly. */
  2983. static int
  2984. handle_control_usefeature(control_connection_t *conn,
  2985. uint32_t len,
  2986. const char *body)
  2987. {
  2988. smartlist_t *args;
  2989. int bad = 0;
  2990. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2991. args = smartlist_new();
  2992. smartlist_split_string(args, body, " ",
  2993. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2994. SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
  2995. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  2996. ;
  2997. else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
  2998. ;
  2999. else {
  3000. connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
  3001. arg);
  3002. bad = 1;
  3003. break;
  3004. }
  3005. } SMARTLIST_FOREACH_END(arg);
  3006. if (!bad) {
  3007. send_control_done(conn);
  3008. }
  3009. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3010. smartlist_free(args);
  3011. return 0;
  3012. }
  3013. /** Implementation for the DROPGUARDS command. */
  3014. static int
  3015. handle_control_dropguards(control_connection_t *conn,
  3016. uint32_t len,
  3017. const char *body)
  3018. {
  3019. smartlist_t *args;
  3020. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3021. args = smartlist_new();
  3022. smartlist_split_string(args, body, " ",
  3023. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3024. if (smartlist_len(args)) {
  3025. connection_printf_to_buf(conn, "512 Too many arguments to DROPGUARDS\r\n");
  3026. } else {
  3027. remove_all_entry_guards();
  3028. send_control_done(conn);
  3029. }
  3030. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3031. smartlist_free(args);
  3032. return 0;
  3033. }
  3034. /** Implementation for the HSFETCH command. */
  3035. static int
  3036. handle_control_hsfetch(control_connection_t *conn, uint32_t len,
  3037. const char *body)
  3038. {
  3039. int i;
  3040. char digest[DIGEST_LEN], *hsaddress = NULL, *arg1 = NULL, *desc_id = NULL;
  3041. smartlist_t *args = NULL, *hsdirs = NULL;
  3042. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3043. static const char *hsfetch_command = "HSFETCH";
  3044. static const char *v2_str = "v2-";
  3045. const size_t v2_str_len = strlen(v2_str);
  3046. rend_data_t *rend_query = NULL;
  3047. /* Make sure we have at least one argument, the HSAddress. */
  3048. args = getargs_helper(hsfetch_command, conn, body, 1, -1);
  3049. if (!args) {
  3050. goto exit;
  3051. }
  3052. /* Extract the first argument (either HSAddress or DescID). */
  3053. arg1 = smartlist_get(args, 0);
  3054. /* Test if it's an HS address without the .onion part. */
  3055. if (rend_valid_service_id(arg1)) {
  3056. hsaddress = arg1;
  3057. } else if (strcmpstart(arg1, v2_str) == 0 &&
  3058. rend_valid_descriptor_id(arg1 + v2_str_len) &&
  3059. base32_decode(digest, sizeof(digest), arg1 + v2_str_len,
  3060. REND_DESC_ID_V2_LEN_BASE32) == 0) {
  3061. /* We have a well formed version 2 descriptor ID. Keep the decoded value
  3062. * of the id. */
  3063. desc_id = digest;
  3064. } else {
  3065. connection_printf_to_buf(conn, "513 Unrecognized \"%s\"\r\n",
  3066. arg1);
  3067. goto done;
  3068. }
  3069. static const char *opt_server = "SERVER=";
  3070. /* Skip first argument because it's the HSAddress or DescID. */
  3071. for (i = 1; i < smartlist_len(args); ++i) {
  3072. const char *arg = smartlist_get(args, i);
  3073. const node_t *node;
  3074. if (!strcasecmpstart(arg, opt_server)) {
  3075. const char *server;
  3076. server = arg + strlen(opt_server);
  3077. node = node_get_by_hex_id(server);
  3078. if (!node) {
  3079. connection_printf_to_buf(conn, "552 Server \"%s\" not found\r\n",
  3080. server);
  3081. goto done;
  3082. }
  3083. if (!hsdirs) {
  3084. /* Stores routerstatus_t object for each specified server. */
  3085. hsdirs = smartlist_new();
  3086. }
  3087. /* Valid server, add it to our local list. */
  3088. smartlist_add(hsdirs, node->rs);
  3089. } else {
  3090. connection_printf_to_buf(conn, "513 Unexpected argument \"%s\"\r\n",
  3091. arg);
  3092. goto done;
  3093. }
  3094. }
  3095. rend_query = tor_malloc_zero(sizeof(*rend_query));
  3096. if (hsaddress) {
  3097. strncpy(rend_query->onion_address, hsaddress,
  3098. sizeof(rend_query->onion_address));
  3099. } else if (desc_id) {
  3100. /* Using a descriptor ID, we force the user to provide at least one
  3101. * hsdir server using the SERVER= option. */
  3102. if (!hsdirs || !smartlist_len(hsdirs)) {
  3103. connection_printf_to_buf(conn, "512 %s option is required\r\n",
  3104. opt_server);
  3105. goto done;
  3106. }
  3107. memcpy(rend_query->descriptor_id, desc_id,
  3108. sizeof(rend_query->descriptor_id));
  3109. } else {
  3110. /* We can't get in here because of the first argument check. */
  3111. tor_assert(0);
  3112. }
  3113. /* We are about to trigger HSDir fetch so send the OK now because after
  3114. * that 650 event(s) are possible so better to have the 250 OK before them
  3115. * to avoid out of order replies. */
  3116. send_control_done(conn);
  3117. /* Trigger the fetch using the built rend query and possibly a list of HS
  3118. * directory to use. This function ignores the client cache thus this will
  3119. * always send a fetch command. */
  3120. rend_client_fetch_v2_desc(rend_query, hsdirs);
  3121. done:
  3122. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3123. smartlist_free(args);
  3124. /* Contains data pointer that we don't own thus no cleanup. */
  3125. smartlist_free(hsdirs);
  3126. tor_free(rend_query);
  3127. exit:
  3128. return 0;
  3129. }
  3130. /** Called when we get a ADD_ONION command; parse the body, and set up
  3131. * the new ephemeral Onion Service. */
  3132. static int
  3133. handle_control_add_onion(control_connection_t *conn,
  3134. uint32_t len,
  3135. const char *body)
  3136. {
  3137. smartlist_t *args;
  3138. size_t arg_len;
  3139. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3140. args = getargs_helper("ADD_ONION", conn, body, 2, -1);
  3141. if (!args)
  3142. return 0;
  3143. arg_len = smartlist_len(args);
  3144. /* Parse all of the arguments that do not involve handling cryptographic
  3145. * material first, since there's no reason to touch that at all if any of
  3146. * the other arguments are malformed.
  3147. */
  3148. smartlist_t *port_cfgs = smartlist_new();
  3149. int discard_pk = 0;
  3150. int detach = 0;
  3151. for (size_t i = 1; i < arg_len; i++) {
  3152. static const char *port_prefix = "Port=";
  3153. static const char *flags_prefix = "Flags=";
  3154. const char *arg = smartlist_get(args, i);
  3155. if (!strcasecmpstart(arg, port_prefix)) {
  3156. /* "Port=VIRTPORT[,TARGET]". */
  3157. const char *port_str = arg + strlen(port_prefix);
  3158. rend_service_port_config_t *cfg =
  3159. rend_service_parse_port_config(port_str, ",", NULL);
  3160. if (!cfg) {
  3161. connection_printf_to_buf(conn, "512 Invalid VIRTPORT/TARGET\r\n");
  3162. goto out;
  3163. }
  3164. smartlist_add(port_cfgs, cfg);
  3165. } else if (!strcasecmpstart(arg, flags_prefix)) {
  3166. /* "Flags=Flag[,Flag]", where Flag can be:
  3167. * * 'DiscardPK' - If tor generates the keypair, do not include it in
  3168. * the response.
  3169. * * 'Detach' - Do not tie this onion service to any particular control
  3170. * connection.
  3171. */
  3172. static const char *discard_flag = "DiscardPK";
  3173. static const char *detach_flag = "Detach";
  3174. smartlist_t *flags = smartlist_new();
  3175. int bad = 0;
  3176. smartlist_split_string(flags, arg + strlen(flags_prefix), ",",
  3177. SPLIT_IGNORE_BLANK, 0);
  3178. if (smartlist_len(flags) < 1) {
  3179. connection_printf_to_buf(conn, "512 Invalid 'Flags' argument\r\n");
  3180. bad = 1;
  3181. }
  3182. SMARTLIST_FOREACH_BEGIN(flags, const char *, flag)
  3183. {
  3184. if (!strcasecmp(flag, discard_flag)) {
  3185. discard_pk = 1;
  3186. } else if (!strcasecmp(flag, detach_flag)) {
  3187. detach = 1;
  3188. } else {
  3189. connection_printf_to_buf(conn,
  3190. "512 Invalid 'Flags' argument: %s\r\n",
  3191. escaped(flag));
  3192. bad = 1;
  3193. break;
  3194. }
  3195. } SMARTLIST_FOREACH_END(flag);
  3196. SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
  3197. smartlist_free(flags);
  3198. if (bad)
  3199. goto out;
  3200. } else {
  3201. connection_printf_to_buf(conn, "513 Invalid argument\r\n");
  3202. goto out;
  3203. }
  3204. }
  3205. if (smartlist_len(port_cfgs) == 0) {
  3206. connection_printf_to_buf(conn, "512 Missing 'Port' argument\r\n");
  3207. goto out;
  3208. }
  3209. /* Parse the "keytype:keyblob" argument. */
  3210. crypto_pk_t *pk = NULL;
  3211. const char *key_new_alg = NULL;
  3212. char *key_new_blob = NULL;
  3213. char *err_msg = NULL;
  3214. pk = add_onion_helper_keyarg(smartlist_get(args, 0), discard_pk,
  3215. &key_new_alg, &key_new_blob,
  3216. &err_msg);
  3217. if (!pk) {
  3218. if (err_msg) {
  3219. connection_write_str_to_buf(err_msg, conn);
  3220. tor_free(err_msg);
  3221. }
  3222. goto out;
  3223. }
  3224. tor_assert(!err_msg);
  3225. /* Create the HS, using private key pk, and port config port_cfg.
  3226. * rend_service_add_ephemeral() will take ownership of pk and port_cfg,
  3227. * regardless of success/failure.
  3228. */
  3229. char *service_id = NULL;
  3230. int ret = rend_service_add_ephemeral(pk, port_cfgs, &service_id);
  3231. port_cfgs = NULL; /* port_cfgs is now owned by the rendservice code. */
  3232. switch (ret) {
  3233. case RSAE_OKAY:
  3234. {
  3235. char *buf = NULL;
  3236. tor_assert(service_id);
  3237. if (key_new_alg) {
  3238. tor_assert(key_new_blob);
  3239. tor_asprintf(&buf,
  3240. "250-ServiceID=%s\r\n"
  3241. "250-PrivateKey=%s:%s\r\n"
  3242. "250 OK\r\n",
  3243. service_id,
  3244. key_new_alg,
  3245. key_new_blob);
  3246. } else {
  3247. tor_asprintf(&buf,
  3248. "250-ServiceID=%s\r\n"
  3249. "250 OK\r\n",
  3250. service_id);
  3251. }
  3252. if (detach) {
  3253. if (!detached_onion_services)
  3254. detached_onion_services = smartlist_new();
  3255. smartlist_add(detached_onion_services, service_id);
  3256. } else {
  3257. if (!conn->ephemeral_onion_services)
  3258. conn->ephemeral_onion_services = smartlist_new();
  3259. smartlist_add(conn->ephemeral_onion_services, service_id);
  3260. }
  3261. connection_write_str_to_buf(buf, conn);
  3262. memwipe(buf, 0, strlen(buf));
  3263. tor_free(buf);
  3264. break;
  3265. }
  3266. case RSAE_BADPRIVKEY:
  3267. connection_printf_to_buf(conn, "551 Failed to generate onion address\r\n");
  3268. break;
  3269. case RSAE_ADDREXISTS:
  3270. connection_printf_to_buf(conn, "550 Onion address collision\r\n");
  3271. break;
  3272. case RSAE_BADVIRTPORT:
  3273. connection_printf_to_buf(conn, "512 Invalid VIRTPORT/TARGET\r\n");
  3274. break;
  3275. case RSAE_INTERNAL: /* FALLSTHROUGH */
  3276. default:
  3277. connection_printf_to_buf(conn, "551 Failed to add Onion Service\r\n");
  3278. }
  3279. if (key_new_blob) {
  3280. memwipe(key_new_blob, 0, strlen(key_new_blob));
  3281. tor_free(key_new_blob);
  3282. }
  3283. out:
  3284. if (port_cfgs) {
  3285. SMARTLIST_FOREACH(port_cfgs, rend_service_port_config_t*, p,
  3286. rend_service_port_config_free(p));
  3287. smartlist_free(port_cfgs);
  3288. }
  3289. SMARTLIST_FOREACH(args, char *, cp, {
  3290. memwipe(cp, 0, strlen(cp));
  3291. tor_free(cp);
  3292. });
  3293. smartlist_free(args);
  3294. return 0;
  3295. }
  3296. /** Helper function to handle parsing the KeyType:KeyBlob argument to the
  3297. * ADD_ONION command. Return a new crypto_pk_t and if a new key was generated
  3298. * and the private key not discarded, the algorithm and serialized private key,
  3299. * or NULL and an optional control protocol error message on failure. The
  3300. * caller is responsible for freeing the returned key_new_blob and err_msg.
  3301. *
  3302. * Note: The error messages returned are deliberately vague to avoid echoing
  3303. * key material.
  3304. */
  3305. STATIC crypto_pk_t *
  3306. add_onion_helper_keyarg(const char *arg, int discard_pk,
  3307. const char **key_new_alg_out, char **key_new_blob_out,
  3308. char **err_msg_out)
  3309. {
  3310. smartlist_t *key_args = smartlist_new();
  3311. crypto_pk_t *pk = NULL;
  3312. const char *key_new_alg = NULL;
  3313. char *key_new_blob = NULL;
  3314. char *err_msg = NULL;
  3315. int ok = 0;
  3316. smartlist_split_string(key_args, arg, ":", SPLIT_IGNORE_BLANK, 0);
  3317. if (smartlist_len(key_args) != 2) {
  3318. err_msg = tor_strdup("512 Invalid key type/blob\r\n");
  3319. goto err;
  3320. }
  3321. /* The format is "KeyType:KeyBlob". */
  3322. static const char *key_type_new = "NEW";
  3323. static const char *key_type_best = "BEST";
  3324. static const char *key_type_rsa1024 = "RSA1024";
  3325. const char *key_type = smartlist_get(key_args, 0);
  3326. const char *key_blob = smartlist_get(key_args, 1);
  3327. if (!strcasecmp(key_type_rsa1024, key_type)) {
  3328. /* "RSA:<Base64 Blob>" - Loading a pre-existing RSA1024 key. */
  3329. pk = crypto_pk_base64_decode(key_blob, strlen(key_blob));
  3330. if (!pk) {
  3331. err_msg = tor_strdup("512 Failed to decode RSA key\r\n");
  3332. goto err;
  3333. }
  3334. if (crypto_pk_num_bits(pk) != PK_BYTES*8) {
  3335. err_msg = tor_strdup("512 Invalid RSA key size\r\n");
  3336. goto err;
  3337. }
  3338. } else if (!strcasecmp(key_type_new, key_type)) {
  3339. /* "NEW:<Algorithm>" - Generating a new key, blob as algorithm. */
  3340. if (!strcasecmp(key_type_rsa1024, key_blob) ||
  3341. !strcasecmp(key_type_best, key_blob)) {
  3342. /* "RSA1024", RSA 1024 bit, also currently "BEST" by default. */
  3343. pk = crypto_pk_new();
  3344. if (crypto_pk_generate_key(pk)) {
  3345. tor_asprintf(&err_msg, "551 Failed to generate %s key\r\n",
  3346. key_type_rsa1024);
  3347. goto err;
  3348. }
  3349. if (!discard_pk) {
  3350. if (crypto_pk_base64_encode(pk, &key_new_blob)) {
  3351. tor_asprintf(&err_msg, "551 Failed to encode %s key\r\n",
  3352. key_type_rsa1024);
  3353. goto err;
  3354. }
  3355. key_new_alg = key_type_rsa1024;
  3356. }
  3357. } else {
  3358. err_msg = tor_strdup("513 Invalid key type\r\n");
  3359. goto err;
  3360. }
  3361. } else {
  3362. err_msg = tor_strdup("513 Invalid key type\r\n");
  3363. goto err;
  3364. }
  3365. /* Succeded in loading or generating a private key. */
  3366. tor_assert(pk);
  3367. ok = 1;
  3368. err:
  3369. SMARTLIST_FOREACH(key_args, char *, cp, {
  3370. memwipe(cp, 0, strlen(cp));
  3371. tor_free(cp);
  3372. });
  3373. if (!ok) {
  3374. crypto_pk_free(pk);
  3375. pk = NULL;
  3376. }
  3377. if (err_msg_out) *err_msg_out = err_msg;
  3378. *key_new_alg_out = key_new_alg;
  3379. *key_new_blob_out = key_new_blob;
  3380. return pk;
  3381. }
  3382. /** Called when we get a DEL_ONION command; parse the body, and remove
  3383. * the existing ephemeral Onion Service. */
  3384. static int
  3385. handle_control_del_onion(control_connection_t *conn,
  3386. uint32_t len,
  3387. const char *body)
  3388. {
  3389. smartlist_t *args;
  3390. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3391. args = getargs_helper("DEL_ONION", conn, body, 1, 1);
  3392. if (!args)
  3393. return 0;
  3394. const char *service_id = smartlist_get(args, 0);
  3395. if (!rend_valid_service_id(service_id)) {
  3396. connection_printf_to_buf(conn, "512 Malformed Onion Service id\r\n");
  3397. goto out;
  3398. }
  3399. /* Determine if the onion service belongs to this particular control
  3400. * connection, or if it is in the global list of detached services. If it
  3401. * is in neither, either the service ID is invalid in some way, or it
  3402. * explicitly belongs to a different control connection, and an error
  3403. * should be returned.
  3404. */
  3405. smartlist_t *services[2] = {
  3406. conn->ephemeral_onion_services,
  3407. detached_onion_services
  3408. };
  3409. smartlist_t *onion_services = NULL;
  3410. int idx = -1;
  3411. for (size_t i = 0; i < ARRAY_LENGTH(services); i++) {
  3412. idx = smartlist_string_pos(services[i], service_id);
  3413. if (idx != -1) {
  3414. onion_services = services[i];
  3415. break;
  3416. }
  3417. }
  3418. if (onion_services == NULL) {
  3419. connection_printf_to_buf(conn, "552 Unknown Onion Service id\r\n");
  3420. } else {
  3421. int ret = rend_service_del_ephemeral(service_id);
  3422. if (ret) {
  3423. /* This should *NEVER* fail, since the service is on either the
  3424. * per-control connection list, or the global one.
  3425. */
  3426. log_warn(LD_BUG, "Failed to remove Onion Service %s.",
  3427. escaped(service_id));
  3428. tor_fragile_assert();
  3429. }
  3430. /* Remove/scrub the service_id from the appropriate list. */
  3431. char *cp = smartlist_get(onion_services, idx);
  3432. smartlist_del(onion_services, idx);
  3433. memwipe(cp, 0, strlen(cp));
  3434. tor_free(cp);
  3435. send_control_done(conn);
  3436. }
  3437. out:
  3438. SMARTLIST_FOREACH(args, char *, cp, {
  3439. memwipe(cp, 0, strlen(cp));
  3440. tor_free(cp);
  3441. });
  3442. smartlist_free(args);
  3443. return 0;
  3444. }
  3445. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  3446. int
  3447. connection_control_finished_flushing(control_connection_t *conn)
  3448. {
  3449. tor_assert(conn);
  3450. return 0;
  3451. }
  3452. /** Called when <b>conn</b> has gotten its socket closed. */
  3453. int
  3454. connection_control_reached_eof(control_connection_t *conn)
  3455. {
  3456. tor_assert(conn);
  3457. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  3458. connection_mark_for_close(TO_CONN(conn));
  3459. return 0;
  3460. }
  3461. static void lost_owning_controller(const char *owner_type,
  3462. const char *loss_manner)
  3463. ATTR_NORETURN;
  3464. /** Shut down this Tor instance in the same way that SIGINT would, but
  3465. * with a log message appropriate for the loss of an owning controller. */
  3466. static void
  3467. lost_owning_controller(const char *owner_type, const char *loss_manner)
  3468. {
  3469. log_notice(LD_CONTROL, "Owning controller %s has %s -- exiting now.",
  3470. owner_type, loss_manner);
  3471. /* XXXX Perhaps this chunk of code should be a separate function,
  3472. * called here and by process_signal(SIGINT). */
  3473. tor_cleanup();
  3474. exit(0);
  3475. }
  3476. /** Called when <b>conn</b> is being freed. */
  3477. void
  3478. connection_control_closed(control_connection_t *conn)
  3479. {
  3480. tor_assert(conn);
  3481. conn->event_mask = 0;
  3482. control_update_global_event_mask();
  3483. /* Close all ephemeral Onion Services if any.
  3484. * The list and it's contents are scrubbed/freed in connection_free_.
  3485. */
  3486. if (conn->ephemeral_onion_services) {
  3487. SMARTLIST_FOREACH(conn->ephemeral_onion_services, char *, cp, {
  3488. rend_service_del_ephemeral(cp);
  3489. });
  3490. }
  3491. if (conn->is_owning_control_connection) {
  3492. lost_owning_controller("connection", "closed");
  3493. }
  3494. }
  3495. /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
  3496. * stage of the protocol. */
  3497. static int
  3498. is_valid_initial_command(control_connection_t *conn, const char *cmd)
  3499. {
  3500. if (conn->base_.state == CONTROL_CONN_STATE_OPEN)
  3501. return 1;
  3502. if (!strcasecmp(cmd, "PROTOCOLINFO"))
  3503. return (!conn->have_sent_protocolinfo &&
  3504. conn->safecookie_client_hash == NULL);
  3505. if (!strcasecmp(cmd, "AUTHCHALLENGE"))
  3506. return (conn->safecookie_client_hash == NULL);
  3507. if (!strcasecmp(cmd, "AUTHENTICATE") ||
  3508. !strcasecmp(cmd, "QUIT"))
  3509. return 1;
  3510. return 0;
  3511. }
  3512. /** Do not accept any control command of more than 1MB in length. Anything
  3513. * that needs to be anywhere near this long probably means that one of our
  3514. * interfaces is broken. */
  3515. #define MAX_COMMAND_LINE_LENGTH (1024*1024)
  3516. /** Wrapper around peek_(evbuffer|buf)_has_control0 command: presents the same
  3517. * interface as those underlying functions, but takes a connection_t intead of
  3518. * an evbuffer or a buf_t.
  3519. */
  3520. static int
  3521. peek_connection_has_control0_command(connection_t *conn)
  3522. {
  3523. IF_HAS_BUFFEREVENT(conn, {
  3524. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  3525. return peek_evbuffer_has_control0_command(input);
  3526. }) ELSE_IF_NO_BUFFEREVENT {
  3527. return peek_buf_has_control0_command(conn->inbuf);
  3528. }
  3529. }
  3530. /** Called when data has arrived on a v1 control connection: Try to fetch
  3531. * commands from conn->inbuf, and execute them.
  3532. */
  3533. int
  3534. connection_control_process_inbuf(control_connection_t *conn)
  3535. {
  3536. size_t data_len;
  3537. uint32_t cmd_data_len;
  3538. int cmd_len;
  3539. char *args;
  3540. tor_assert(conn);
  3541. tor_assert(conn->base_.state == CONTROL_CONN_STATE_OPEN ||
  3542. conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH);
  3543. if (!conn->incoming_cmd) {
  3544. conn->incoming_cmd = tor_malloc(1024);
  3545. conn->incoming_cmd_len = 1024;
  3546. conn->incoming_cmd_cur_len = 0;
  3547. }
  3548. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  3549. peek_connection_has_control0_command(TO_CONN(conn))) {
  3550. /* Detect v0 commands and send a "no more v0" message. */
  3551. size_t body_len;
  3552. char buf[128];
  3553. set_uint16(buf+2, htons(0x0000)); /* type == error */
  3554. set_uint16(buf+4, htons(0x0001)); /* code == internal error */
  3555. strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
  3556. "and later; upgrade your controller.",
  3557. sizeof(buf)-6);
  3558. body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
  3559. set_uint16(buf+0, htons(body_len));
  3560. connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
  3561. connection_mark_and_flush(TO_CONN(conn));
  3562. return 0;
  3563. }
  3564. again:
  3565. while (1) {
  3566. size_t last_idx;
  3567. int r;
  3568. /* First, fetch a line. */
  3569. do {
  3570. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  3571. r = connection_fetch_from_buf_line(TO_CONN(conn),
  3572. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  3573. &data_len);
  3574. if (r == 0)
  3575. /* Line not all here yet. Wait. */
  3576. return 0;
  3577. else if (r == -1) {
  3578. if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
  3579. connection_write_str_to_buf("500 Line too long.\r\n", conn);
  3580. connection_stop_reading(TO_CONN(conn));
  3581. connection_mark_and_flush(TO_CONN(conn));
  3582. }
  3583. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  3584. conn->incoming_cmd_len *= 2;
  3585. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  3586. conn->incoming_cmd_len);
  3587. }
  3588. } while (r != 1);
  3589. tor_assert(data_len);
  3590. last_idx = conn->incoming_cmd_cur_len;
  3591. conn->incoming_cmd_cur_len += (int)data_len;
  3592. /* We have appended a line to incoming_cmd. Is the command done? */
  3593. if (last_idx == 0 && *conn->incoming_cmd != '+')
  3594. /* One line command, didn't start with '+'. */
  3595. break;
  3596. /* XXXX this code duplication is kind of dumb. */
  3597. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  3598. tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  3599. /* Just appended ".\r\n"; we're done. Remove it. */
  3600. conn->incoming_cmd[last_idx] = '\0';
  3601. conn->incoming_cmd_cur_len -= 3;
  3602. break;
  3603. } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
  3604. tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
  3605. /* Just appended ".\n"; we're done. Remove it. */
  3606. conn->incoming_cmd[last_idx] = '\0';
  3607. conn->incoming_cmd_cur_len -= 2;
  3608. break;
  3609. }
  3610. /* Otherwise, read another line. */
  3611. }
  3612. data_len = conn->incoming_cmd_cur_len;
  3613. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  3614. * recognize it.
  3615. */
  3616. cmd_len = 0;
  3617. while ((size_t)cmd_len < data_len
  3618. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  3619. ++cmd_len;
  3620. conn->incoming_cmd[cmd_len]='\0';
  3621. args = conn->incoming_cmd+cmd_len+1;
  3622. tor_assert(data_len>(size_t)cmd_len);
  3623. data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
  3624. while (TOR_ISSPACE(*args)) {
  3625. ++args;
  3626. --data_len;
  3627. }
  3628. /* If the connection is already closing, ignore further commands */
  3629. if (TO_CONN(conn)->marked_for_close) {
  3630. return 0;
  3631. }
  3632. /* Otherwise, Quit is always valid. */
  3633. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  3634. connection_write_str_to_buf("250 closing connection\r\n", conn);
  3635. connection_mark_and_flush(TO_CONN(conn));
  3636. return 0;
  3637. }
  3638. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  3639. !is_valid_initial_command(conn, conn->incoming_cmd)) {
  3640. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  3641. connection_mark_for_close(TO_CONN(conn));
  3642. return 0;
  3643. }
  3644. if (data_len >= UINT32_MAX) {
  3645. connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
  3646. connection_mark_for_close(TO_CONN(conn));
  3647. return 0;
  3648. }
  3649. /* XXXX Why is this not implemented as a table like the GETINFO
  3650. * items are? Even handling the plus signs at the beginnings of
  3651. * commands wouldn't be very hard with proper macros. */
  3652. cmd_data_len = (uint32_t)data_len;
  3653. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  3654. if (handle_control_setconf(conn, cmd_data_len, args))
  3655. return -1;
  3656. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  3657. if (handle_control_resetconf(conn, cmd_data_len, args))
  3658. return -1;
  3659. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  3660. if (handle_control_getconf(conn, cmd_data_len, args))
  3661. return -1;
  3662. } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
  3663. if (handle_control_loadconf(conn, cmd_data_len, args))
  3664. return -1;
  3665. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  3666. if (handle_control_setevents(conn, cmd_data_len, args))
  3667. return -1;
  3668. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  3669. if (handle_control_authenticate(conn, cmd_data_len, args))
  3670. return -1;
  3671. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  3672. if (handle_control_saveconf(conn, cmd_data_len, args))
  3673. return -1;
  3674. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  3675. if (handle_control_signal(conn, cmd_data_len, args))
  3676. return -1;
  3677. } else if (!strcasecmp(conn->incoming_cmd, "TAKEOWNERSHIP")) {
  3678. if (handle_control_takeownership(conn, cmd_data_len, args))
  3679. return -1;
  3680. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  3681. if (handle_control_mapaddress(conn, cmd_data_len, args))
  3682. return -1;
  3683. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  3684. if (handle_control_getinfo(conn, cmd_data_len, args))
  3685. return -1;
  3686. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  3687. if (handle_control_extendcircuit(conn, cmd_data_len, args))
  3688. return -1;
  3689. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  3690. if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
  3691. return -1;
  3692. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  3693. connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
  3694. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  3695. if (handle_control_attachstream(conn, cmd_data_len, args))
  3696. return -1;
  3697. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  3698. if (handle_control_postdescriptor(conn, cmd_data_len, args))
  3699. return -1;
  3700. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  3701. if (handle_control_redirectstream(conn, cmd_data_len, args))
  3702. return -1;
  3703. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  3704. if (handle_control_closestream(conn, cmd_data_len, args))
  3705. return -1;
  3706. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  3707. if (handle_control_closecircuit(conn, cmd_data_len, args))
  3708. return -1;
  3709. } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
  3710. if (handle_control_usefeature(conn, cmd_data_len, args))
  3711. return -1;
  3712. } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
  3713. if (handle_control_resolve(conn, cmd_data_len, args))
  3714. return -1;
  3715. } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
  3716. if (handle_control_protocolinfo(conn, cmd_data_len, args))
  3717. return -1;
  3718. } else if (!strcasecmp(conn->incoming_cmd, "AUTHCHALLENGE")) {
  3719. if (handle_control_authchallenge(conn, cmd_data_len, args))
  3720. return -1;
  3721. } else if (!strcasecmp(conn->incoming_cmd, "DROPGUARDS")) {
  3722. if (handle_control_dropguards(conn, cmd_data_len, args))
  3723. return -1;
  3724. } else if (!strcasecmp(conn->incoming_cmd, "HSFETCH")) {
  3725. if (handle_control_hsfetch(conn, cmd_data_len, args))
  3726. return -1;
  3727. } else if (!strcasecmp(conn->incoming_cmd, "ADD_ONION")) {
  3728. int ret = handle_control_add_onion(conn, cmd_data_len, args);
  3729. memwipe(args, 0, cmd_data_len); /* Scrub the private key. */
  3730. if (ret)
  3731. return -1;
  3732. } else if (!strcasecmp(conn->incoming_cmd, "DEL_ONION")) {
  3733. int ret = handle_control_del_onion(conn, cmd_data_len, args);
  3734. memwipe(args, 0, cmd_data_len); /* Scrub the service id/pk. */
  3735. if (ret)
  3736. return -1;
  3737. } else {
  3738. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  3739. conn->incoming_cmd);
  3740. }
  3741. conn->incoming_cmd_cur_len = 0;
  3742. goto again;
  3743. }
  3744. /** Something major has happened to circuit <b>circ</b>: tell any
  3745. * interested control connections. */
  3746. int
  3747. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
  3748. int reason_code)
  3749. {
  3750. const char *status;
  3751. char reasons[64] = "";
  3752. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  3753. return 0;
  3754. tor_assert(circ);
  3755. switch (tp)
  3756. {
  3757. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  3758. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  3759. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  3760. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  3761. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  3762. default:
  3763. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3764. tor_fragile_assert();
  3765. return 0;
  3766. }
  3767. if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
  3768. const char *reason_str = circuit_end_reason_to_control_string(reason_code);
  3769. char unk_reason_buf[16];
  3770. if (!reason_str) {
  3771. tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
  3772. reason_str = unk_reason_buf;
  3773. }
  3774. if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
  3775. tor_snprintf(reasons, sizeof(reasons),
  3776. " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
  3777. } else {
  3778. tor_snprintf(reasons, sizeof(reasons),
  3779. " REASON=%s", reason_str);
  3780. }
  3781. }
  3782. {
  3783. char *circdesc = circuit_describe_status_for_controller(circ);
  3784. const char *sp = strlen(circdesc) ? " " : "";
  3785. send_control_event(EVENT_CIRCUIT_STATUS, ALL_FORMATS,
  3786. "650 CIRC %lu %s%s%s%s\r\n",
  3787. (unsigned long)circ->global_identifier,
  3788. status, sp,
  3789. circdesc,
  3790. reasons);
  3791. tor_free(circdesc);
  3792. }
  3793. return 0;
  3794. }
  3795. /** Something minor has happened to circuit <b>circ</b>: tell any
  3796. * interested control connections. */
  3797. static int
  3798. control_event_circuit_status_minor(origin_circuit_t *circ,
  3799. circuit_status_minor_event_t e,
  3800. int purpose, const struct timeval *tv)
  3801. {
  3802. const char *event_desc;
  3803. char event_tail[160] = "";
  3804. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
  3805. return 0;
  3806. tor_assert(circ);
  3807. switch (e)
  3808. {
  3809. case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
  3810. event_desc = "PURPOSE_CHANGED";
  3811. {
  3812. /* event_tail can currently be up to 68 chars long */
  3813. const char *hs_state_str =
  3814. circuit_purpose_to_controller_hs_state_string(purpose);
  3815. tor_snprintf(event_tail, sizeof(event_tail),
  3816. " OLD_PURPOSE=%s%s%s",
  3817. circuit_purpose_to_controller_string(purpose),
  3818. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  3819. (hs_state_str != NULL) ? hs_state_str : "");
  3820. }
  3821. break;
  3822. case CIRC_MINOR_EVENT_CANNIBALIZED:
  3823. event_desc = "CANNIBALIZED";
  3824. {
  3825. /* event_tail can currently be up to 130 chars long */
  3826. const char *hs_state_str =
  3827. circuit_purpose_to_controller_hs_state_string(purpose);
  3828. const struct timeval *old_timestamp_began = tv;
  3829. char tbuf[ISO_TIME_USEC_LEN+1];
  3830. format_iso_time_nospace_usec(tbuf, old_timestamp_began);
  3831. tor_snprintf(event_tail, sizeof(event_tail),
  3832. " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
  3833. circuit_purpose_to_controller_string(purpose),
  3834. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  3835. (hs_state_str != NULL) ? hs_state_str : "",
  3836. tbuf);
  3837. }
  3838. break;
  3839. default:
  3840. log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
  3841. tor_fragile_assert();
  3842. return 0;
  3843. }
  3844. {
  3845. char *circdesc = circuit_describe_status_for_controller(circ);
  3846. const char *sp = strlen(circdesc) ? " " : "";
  3847. send_control_event(EVENT_CIRCUIT_STATUS_MINOR, ALL_FORMATS,
  3848. "650 CIRC_MINOR %lu %s%s%s%s\r\n",
  3849. (unsigned long)circ->global_identifier,
  3850. event_desc, sp,
  3851. circdesc,
  3852. event_tail);
  3853. tor_free(circdesc);
  3854. }
  3855. return 0;
  3856. }
  3857. /**
  3858. * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
  3859. * interested controllers.
  3860. */
  3861. int
  3862. control_event_circuit_purpose_changed(origin_circuit_t *circ,
  3863. int old_purpose)
  3864. {
  3865. return control_event_circuit_status_minor(circ,
  3866. CIRC_MINOR_EVENT_PURPOSE_CHANGED,
  3867. old_purpose,
  3868. NULL);
  3869. }
  3870. /**
  3871. * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
  3872. * created-time from <b>old_tv_created</b>: tell any interested controllers.
  3873. */
  3874. int
  3875. control_event_circuit_cannibalized(origin_circuit_t *circ,
  3876. int old_purpose,
  3877. const struct timeval *old_tv_created)
  3878. {
  3879. return control_event_circuit_status_minor(circ,
  3880. CIRC_MINOR_EVENT_CANNIBALIZED,
  3881. old_purpose,
  3882. old_tv_created);
  3883. }
  3884. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  3885. * <b>buf</b>, determine the address:port combination requested on
  3886. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  3887. * failure. */
  3888. static int
  3889. write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
  3890. {
  3891. char buf2[256];
  3892. if (conn->chosen_exit_name)
  3893. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  3894. return -1;
  3895. if (!conn->socks_request)
  3896. return -1;
  3897. if (tor_snprintf(buf, len, "%s%s%s:%d",
  3898. conn->socks_request->address,
  3899. conn->chosen_exit_name ? buf2 : "",
  3900. !conn->chosen_exit_name && connection_edge_is_rendezvous_stream(
  3901. ENTRY_TO_EDGE_CONN(conn)) ? ".onion" : "",
  3902. conn->socks_request->port)<0)
  3903. return -1;
  3904. return 0;
  3905. }
  3906. /** Something has happened to the stream associated with AP connection
  3907. * <b>conn</b>: tell any interested control connections. */
  3908. int
  3909. control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
  3910. int reason_code)
  3911. {
  3912. char reason_buf[64];
  3913. char addrport_buf[64];
  3914. const char *status;
  3915. circuit_t *circ;
  3916. origin_circuit_t *origin_circ = NULL;
  3917. char buf[256];
  3918. const char *purpose = "";
  3919. tor_assert(conn->socks_request);
  3920. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  3921. return 0;
  3922. if (tp == STREAM_EVENT_CLOSED &&
  3923. (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
  3924. return 0;
  3925. write_stream_target_to_buf(conn, buf, sizeof(buf));
  3926. reason_buf[0] = '\0';
  3927. switch (tp)
  3928. {
  3929. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  3930. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  3931. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  3932. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  3933. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  3934. case STREAM_EVENT_NEW: status = "NEW"; break;
  3935. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  3936. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  3937. case STREAM_EVENT_REMAP: status = "REMAP"; break;
  3938. default:
  3939. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3940. return 0;
  3941. }
  3942. if (reason_code && (tp == STREAM_EVENT_FAILED ||
  3943. tp == STREAM_EVENT_CLOSED ||
  3944. tp == STREAM_EVENT_FAILED_RETRIABLE)) {
  3945. const char *reason_str = stream_end_reason_to_control_string(reason_code);
  3946. char *r = NULL;
  3947. if (!reason_str) {
  3948. tor_asprintf(&r, " UNKNOWN_%d", reason_code);
  3949. reason_str = r;
  3950. }
  3951. if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
  3952. tor_snprintf(reason_buf, sizeof(reason_buf),
  3953. " REASON=END REMOTE_REASON=%s", reason_str);
  3954. else
  3955. tor_snprintf(reason_buf, sizeof(reason_buf),
  3956. " REASON=%s", reason_str);
  3957. tor_free(r);
  3958. } else if (reason_code && tp == STREAM_EVENT_REMAP) {
  3959. switch (reason_code) {
  3960. case REMAP_STREAM_SOURCE_CACHE:
  3961. strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
  3962. break;
  3963. case REMAP_STREAM_SOURCE_EXIT:
  3964. strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
  3965. break;
  3966. default:
  3967. tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
  3968. reason_code);
  3969. /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
  3970. break;
  3971. }
  3972. }
  3973. if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
  3974. /*
  3975. * When the control conn is an AF_UNIX socket and we have no address,
  3976. * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
  3977. * dnsserv.c.
  3978. */
  3979. if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
  3980. tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
  3981. ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
  3982. } else {
  3983. /*
  3984. * else leave it blank so control on AF_UNIX doesn't need to make
  3985. * something up.
  3986. */
  3987. addrport_buf[0] = '\0';
  3988. }
  3989. } else {
  3990. addrport_buf[0] = '\0';
  3991. }
  3992. if (tp == STREAM_EVENT_NEW_RESOLVE) {
  3993. purpose = " PURPOSE=DNS_REQUEST";
  3994. } else if (tp == STREAM_EVENT_NEW) {
  3995. if (conn->use_begindir) {
  3996. connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
  3997. int linked_dir_purpose = -1;
  3998. if (linked && linked->type == CONN_TYPE_DIR)
  3999. linked_dir_purpose = linked->purpose;
  4000. if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
  4001. purpose = " PURPOSE=DIR_UPLOAD";
  4002. else
  4003. purpose = " PURPOSE=DIR_FETCH";
  4004. } else
  4005. purpose = " PURPOSE=USER";
  4006. }
  4007. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  4008. if (circ && CIRCUIT_IS_ORIGIN(circ))
  4009. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  4010. send_control_event(EVENT_STREAM_STATUS, ALL_FORMATS,
  4011. "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
  4012. U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
  4013. status,
  4014. origin_circ?
  4015. (unsigned long)origin_circ->global_identifier : 0ul,
  4016. buf, reason_buf, addrport_buf, purpose);
  4017. /* XXX need to specify its intended exit, etc? */
  4018. return 0;
  4019. }
  4020. /** Figure out the best name for the target router of an OR connection
  4021. * <b>conn</b>, and write it into the <b>len</b>-character buffer
  4022. * <b>name</b>. */
  4023. static void
  4024. orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
  4025. {
  4026. const node_t *node = node_get_by_id(conn->identity_digest);
  4027. if (node) {
  4028. tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
  4029. node_get_verbose_nickname(node, name);
  4030. } else if (! tor_digest_is_zero(conn->identity_digest)) {
  4031. name[0] = '$';
  4032. base16_encode(name+1, len-1, conn->identity_digest,
  4033. DIGEST_LEN);
  4034. } else {
  4035. tor_snprintf(name, len, "%s:%d",
  4036. conn->base_.address, conn->base_.port);
  4037. }
  4038. }
  4039. /** Called when the status of an OR connection <b>conn</b> changes: tell any
  4040. * interested control connections. <b>tp</b> is the new status for the
  4041. * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
  4042. * may be the reason why.
  4043. */
  4044. int
  4045. control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
  4046. int reason)
  4047. {
  4048. int ncircs = 0;
  4049. const char *status;
  4050. char name[128];
  4051. char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
  4052. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  4053. return 0;
  4054. switch (tp)
  4055. {
  4056. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  4057. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  4058. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  4059. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  4060. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  4061. default:
  4062. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  4063. return 0;
  4064. }
  4065. if (conn->chan) {
  4066. ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
  4067. } else {
  4068. ncircs = 0;
  4069. }
  4070. ncircs += connection_or_get_num_circuits(conn);
  4071. if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
  4072. tor_snprintf(ncircs_buf, sizeof(ncircs_buf), " NCIRCS=%d", ncircs);
  4073. }
  4074. orconn_target_get_name(name, sizeof(name), conn);
  4075. send_control_event(EVENT_OR_CONN_STATUS, ALL_FORMATS,
  4076. "650 ORCONN %s %s%s%s%s ID="U64_FORMAT"\r\n",
  4077. name, status,
  4078. reason ? " REASON=" : "",
  4079. orconn_end_reason_to_control_string(reason),
  4080. ncircs_buf,
  4081. U64_PRINTF_ARG(conn->base_.global_identifier));
  4082. return 0;
  4083. }
  4084. /**
  4085. * Print out STREAM_BW event for a single conn
  4086. */
  4087. int
  4088. control_event_stream_bandwidth(edge_connection_t *edge_conn)
  4089. {
  4090. circuit_t *circ;
  4091. origin_circuit_t *ocirc;
  4092. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  4093. if (!edge_conn->n_read && !edge_conn->n_written)
  4094. return 0;
  4095. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  4096. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  4097. U64_PRINTF_ARG(edge_conn->base_.global_identifier),
  4098. (unsigned long)edge_conn->n_read,
  4099. (unsigned long)edge_conn->n_written);
  4100. circ = circuit_get_by_edge_conn(edge_conn);
  4101. if (circ && CIRCUIT_IS_ORIGIN(circ)) {
  4102. ocirc = TO_ORIGIN_CIRCUIT(circ);
  4103. ocirc->n_read_circ_bw += edge_conn->n_read;
  4104. ocirc->n_written_circ_bw += edge_conn->n_written;
  4105. }
  4106. edge_conn->n_written = edge_conn->n_read = 0;
  4107. }
  4108. return 0;
  4109. }
  4110. /** A second or more has elapsed: tell any interested control
  4111. * connections how much bandwidth streams have used. */
  4112. int
  4113. control_event_stream_bandwidth_used(void)
  4114. {
  4115. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  4116. smartlist_t *conns = get_connection_array();
  4117. edge_connection_t *edge_conn;
  4118. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
  4119. {
  4120. if (conn->type != CONN_TYPE_AP)
  4121. continue;
  4122. edge_conn = TO_EDGE_CONN(conn);
  4123. if (!edge_conn->n_read && !edge_conn->n_written)
  4124. continue;
  4125. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  4126. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  4127. U64_PRINTF_ARG(edge_conn->base_.global_identifier),
  4128. (unsigned long)edge_conn->n_read,
  4129. (unsigned long)edge_conn->n_written);
  4130. edge_conn->n_written = edge_conn->n_read = 0;
  4131. }
  4132. SMARTLIST_FOREACH_END(conn);
  4133. }
  4134. return 0;
  4135. }
  4136. /** A second or more has elapsed: tell any interested control connections
  4137. * how much bandwidth origin circuits have used. */
  4138. int
  4139. control_event_circ_bandwidth_used(void)
  4140. {
  4141. origin_circuit_t *ocirc;
  4142. if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
  4143. return 0;
  4144. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  4145. if (!CIRCUIT_IS_ORIGIN(circ))
  4146. continue;
  4147. ocirc = TO_ORIGIN_CIRCUIT(circ);
  4148. if (!ocirc->n_read_circ_bw && !ocirc->n_written_circ_bw)
  4149. continue;
  4150. send_control_event(EVENT_CIRC_BANDWIDTH_USED, ALL_FORMATS,
  4151. "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu\r\n",
  4152. ocirc->global_identifier,
  4153. (unsigned long)ocirc->n_read_circ_bw,
  4154. (unsigned long)ocirc->n_written_circ_bw);
  4155. ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
  4156. }
  4157. SMARTLIST_FOREACH_END(circ);
  4158. return 0;
  4159. }
  4160. /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
  4161. * bandwidth counters. */
  4162. int
  4163. control_event_conn_bandwidth(connection_t *conn)
  4164. {
  4165. const char *conn_type_str;
  4166. if (!get_options()->TestingEnableConnBwEvent ||
  4167. !EVENT_IS_INTERESTING(EVENT_CONN_BW))
  4168. return 0;
  4169. if (!conn->n_read_conn_bw && !conn->n_written_conn_bw)
  4170. return 0;
  4171. switch (conn->type) {
  4172. case CONN_TYPE_OR:
  4173. conn_type_str = "OR";
  4174. break;
  4175. case CONN_TYPE_DIR:
  4176. conn_type_str = "DIR";
  4177. break;
  4178. case CONN_TYPE_EXIT:
  4179. conn_type_str = "EXIT";
  4180. break;
  4181. default:
  4182. return 0;
  4183. }
  4184. send_control_event(EVENT_CONN_BW, ALL_FORMATS,
  4185. "650 CONN_BW ID="U64_FORMAT" TYPE=%s "
  4186. "READ=%lu WRITTEN=%lu\r\n",
  4187. U64_PRINTF_ARG(conn->global_identifier),
  4188. conn_type_str,
  4189. (unsigned long)conn->n_read_conn_bw,
  4190. (unsigned long)conn->n_written_conn_bw);
  4191. conn->n_written_conn_bw = conn->n_read_conn_bw = 0;
  4192. return 0;
  4193. }
  4194. /** A second or more has elapsed: tell any interested control
  4195. * connections how much bandwidth connections have used. */
  4196. int
  4197. control_event_conn_bandwidth_used(void)
  4198. {
  4199. if (get_options()->TestingEnableConnBwEvent &&
  4200. EVENT_IS_INTERESTING(EVENT_CONN_BW)) {
  4201. SMARTLIST_FOREACH(get_connection_array(), connection_t *, conn,
  4202. control_event_conn_bandwidth(conn));
  4203. }
  4204. return 0;
  4205. }
  4206. /** Helper: iterate over cell statistics of <b>circ</b> and sum up added
  4207. * cells, removed cells, and waiting times by cell command and direction.
  4208. * Store results in <b>cell_stats</b>. Free cell statistics of the
  4209. * circuit afterwards. */
  4210. void
  4211. sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
  4212. {
  4213. memset(cell_stats, 0, sizeof(cell_stats_t));
  4214. SMARTLIST_FOREACH_BEGIN(circ->testing_cell_stats,
  4215. testing_cell_stats_entry_t *, ent) {
  4216. tor_assert(ent->command <= CELL_COMMAND_MAX_);
  4217. if (!ent->removed && !ent->exitward) {
  4218. cell_stats->added_cells_appward[ent->command] += 1;
  4219. } else if (!ent->removed && ent->exitward) {
  4220. cell_stats->added_cells_exitward[ent->command] += 1;
  4221. } else if (!ent->exitward) {
  4222. cell_stats->removed_cells_appward[ent->command] += 1;
  4223. cell_stats->total_time_appward[ent->command] += ent->waiting_time * 10;
  4224. } else {
  4225. cell_stats->removed_cells_exitward[ent->command] += 1;
  4226. cell_stats->total_time_exitward[ent->command] += ent->waiting_time * 10;
  4227. }
  4228. tor_free(ent);
  4229. } SMARTLIST_FOREACH_END(ent);
  4230. smartlist_free(circ->testing_cell_stats);
  4231. circ->testing_cell_stats = NULL;
  4232. }
  4233. /** Helper: append a cell statistics string to <code>event_parts</code>,
  4234. * prefixed with <code>key</code>=. Statistics consist of comma-separated
  4235. * key:value pairs with lower-case command strings as keys and cell
  4236. * numbers or total waiting times as values. A key:value pair is included
  4237. * if the entry in <code>include_if_non_zero</code> is not zero, but with
  4238. * the (possibly zero) entry from <code>number_to_include</code>. Both
  4239. * arrays are expected to have a length of CELL_COMMAND_MAX_ + 1. If no
  4240. * entry in <code>include_if_non_zero</code> is positive, no string will
  4241. * be added to <code>event_parts</code>. */
  4242. void
  4243. append_cell_stats_by_command(smartlist_t *event_parts, const char *key,
  4244. const uint64_t *include_if_non_zero,
  4245. const uint64_t *number_to_include)
  4246. {
  4247. smartlist_t *key_value_strings = smartlist_new();
  4248. int i;
  4249. for (i = 0; i <= CELL_COMMAND_MAX_; i++) {
  4250. if (include_if_non_zero[i] > 0) {
  4251. smartlist_add_asprintf(key_value_strings, "%s:"U64_FORMAT,
  4252. cell_command_to_string(i),
  4253. U64_PRINTF_ARG(number_to_include[i]));
  4254. }
  4255. }
  4256. if (smartlist_len(key_value_strings) > 0) {
  4257. char *joined = smartlist_join_strings(key_value_strings, ",", 0, NULL);
  4258. smartlist_add_asprintf(event_parts, "%s=%s", key, joined);
  4259. SMARTLIST_FOREACH(key_value_strings, char *, cp, tor_free(cp));
  4260. tor_free(joined);
  4261. }
  4262. smartlist_free(key_value_strings);
  4263. }
  4264. /** Helper: format <b>cell_stats</b> for <b>circ</b> for inclusion in a
  4265. * CELL_STATS event and write result string to <b>event_string</b>. */
  4266. void
  4267. format_cell_stats(char **event_string, circuit_t *circ,
  4268. cell_stats_t *cell_stats)
  4269. {
  4270. smartlist_t *event_parts = smartlist_new();
  4271. if (CIRCUIT_IS_ORIGIN(circ)) {
  4272. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  4273. smartlist_add_asprintf(event_parts, "ID=%lu",
  4274. (unsigned long)ocirc->global_identifier);
  4275. } else if (TO_OR_CIRCUIT(circ)->p_chan) {
  4276. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  4277. smartlist_add_asprintf(event_parts, "InboundQueue=%lu",
  4278. (unsigned long)or_circ->p_circ_id);
  4279. smartlist_add_asprintf(event_parts, "InboundConn="U64_FORMAT,
  4280. U64_PRINTF_ARG(or_circ->p_chan->global_identifier));
  4281. append_cell_stats_by_command(event_parts, "InboundAdded",
  4282. cell_stats->added_cells_appward,
  4283. cell_stats->added_cells_appward);
  4284. append_cell_stats_by_command(event_parts, "InboundRemoved",
  4285. cell_stats->removed_cells_appward,
  4286. cell_stats->removed_cells_appward);
  4287. append_cell_stats_by_command(event_parts, "InboundTime",
  4288. cell_stats->removed_cells_appward,
  4289. cell_stats->total_time_appward);
  4290. }
  4291. if (circ->n_chan) {
  4292. smartlist_add_asprintf(event_parts, "OutboundQueue=%lu",
  4293. (unsigned long)circ->n_circ_id);
  4294. smartlist_add_asprintf(event_parts, "OutboundConn="U64_FORMAT,
  4295. U64_PRINTF_ARG(circ->n_chan->global_identifier));
  4296. append_cell_stats_by_command(event_parts, "OutboundAdded",
  4297. cell_stats->added_cells_exitward,
  4298. cell_stats->added_cells_exitward);
  4299. append_cell_stats_by_command(event_parts, "OutboundRemoved",
  4300. cell_stats->removed_cells_exitward,
  4301. cell_stats->removed_cells_exitward);
  4302. append_cell_stats_by_command(event_parts, "OutboundTime",
  4303. cell_stats->removed_cells_exitward,
  4304. cell_stats->total_time_exitward);
  4305. }
  4306. *event_string = smartlist_join_strings(event_parts, " ", 0, NULL);
  4307. SMARTLIST_FOREACH(event_parts, char *, cp, tor_free(cp));
  4308. smartlist_free(event_parts);
  4309. }
  4310. /** A second or more has elapsed: tell any interested control connection
  4311. * how many cells have been processed for a given circuit. */
  4312. int
  4313. control_event_circuit_cell_stats(void)
  4314. {
  4315. cell_stats_t *cell_stats;
  4316. char *event_string;
  4317. if (!get_options()->TestingEnableCellStatsEvent ||
  4318. !EVENT_IS_INTERESTING(EVENT_CELL_STATS))
  4319. return 0;
  4320. cell_stats = tor_malloc(sizeof(cell_stats_t));;
  4321. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  4322. if (!circ->testing_cell_stats)
  4323. continue;
  4324. sum_up_cell_stats_by_command(circ, cell_stats);
  4325. format_cell_stats(&event_string, circ, cell_stats);
  4326. send_control_event(EVENT_CELL_STATS, ALL_FORMATS,
  4327. "650 CELL_STATS %s\r\n", event_string);
  4328. tor_free(event_string);
  4329. }
  4330. SMARTLIST_FOREACH_END(circ);
  4331. tor_free(cell_stats);
  4332. return 0;
  4333. }
  4334. /** Tokens in <b>bucket</b> have been refilled: the read bucket was empty
  4335. * for <b>read_empty_time</b> millis, the write bucket was empty for
  4336. * <b>write_empty_time</b> millis, and buckets were last refilled
  4337. * <b>milliseconds_elapsed</b> millis ago. Only emit TB_EMPTY event if
  4338. * either read or write bucket have been empty before. */
  4339. int
  4340. control_event_tb_empty(const char *bucket, uint32_t read_empty_time,
  4341. uint32_t write_empty_time,
  4342. int milliseconds_elapsed)
  4343. {
  4344. if (get_options()->TestingEnableTbEmptyEvent &&
  4345. EVENT_IS_INTERESTING(EVENT_TB_EMPTY) &&
  4346. (read_empty_time > 0 || write_empty_time > 0)) {
  4347. send_control_event(EVENT_TB_EMPTY, ALL_FORMATS,
  4348. "650 TB_EMPTY %s READ=%d WRITTEN=%d "
  4349. "LAST=%d\r\n",
  4350. bucket, read_empty_time, write_empty_time,
  4351. milliseconds_elapsed);
  4352. }
  4353. return 0;
  4354. }
  4355. /* about 5 minutes worth. */
  4356. #define N_BW_EVENTS_TO_CACHE 300
  4357. /* Index into cached_bw_events to next write. */
  4358. static int next_measurement_idx = 0;
  4359. /* number of entries set in n_measurements */
  4360. static int n_measurements = 0;
  4361. static struct cached_bw_event_s {
  4362. uint32_t n_read;
  4363. uint32_t n_written;
  4364. } cached_bw_events[N_BW_EVENTS_TO_CACHE];
  4365. /** A second or more has elapsed: tell any interested control
  4366. * connections how much bandwidth we used. */
  4367. int
  4368. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  4369. {
  4370. cached_bw_events[next_measurement_idx].n_read = n_read;
  4371. cached_bw_events[next_measurement_idx].n_written = n_written;
  4372. if (++next_measurement_idx == N_BW_EVENTS_TO_CACHE)
  4373. next_measurement_idx = 0;
  4374. if (n_measurements < N_BW_EVENTS_TO_CACHE)
  4375. ++n_measurements;
  4376. if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
  4377. send_control_event(EVENT_BANDWIDTH_USED, ALL_FORMATS,
  4378. "650 BW %lu %lu\r\n",
  4379. (unsigned long)n_read,
  4380. (unsigned long)n_written);
  4381. }
  4382. return 0;
  4383. }
  4384. STATIC char *
  4385. get_bw_samples(void)
  4386. {
  4387. int i;
  4388. int idx = (next_measurement_idx + N_BW_EVENTS_TO_CACHE - n_measurements)
  4389. % N_BW_EVENTS_TO_CACHE;
  4390. tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
  4391. smartlist_t *elements = smartlist_new();
  4392. for (i = 0; i < n_measurements; ++i) {
  4393. tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
  4394. const struct cached_bw_event_s *bwe = &cached_bw_events[idx];
  4395. smartlist_add_asprintf(elements, "%u,%u",
  4396. (unsigned)bwe->n_read,
  4397. (unsigned)bwe->n_written);
  4398. idx = (idx + 1) % N_BW_EVENTS_TO_CACHE;
  4399. }
  4400. char *result = smartlist_join_strings(elements, " ", 0, NULL);
  4401. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  4402. smartlist_free(elements);
  4403. return result;
  4404. }
  4405. /** Called when we are sending a log message to the controllers: suspend
  4406. * sending further log messages to the controllers until we're done. Used by
  4407. * CONN_LOG_PROTECT. */
  4408. void
  4409. disable_control_logging(void)
  4410. {
  4411. ++disable_log_messages;
  4412. }
  4413. /** We're done sending a log message to the controllers: re-enable controller
  4414. * logging. Used by CONN_LOG_PROTECT. */
  4415. void
  4416. enable_control_logging(void)
  4417. {
  4418. if (--disable_log_messages < 0)
  4419. tor_assert(0);
  4420. }
  4421. /** We got a log message: tell any interested control connections. */
  4422. void
  4423. control_event_logmsg(int severity, uint32_t domain, const char *msg)
  4424. {
  4425. int event;
  4426. /* Don't even think of trying to add stuff to a buffer from a cpuworker
  4427. * thread. */
  4428. if (! in_main_thread())
  4429. return;
  4430. if (disable_log_messages)
  4431. return;
  4432. if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
  4433. severity <= LOG_NOTICE) {
  4434. char *esc = esc_for_log(msg);
  4435. ++disable_log_messages;
  4436. control_event_general_status(severity, "BUG REASON=%s", esc);
  4437. --disable_log_messages;
  4438. tor_free(esc);
  4439. }
  4440. event = log_severity_to_event(severity);
  4441. if (event >= 0 && EVENT_IS_INTERESTING(event)) {
  4442. char *b = NULL;
  4443. const char *s;
  4444. if (strchr(msg, '\n')) {
  4445. char *cp;
  4446. b = tor_strdup(msg);
  4447. for (cp = b; *cp; ++cp)
  4448. if (*cp == '\r' || *cp == '\n')
  4449. *cp = ' ';
  4450. }
  4451. switch (severity) {
  4452. case LOG_DEBUG: s = "DEBUG"; break;
  4453. case LOG_INFO: s = "INFO"; break;
  4454. case LOG_NOTICE: s = "NOTICE"; break;
  4455. case LOG_WARN: s = "WARN"; break;
  4456. case LOG_ERR: s = "ERR"; break;
  4457. default: s = "UnknownLogSeverity"; break;
  4458. }
  4459. ++disable_log_messages;
  4460. send_control_event(event, ALL_FORMATS, "650 %s %s\r\n", s, b?b:msg);
  4461. --disable_log_messages;
  4462. tor_free(b);
  4463. }
  4464. }
  4465. /** Called whenever we receive new router descriptors: tell any
  4466. * interested control connections. <b>routers</b> is a list of
  4467. * routerinfo_t's.
  4468. */
  4469. int
  4470. control_event_descriptors_changed(smartlist_t *routers)
  4471. {
  4472. char *msg;
  4473. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  4474. return 0;
  4475. {
  4476. smartlist_t *names = smartlist_new();
  4477. char *ids;
  4478. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  4479. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  4480. router_get_verbose_nickname(b, ri);
  4481. smartlist_add(names, b);
  4482. });
  4483. ids = smartlist_join_strings(names, " ", 0, NULL);
  4484. tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
  4485. send_control_event_string(EVENT_NEW_DESC, ALL_FORMATS, msg);
  4486. tor_free(ids);
  4487. tor_free(msg);
  4488. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  4489. smartlist_free(names);
  4490. }
  4491. return 0;
  4492. }
  4493. /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
  4494. * <b>expires</b> values less than 3 are special; see connection_edge.c. If
  4495. * <b>error</b> is non-NULL, it is an error code describing the failure
  4496. * mode of the mapping.
  4497. */
  4498. int
  4499. control_event_address_mapped(const char *from, const char *to, time_t expires,
  4500. const char *error, const int cached)
  4501. {
  4502. if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
  4503. return 0;
  4504. if (expires < 3 || expires == TIME_MAX)
  4505. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  4506. "650 ADDRMAP %s %s NEVER %s%s"
  4507. "CACHED=\"%s\"\r\n",
  4508. from, to, error?error:"", error?" ":"",
  4509. cached?"YES":"NO");
  4510. else {
  4511. char buf[ISO_TIME_LEN+1];
  4512. char buf2[ISO_TIME_LEN+1];
  4513. format_local_iso_time(buf,expires);
  4514. format_iso_time(buf2,expires);
  4515. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  4516. "650 ADDRMAP %s %s \"%s\""
  4517. " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
  4518. from, to, buf,
  4519. error?error:"", error?" ":"",
  4520. buf2, cached?"YES":"NO");
  4521. }
  4522. return 0;
  4523. }
  4524. /** The authoritative dirserver has received a new descriptor that
  4525. * has passed basic syntax checks and is properly self-signed.
  4526. *
  4527. * Notify any interested party of the new descriptor and what has
  4528. * been done with it, and also optionally give an explanation/reason. */
  4529. int
  4530. control_event_or_authdir_new_descriptor(const char *action,
  4531. const char *desc, size_t desclen,
  4532. const char *msg)
  4533. {
  4534. char firstline[1024];
  4535. char *buf;
  4536. size_t totallen;
  4537. char *esc = NULL;
  4538. size_t esclen;
  4539. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  4540. return 0;
  4541. tor_snprintf(firstline, sizeof(firstline),
  4542. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  4543. action,
  4544. msg ? msg : "");
  4545. /* Escape the server descriptor properly */
  4546. esclen = write_escaped_data(desc, desclen, &esc);
  4547. totallen = strlen(firstline) + esclen + 1;
  4548. buf = tor_malloc(totallen);
  4549. strlcpy(buf, firstline, totallen);
  4550. strlcpy(buf+strlen(firstline), esc, totallen);
  4551. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  4552. buf);
  4553. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  4554. "650 OK\r\n");
  4555. tor_free(esc);
  4556. tor_free(buf);
  4557. return 0;
  4558. }
  4559. /** Helper function for NS-style events. Constructs and sends an event
  4560. * of type <b>event</b> with string <b>event_string</b> out of the set of
  4561. * networkstatuses <b>statuses</b>. Currently it is used for NS events
  4562. * and NEWCONSENSUS events. */
  4563. static int
  4564. control_event_networkstatus_changed_helper(smartlist_t *statuses,
  4565. uint16_t event,
  4566. const char *event_string)
  4567. {
  4568. smartlist_t *strs;
  4569. char *s, *esc = NULL;
  4570. if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
  4571. return 0;
  4572. strs = smartlist_new();
  4573. smartlist_add(strs, tor_strdup("650+"));
  4574. smartlist_add(strs, tor_strdup(event_string));
  4575. smartlist_add(strs, tor_strdup("\r\n"));
  4576. SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
  4577. {
  4578. s = networkstatus_getinfo_helper_single(rs);
  4579. if (!s) continue;
  4580. smartlist_add(strs, s);
  4581. });
  4582. s = smartlist_join_strings(strs, "", 0, NULL);
  4583. write_escaped_data(s, strlen(s), &esc);
  4584. SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
  4585. smartlist_free(strs);
  4586. tor_free(s);
  4587. send_control_event_string(event, ALL_FORMATS, esc);
  4588. send_control_event_string(event, ALL_FORMATS,
  4589. "650 OK\r\n");
  4590. tor_free(esc);
  4591. return 0;
  4592. }
  4593. /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
  4594. * an NS event to any controller that cares. */
  4595. int
  4596. control_event_networkstatus_changed(smartlist_t *statuses)
  4597. {
  4598. return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
  4599. }
  4600. /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
  4601. * event consisting of an NS-style line for each relay in the consensus. */
  4602. int
  4603. control_event_newconsensus(const networkstatus_t *consensus)
  4604. {
  4605. if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
  4606. return 0;
  4607. return control_event_networkstatus_changed_helper(
  4608. consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
  4609. }
  4610. /** Called when we compute a new circuitbuildtimeout */
  4611. int
  4612. control_event_buildtimeout_set(buildtimeout_set_event_t type,
  4613. const char *args)
  4614. {
  4615. const char *type_string = NULL;
  4616. if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
  4617. return 0;
  4618. switch (type) {
  4619. case BUILDTIMEOUT_SET_EVENT_COMPUTED:
  4620. type_string = "COMPUTED";
  4621. break;
  4622. case BUILDTIMEOUT_SET_EVENT_RESET:
  4623. type_string = "RESET";
  4624. break;
  4625. case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
  4626. type_string = "SUSPENDED";
  4627. break;
  4628. case BUILDTIMEOUT_SET_EVENT_DISCARD:
  4629. type_string = "DISCARD";
  4630. break;
  4631. case BUILDTIMEOUT_SET_EVENT_RESUME:
  4632. type_string = "RESUME";
  4633. break;
  4634. default:
  4635. type_string = "UNKNOWN";
  4636. break;
  4637. }
  4638. send_control_event(EVENT_BUILDTIMEOUT_SET, ALL_FORMATS,
  4639. "650 BUILDTIMEOUT_SET %s %s\r\n",
  4640. type_string, args);
  4641. return 0;
  4642. }
  4643. /** Called when a signal has been processed from signal_callback */
  4644. int
  4645. control_event_signal(uintptr_t signal)
  4646. {
  4647. const char *signal_string = NULL;
  4648. if (!control_event_is_interesting(EVENT_SIGNAL))
  4649. return 0;
  4650. switch (signal) {
  4651. case SIGHUP:
  4652. signal_string = "RELOAD";
  4653. break;
  4654. case SIGUSR1:
  4655. signal_string = "DUMP";
  4656. break;
  4657. case SIGUSR2:
  4658. signal_string = "DEBUG";
  4659. break;
  4660. case SIGNEWNYM:
  4661. signal_string = "NEWNYM";
  4662. break;
  4663. case SIGCLEARDNSCACHE:
  4664. signal_string = "CLEARDNSCACHE";
  4665. break;
  4666. case SIGHEARTBEAT:
  4667. signal_string = "HEARTBEAT";
  4668. break;
  4669. default:
  4670. log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
  4671. (unsigned long)signal);
  4672. return -1;
  4673. }
  4674. send_control_event(EVENT_SIGNAL, ALL_FORMATS, "650 SIGNAL %s\r\n",
  4675. signal_string);
  4676. return 0;
  4677. }
  4678. /** Called when a single local_routerstatus_t has changed: Sends an NS event
  4679. * to any controller that cares. */
  4680. int
  4681. control_event_networkstatus_changed_single(const routerstatus_t *rs)
  4682. {
  4683. smartlist_t *statuses;
  4684. int r;
  4685. if (!EVENT_IS_INTERESTING(EVENT_NS))
  4686. return 0;
  4687. statuses = smartlist_new();
  4688. smartlist_add(statuses, (void*)rs);
  4689. r = control_event_networkstatus_changed(statuses);
  4690. smartlist_free(statuses);
  4691. return r;
  4692. }
  4693. /** Our own router descriptor has changed; tell any controllers that care.
  4694. */
  4695. int
  4696. control_event_my_descriptor_changed(void)
  4697. {
  4698. send_control_event(EVENT_DESCCHANGED, ALL_FORMATS, "650 DESCCHANGED\r\n");
  4699. return 0;
  4700. }
  4701. /** Helper: sends a status event where <b>type</b> is one of
  4702. * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
  4703. * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
  4704. * string corresponding to <b>args</b>. */
  4705. static int
  4706. control_event_status(int type, int severity, const char *format, va_list args)
  4707. {
  4708. char *user_buf = NULL;
  4709. char format_buf[160];
  4710. const char *status, *sev;
  4711. switch (type) {
  4712. case EVENT_STATUS_GENERAL:
  4713. status = "STATUS_GENERAL";
  4714. break;
  4715. case EVENT_STATUS_CLIENT:
  4716. status = "STATUS_CLIENT";
  4717. break;
  4718. case EVENT_STATUS_SERVER:
  4719. status = "STATUS_SERVER";
  4720. break;
  4721. default:
  4722. log_warn(LD_BUG, "Unrecognized status type %d", type);
  4723. return -1;
  4724. }
  4725. switch (severity) {
  4726. case LOG_NOTICE:
  4727. sev = "NOTICE";
  4728. break;
  4729. case LOG_WARN:
  4730. sev = "WARN";
  4731. break;
  4732. case LOG_ERR:
  4733. sev = "ERR";
  4734. break;
  4735. default:
  4736. log_warn(LD_BUG, "Unrecognized status severity %d", severity);
  4737. return -1;
  4738. }
  4739. if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
  4740. status, sev)<0) {
  4741. log_warn(LD_BUG, "Format string too long.");
  4742. return -1;
  4743. }
  4744. tor_vasprintf(&user_buf, format, args);
  4745. send_control_event(type, ALL_FORMATS, "%s %s\r\n", format_buf, user_buf);
  4746. tor_free(user_buf);
  4747. return 0;
  4748. }
  4749. /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
  4750. * by formatting the arguments using the printf-style <b>format</b>. */
  4751. int
  4752. control_event_general_status(int severity, const char *format, ...)
  4753. {
  4754. va_list ap;
  4755. int r;
  4756. if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
  4757. return 0;
  4758. va_start(ap, format);
  4759. r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
  4760. va_end(ap);
  4761. return r;
  4762. }
  4763. /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
  4764. * by formatting the arguments using the printf-style <b>format</b>. */
  4765. int
  4766. control_event_client_status(int severity, const char *format, ...)
  4767. {
  4768. va_list ap;
  4769. int r;
  4770. if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
  4771. return 0;
  4772. va_start(ap, format);
  4773. r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
  4774. va_end(ap);
  4775. return r;
  4776. }
  4777. /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
  4778. * by formatting the arguments using the printf-style <b>format</b>. */
  4779. int
  4780. control_event_server_status(int severity, const char *format, ...)
  4781. {
  4782. va_list ap;
  4783. int r;
  4784. if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
  4785. return 0;
  4786. va_start(ap, format);
  4787. r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
  4788. va_end(ap);
  4789. return r;
  4790. }
  4791. /** Called when the status of an entry guard with the given <b>nickname</b>
  4792. * and identity <b>digest</b> has changed to <b>status</b>: tells any
  4793. * controllers that care. */
  4794. int
  4795. control_event_guard(const char *nickname, const char *digest,
  4796. const char *status)
  4797. {
  4798. char hbuf[HEX_DIGEST_LEN+1];
  4799. base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
  4800. if (!EVENT_IS_INTERESTING(EVENT_GUARD))
  4801. return 0;
  4802. {
  4803. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  4804. const node_t *node = node_get_by_id(digest);
  4805. if (node) {
  4806. node_get_verbose_nickname(node, buf);
  4807. } else {
  4808. tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
  4809. }
  4810. send_control_event(EVENT_GUARD, ALL_FORMATS,
  4811. "650 GUARD ENTRY %s %s\r\n", buf, status);
  4812. }
  4813. return 0;
  4814. }
  4815. /** Called when a configuration option changes. This is generally triggered
  4816. * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
  4817. * a smartlist_t containing (key, value, ...) pairs in sequence.
  4818. * <b>value</b> can be NULL. */
  4819. int
  4820. control_event_conf_changed(const smartlist_t *elements)
  4821. {
  4822. int i;
  4823. char *result;
  4824. smartlist_t *lines;
  4825. if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) ||
  4826. smartlist_len(elements) == 0) {
  4827. return 0;
  4828. }
  4829. lines = smartlist_new();
  4830. for (i = 0; i < smartlist_len(elements); i += 2) {
  4831. char *k = smartlist_get(elements, i);
  4832. char *v = smartlist_get(elements, i+1);
  4833. if (v == NULL) {
  4834. smartlist_add_asprintf(lines, "650-%s", k);
  4835. } else {
  4836. smartlist_add_asprintf(lines, "650-%s=%s", k, v);
  4837. }
  4838. }
  4839. result = smartlist_join_strings(lines, "\r\n", 0, NULL);
  4840. send_control_event(EVENT_CONF_CHANGED, 0,
  4841. "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
  4842. tor_free(result);
  4843. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  4844. smartlist_free(lines);
  4845. return 0;
  4846. }
  4847. /** Helper: Return a newly allocated string containing a path to the
  4848. * file where we store our authentication cookie. */
  4849. char *
  4850. get_controller_cookie_file_name(void)
  4851. {
  4852. const or_options_t *options = get_options();
  4853. if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
  4854. return tor_strdup(options->CookieAuthFile);
  4855. } else {
  4856. return get_datadir_fname("control_auth_cookie");
  4857. }
  4858. }
  4859. /* Initialize the cookie-based authentication system of the
  4860. * ControlPort. If <b>enabled</b> is 0, then disable the cookie
  4861. * authentication system. */
  4862. int
  4863. init_control_cookie_authentication(int enabled)
  4864. {
  4865. char *fname = NULL;
  4866. int retval;
  4867. if (!enabled) {
  4868. authentication_cookie_is_set = 0;
  4869. return 0;
  4870. }
  4871. fname = get_controller_cookie_file_name();
  4872. retval = init_cookie_authentication(fname, "", /* no header */
  4873. AUTHENTICATION_COOKIE_LEN,
  4874. get_options()->CookieAuthFileGroupReadable,
  4875. &authentication_cookie,
  4876. &authentication_cookie_is_set);
  4877. tor_free(fname);
  4878. return retval;
  4879. }
  4880. /** A copy of the process specifier of Tor's owning controller, or
  4881. * NULL if this Tor instance is not currently owned by a process. */
  4882. static char *owning_controller_process_spec = NULL;
  4883. /** A process-termination monitor for Tor's owning controller, or NULL
  4884. * if this Tor instance is not currently owned by a process. */
  4885. static tor_process_monitor_t *owning_controller_process_monitor = NULL;
  4886. static void owning_controller_procmon_cb(void *unused) ATTR_NORETURN;
  4887. /** Process-termination monitor callback for Tor's owning controller
  4888. * process. */
  4889. static void
  4890. owning_controller_procmon_cb(void *unused)
  4891. {
  4892. (void)unused;
  4893. lost_owning_controller("process", "vanished");
  4894. }
  4895. /** Set <b>process_spec</b> as Tor's owning controller process.
  4896. * Exit on failure. */
  4897. void
  4898. monitor_owning_controller_process(const char *process_spec)
  4899. {
  4900. const char *msg;
  4901. tor_assert((owning_controller_process_spec == NULL) ==
  4902. (owning_controller_process_monitor == NULL));
  4903. if (owning_controller_process_spec != NULL) {
  4904. if ((process_spec != NULL) && !strcmp(process_spec,
  4905. owning_controller_process_spec)) {
  4906. /* Same process -- return now, instead of disposing of and
  4907. * recreating the process-termination monitor. */
  4908. return;
  4909. }
  4910. /* We are currently owned by a process, and we should no longer be
  4911. * owned by it. Free the process-termination monitor. */
  4912. tor_process_monitor_free(owning_controller_process_monitor);
  4913. owning_controller_process_monitor = NULL;
  4914. tor_free(owning_controller_process_spec);
  4915. owning_controller_process_spec = NULL;
  4916. }
  4917. tor_assert((owning_controller_process_spec == NULL) &&
  4918. (owning_controller_process_monitor == NULL));
  4919. if (process_spec == NULL)
  4920. return;
  4921. owning_controller_process_spec = tor_strdup(process_spec);
  4922. owning_controller_process_monitor =
  4923. tor_process_monitor_new(tor_libevent_get_base(),
  4924. owning_controller_process_spec,
  4925. LD_CONTROL,
  4926. owning_controller_procmon_cb, NULL,
  4927. &msg);
  4928. if (owning_controller_process_monitor == NULL) {
  4929. log_err(LD_BUG, "Couldn't create process-termination monitor for "
  4930. "owning controller: %s. Exiting.",
  4931. msg);
  4932. owning_controller_process_spec = NULL;
  4933. tor_cleanup();
  4934. exit(0);
  4935. }
  4936. }
  4937. /** Convert the name of a bootstrapping phase <b>s</b> into strings
  4938. * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
  4939. static int
  4940. bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
  4941. const char **summary)
  4942. {
  4943. switch (s) {
  4944. case BOOTSTRAP_STATUS_UNDEF:
  4945. *tag = "undef";
  4946. *summary = "Undefined";
  4947. break;
  4948. case BOOTSTRAP_STATUS_STARTING:
  4949. *tag = "starting";
  4950. *summary = "Starting";
  4951. break;
  4952. case BOOTSTRAP_STATUS_CONN_DIR:
  4953. *tag = "conn_dir";
  4954. *summary = "Connecting to directory server";
  4955. break;
  4956. case BOOTSTRAP_STATUS_HANDSHAKE:
  4957. *tag = "status_handshake";
  4958. *summary = "Finishing handshake";
  4959. break;
  4960. case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
  4961. *tag = "handshake_dir";
  4962. *summary = "Finishing handshake with directory server";
  4963. break;
  4964. case BOOTSTRAP_STATUS_ONEHOP_CREATE:
  4965. *tag = "onehop_create";
  4966. *summary = "Establishing an encrypted directory connection";
  4967. break;
  4968. case BOOTSTRAP_STATUS_REQUESTING_STATUS:
  4969. *tag = "requesting_status";
  4970. *summary = "Asking for networkstatus consensus";
  4971. break;
  4972. case BOOTSTRAP_STATUS_LOADING_STATUS:
  4973. *tag = "loading_status";
  4974. *summary = "Loading networkstatus consensus";
  4975. break;
  4976. case BOOTSTRAP_STATUS_LOADING_KEYS:
  4977. *tag = "loading_keys";
  4978. *summary = "Loading authority key certs";
  4979. break;
  4980. case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
  4981. *tag = "requesting_descriptors";
  4982. /* XXXX this appears to incorrectly report internal on most loads */
  4983. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  4984. "Asking for relay descriptors for internal paths" :
  4985. "Asking for relay descriptors";
  4986. break;
  4987. /* If we're sure there are no exits in the consensus,
  4988. * inform the controller by adding "internal"
  4989. * to the status summaries.
  4990. * (We only check this while loading descriptors,
  4991. * so we may not know in the earlier stages.)
  4992. * But if there are exits, we can't be sure whether
  4993. * we're creating internal or exit paths/circuits.
  4994. * XXXX Or should be use different tags or statuses
  4995. * for internal and exit/all? */
  4996. case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
  4997. *tag = "loading_descriptors";
  4998. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  4999. "Loading relay descriptors for internal paths" :
  5000. "Loading relay descriptors";
  5001. break;
  5002. case BOOTSTRAP_STATUS_CONN_OR:
  5003. *tag = "conn_or";
  5004. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  5005. "Connecting to the Tor network internally" :
  5006. "Connecting to the Tor network";
  5007. break;
  5008. case BOOTSTRAP_STATUS_HANDSHAKE_OR:
  5009. *tag = "handshake_or";
  5010. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  5011. "Finishing handshake with first hop of internal circuit" :
  5012. "Finishing handshake with first hop";
  5013. break;
  5014. case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
  5015. *tag = "circuit_create";
  5016. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  5017. "Establishing an internal Tor circuit" :
  5018. "Establishing a Tor circuit";
  5019. break;
  5020. case BOOTSTRAP_STATUS_DONE:
  5021. *tag = "done";
  5022. *summary = "Done";
  5023. break;
  5024. default:
  5025. // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
  5026. *tag = *summary = "unknown";
  5027. return -1;
  5028. }
  5029. return 0;
  5030. }
  5031. /** What percentage through the bootstrap process are we? We remember
  5032. * this so we can avoid sending redundant bootstrap status events, and
  5033. * so we can guess context for the bootstrap messages which are
  5034. * ambiguous. It starts at 'undef', but gets set to 'starting' while
  5035. * Tor initializes. */
  5036. static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
  5037. /** As bootstrap_percent, but holds the bootstrapping level at which we last
  5038. * logged a NOTICE-level message. We use this, plus BOOTSTRAP_PCT_INCREMENT,
  5039. * to avoid flooding the log with a new message every time we get a few more
  5040. * microdescriptors */
  5041. static int notice_bootstrap_percent = 0;
  5042. /** How many problems have we had getting to the next bootstrapping phase?
  5043. * These include failure to establish a connection to a Tor relay,
  5044. * failures to finish the TLS handshake, failures to validate the
  5045. * consensus document, etc. */
  5046. static int bootstrap_problems = 0;
  5047. /** We only tell the controller once we've hit a threshold of problems
  5048. * for the current phase. */
  5049. #define BOOTSTRAP_PROBLEM_THRESHOLD 10
  5050. /** When our bootstrapping progress level changes, but our bootstrapping
  5051. * status has not advanced, we only log at NOTICE when we have made at least
  5052. * this much progress.
  5053. */
  5054. #define BOOTSTRAP_PCT_INCREMENT 5
  5055. /** Called when Tor has made progress at bootstrapping its directory
  5056. * information and initial circuits.
  5057. *
  5058. * <b>status</b> is the new status, that is, what task we will be doing
  5059. * next. <b>progress</b> is zero if we just started this task, else it
  5060. * represents progress on the task.
  5061. *
  5062. * Return true if we logged a message at level NOTICE, and false otherwise.
  5063. */
  5064. int
  5065. control_event_bootstrap(bootstrap_status_t status, int progress)
  5066. {
  5067. const char *tag, *summary;
  5068. char buf[BOOTSTRAP_MSG_LEN];
  5069. if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
  5070. return 0; /* already bootstrapped; nothing to be done here. */
  5071. /* special case for handshaking status, since our TLS handshaking code
  5072. * can't distinguish what the connection is going to be for. */
  5073. if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
  5074. if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
  5075. status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
  5076. } else {
  5077. status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
  5078. }
  5079. }
  5080. if (status > bootstrap_percent ||
  5081. (progress && progress > bootstrap_percent)) {
  5082. int loglevel = LOG_NOTICE;
  5083. bootstrap_status_to_string(status, &tag, &summary);
  5084. if (status <= bootstrap_percent &&
  5085. (progress < notice_bootstrap_percent + BOOTSTRAP_PCT_INCREMENT)) {
  5086. /* We log the message at info if the status hasn't advanced, and if less
  5087. * than BOOTSTRAP_PCT_INCREMENT progress has been made.
  5088. */
  5089. loglevel = LOG_INFO;
  5090. }
  5091. tor_log(loglevel, LD_CONTROL,
  5092. "Bootstrapped %d%%: %s", progress ? progress : status, summary);
  5093. tor_snprintf(buf, sizeof(buf),
  5094. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
  5095. progress ? progress : status, tag, summary);
  5096. tor_snprintf(last_sent_bootstrap_message,
  5097. sizeof(last_sent_bootstrap_message),
  5098. "NOTICE %s", buf);
  5099. control_event_client_status(LOG_NOTICE, "%s", buf);
  5100. if (status > bootstrap_percent) {
  5101. bootstrap_percent = status; /* new milestone reached */
  5102. }
  5103. if (progress > bootstrap_percent) {
  5104. /* incremental progress within a milestone */
  5105. bootstrap_percent = progress;
  5106. bootstrap_problems = 0; /* Progress! Reset our problem counter. */
  5107. }
  5108. if (loglevel == LOG_NOTICE &&
  5109. bootstrap_percent > notice_bootstrap_percent) {
  5110. /* Remember that we gave a notice at this level. */
  5111. notice_bootstrap_percent = bootstrap_percent;
  5112. }
  5113. return loglevel == LOG_NOTICE;
  5114. }
  5115. return 0;
  5116. }
  5117. /** Called when Tor has failed to make bootstrapping progress in a way
  5118. * that indicates a problem. <b>warn</b> gives a hint as to why, and
  5119. * <b>reason</b> provides an "or_conn_end_reason" tag. <b>or_conn</b>
  5120. * is the connection that caused this problem.
  5121. */
  5122. MOCK_IMPL(void,
  5123. control_event_bootstrap_problem, (const char *warn, int reason,
  5124. or_connection_t *or_conn))
  5125. {
  5126. int status = bootstrap_percent;
  5127. const char *tag = "", *summary = "";
  5128. char buf[BOOTSTRAP_MSG_LEN];
  5129. const char *recommendation = "ignore";
  5130. int severity;
  5131. /* bootstrap_percent must not be in "undefined" state here. */
  5132. tor_assert(status >= 0);
  5133. if (or_conn->have_noted_bootstrap_problem)
  5134. return;
  5135. or_conn->have_noted_bootstrap_problem = 1;
  5136. if (bootstrap_percent == 100)
  5137. return; /* already bootstrapped; nothing to be done here. */
  5138. bootstrap_problems++;
  5139. if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
  5140. recommendation = "warn";
  5141. if (reason == END_OR_CONN_REASON_NO_ROUTE)
  5142. recommendation = "warn";
  5143. /* If we are using bridges and all our OR connections are now
  5144. closed, it means that we totally failed to connect to our
  5145. bridges. Throw a warning. */
  5146. if (get_options()->UseBridges && !any_other_active_or_conns(or_conn))
  5147. recommendation = "warn";
  5148. if (we_are_hibernating())
  5149. recommendation = "ignore";
  5150. while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
  5151. status--; /* find a recognized status string based on current progress */
  5152. status = bootstrap_percent; /* set status back to the actual number */
  5153. severity = !strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO;
  5154. log_fn(severity,
  5155. LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
  5156. "count %d; recommendation %s; host %s at %s:%d)",
  5157. status, summary, warn,
  5158. orconn_end_reason_to_control_string(reason),
  5159. bootstrap_problems, recommendation,
  5160. hex_str(or_conn->identity_digest, DIGEST_LEN),
  5161. or_conn->base_.address,
  5162. or_conn->base_.port);
  5163. connection_or_report_broken_states(severity, LD_HANDSHAKE);
  5164. tor_snprintf(buf, sizeof(buf),
  5165. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
  5166. "COUNT=%d RECOMMENDATION=%s HOSTID=\"%s\" HOSTADDR=\"%s:%d\"",
  5167. bootstrap_percent, tag, summary, warn,
  5168. orconn_end_reason_to_control_string(reason), bootstrap_problems,
  5169. recommendation,
  5170. hex_str(or_conn->identity_digest, DIGEST_LEN),
  5171. or_conn->base_.address,
  5172. (int)or_conn->base_.port);
  5173. tor_snprintf(last_sent_bootstrap_message,
  5174. sizeof(last_sent_bootstrap_message),
  5175. "WARN %s", buf);
  5176. control_event_client_status(LOG_WARN, "%s", buf);
  5177. }
  5178. /** We just generated a new summary of which countries we've seen clients
  5179. * from recently. Send a copy to the controller in case it wants to
  5180. * display it for the user. */
  5181. void
  5182. control_event_clients_seen(const char *controller_str)
  5183. {
  5184. send_control_event(EVENT_CLIENTS_SEEN, 0,
  5185. "650 CLIENTS_SEEN %s\r\n", controller_str);
  5186. }
  5187. /** A new pluggable transport called <b>transport_name</b> was
  5188. * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
  5189. * "server" or "client" depending on the mode of the pluggable
  5190. * transport.
  5191. * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
  5192. */
  5193. void
  5194. control_event_transport_launched(const char *mode, const char *transport_name,
  5195. tor_addr_t *addr, uint16_t port)
  5196. {
  5197. send_control_event(EVENT_TRANSPORT_LAUNCHED, ALL_FORMATS,
  5198. "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
  5199. mode, transport_name, fmt_addr(addr), port);
  5200. }
  5201. /** Convert rendezvous auth type to string for HS_DESC control events
  5202. */
  5203. const char *
  5204. rend_auth_type_to_string(rend_auth_type_t auth_type)
  5205. {
  5206. const char *str;
  5207. switch (auth_type) {
  5208. case REND_NO_AUTH:
  5209. str = "NO_AUTH";
  5210. break;
  5211. case REND_BASIC_AUTH:
  5212. str = "BASIC_AUTH";
  5213. break;
  5214. case REND_STEALTH_AUTH:
  5215. str = "STEALTH_AUTH";
  5216. break;
  5217. default:
  5218. str = "UNKNOWN";
  5219. }
  5220. return str;
  5221. }
  5222. /** Return a longname the node whose identity is <b>id_digest</b>. If
  5223. * node_get_by_id() returns NULL, base 16 encoding of <b>id_digest</b> is
  5224. * returned instead.
  5225. *
  5226. * This function is not thread-safe. Each call to this function invalidates
  5227. * previous values returned by this function.
  5228. */
  5229. MOCK_IMPL(const char *,
  5230. node_describe_longname_by_id,(const char *id_digest))
  5231. {
  5232. static char longname[MAX_VERBOSE_NICKNAME_LEN+1];
  5233. node_get_verbose_nickname_by_id(id_digest, longname);
  5234. return longname;
  5235. }
  5236. /** Return either the onion address if the given pointer is a non empty
  5237. * string else the unknown string. */
  5238. static const char *
  5239. rend_hsaddress_str_or_unknown(const char *onion_address)
  5240. {
  5241. static const char *str_unknown = "UNKNOWN";
  5242. const char *str_ret = str_unknown;
  5243. /* No valid pointer, unknown it is. */
  5244. if (!onion_address) {
  5245. goto end;
  5246. }
  5247. /* Empty onion address thus we don't know, unknown it is. */
  5248. if (onion_address[0] == '\0') {
  5249. goto end;
  5250. }
  5251. /* All checks are good so return the given onion address. */
  5252. str_ret = onion_address;
  5253. end:
  5254. return str_ret;
  5255. }
  5256. /** send HS_DESC requested event.
  5257. *
  5258. * <b>rend_query</b> is used to fetch requested onion address and auth type.
  5259. * <b>hs_dir</b> is the description of contacting hs directory.
  5260. * <b>desc_id_base32</b> is the ID of requested hs descriptor.
  5261. */
  5262. void
  5263. control_event_hs_descriptor_requested(const rend_data_t *rend_query,
  5264. const char *id_digest,
  5265. const char *desc_id_base32)
  5266. {
  5267. if (!id_digest || !rend_query || !desc_id_base32) {
  5268. log_warn(LD_BUG, "Called with rend_query==%p, "
  5269. "id_digest==%p, desc_id_base32==%p",
  5270. rend_query, id_digest, desc_id_base32);
  5271. return;
  5272. }
  5273. send_control_event(EVENT_HS_DESC, ALL_FORMATS,
  5274. "650 HS_DESC REQUESTED %s %s %s %s\r\n",
  5275. rend_hsaddress_str_or_unknown(rend_query->onion_address),
  5276. rend_auth_type_to_string(rend_query->auth_type),
  5277. node_describe_longname_by_id(id_digest),
  5278. desc_id_base32);
  5279. }
  5280. /** send HS_DESC event after got response from hs directory.
  5281. *
  5282. * NOTE: this is an internal function used by following functions:
  5283. * control_event_hs_descriptor_received
  5284. * control_event_hs_descriptor_failed
  5285. *
  5286. * So do not call this function directly.
  5287. */
  5288. void
  5289. control_event_hs_descriptor_receive_end(const char *action,
  5290. const char *onion_address,
  5291. rend_auth_type_t auth_type,
  5292. const char *id_digest,
  5293. const char *reason)
  5294. {
  5295. char *reason_field = NULL;
  5296. if (!action || !id_digest || !onion_address) {
  5297. log_warn(LD_BUG, "Called with action==%p, id_digest==%p "
  5298. "onion_address==%p", action, id_digest, onion_address);
  5299. return;
  5300. }
  5301. if (reason) {
  5302. tor_asprintf(&reason_field, " REASON=%s", reason);
  5303. }
  5304. send_control_event(EVENT_HS_DESC, ALL_FORMATS,
  5305. "650 HS_DESC %s %s %s %s%s\r\n",
  5306. action,
  5307. rend_hsaddress_str_or_unknown(onion_address),
  5308. rend_auth_type_to_string(auth_type),
  5309. node_describe_longname_by_id(id_digest),
  5310. reason_field ? reason_field : "");
  5311. tor_free(reason_field);
  5312. }
  5313. /** send HS_DESC RECEIVED event
  5314. *
  5315. * called when a we successfully received a hidden service descriptor.
  5316. */
  5317. void
  5318. control_event_hs_descriptor_received(const char *onion_address,
  5319. rend_auth_type_t auth_type,
  5320. const char *id_digest)
  5321. {
  5322. if (!id_digest) {
  5323. log_warn(LD_BUG, "Called with id_digest==%p", id_digest);
  5324. return;
  5325. }
  5326. control_event_hs_descriptor_receive_end("RECEIVED", onion_address,
  5327. auth_type, id_digest, NULL);
  5328. }
  5329. /** Send HS_DESC event to inform controller that query <b>rend_query</b>
  5330. * failed to retrieve hidden service descriptor identified by
  5331. * <b>id_digest</b>. If <b>reason</b> is not NULL, add it to REASON=
  5332. * field.
  5333. */
  5334. void
  5335. control_event_hs_descriptor_failed(const char *onion_address,
  5336. rend_auth_type_t auth_type,
  5337. const char *id_digest,
  5338. const char *reason)
  5339. {
  5340. if (!id_digest) {
  5341. log_warn(LD_BUG, "Called with id_digest==%p", id_digest);
  5342. return;
  5343. }
  5344. control_event_hs_descriptor_receive_end("FAILED", onion_address, auth_type,
  5345. id_digest, reason);
  5346. }
  5347. /** send HS_DESC_CONTENT event after completion of a successful fetch from
  5348. * hs directory. */
  5349. void
  5350. control_event_hs_descriptor_content(const char *onion_address,
  5351. const char *desc_id,
  5352. const char *hsdir_id_digest,
  5353. const char *content)
  5354. {
  5355. static const char *event_name = "HS_DESC_CONTENT";
  5356. char *esc_content = NULL;
  5357. if (!onion_address || !desc_id || !hsdir_id_digest) {
  5358. log_warn(LD_BUG, "Called with onion_address==%p, desc_id==%p, "
  5359. "hsdir_id_digest==%p", onion_address, desc_id, hsdir_id_digest);
  5360. return;
  5361. }
  5362. if (content == NULL) {
  5363. /* Point it to empty content so it can still be escaped. */
  5364. content = "";
  5365. }
  5366. write_escaped_data(content, strlen(content), &esc_content);
  5367. send_control_event(EVENT_HS_DESC_CONTENT, ALL_FORMATS,
  5368. "650+%s %s %s %s\r\n%s650 OK\r\n",
  5369. event_name,
  5370. rend_hsaddress_str_or_unknown(onion_address),
  5371. desc_id,
  5372. node_describe_longname_by_id(hsdir_id_digest),
  5373. esc_content);
  5374. tor_free(esc_content);
  5375. }
  5376. /** Free any leftover allocated memory of the control.c subsystem. */
  5377. void
  5378. control_free_all(void)
  5379. {
  5380. if (authentication_cookie) /* Free the auth cookie */
  5381. tor_free(authentication_cookie);
  5382. if (detached_onion_services) { /* Free the detached onion services */
  5383. SMARTLIST_FOREACH(detached_onion_services, char *, cp, tor_free(cp));
  5384. smartlist_free(detached_onion_services);
  5385. }
  5386. }
  5387. #ifdef TOR_UNIT_TESTS
  5388. /* For testing: change the value of global_event_mask */
  5389. void
  5390. control_testing_set_global_event_mask(uint64_t mask)
  5391. {
  5392. global_event_mask = mask;
  5393. }
  5394. #endif