control.c 184 KB

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