control.c 183 KB

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