control.c 184 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509
  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. const char *server;
  3021. server = arg + strlen(opt_server);
  3022. node = node_get_by_hex_id(server);
  3023. if (!node) {
  3024. connection_printf_to_buf(conn, "552 Server \"%s\" not found\r\n",
  3025. server);
  3026. goto done;
  3027. }
  3028. if (!hsdirs) {
  3029. /* Stores routerstatus_t object for each specified server. */
  3030. hsdirs = smartlist_new();
  3031. }
  3032. /* Valid server, add it to our local list. */
  3033. smartlist_add(hsdirs, node->rs);
  3034. } else {
  3035. connection_printf_to_buf(conn, "552 Unexpected argument \"%s\"\r\n",
  3036. arg);
  3037. goto done;
  3038. }
  3039. } SMARTLIST_FOREACH_END(arg);
  3040. rend_query = tor_malloc_zero(sizeof(*rend_query));
  3041. if (hsaddress) {
  3042. strncpy(rend_query->onion_address, hsaddress,
  3043. sizeof(rend_query->onion_address));
  3044. } else if (desc_id) {
  3045. /* Using a descriptor ID, we force the user to provide at least one
  3046. * hsdir server using the SERVER= option. */
  3047. if (!hsdirs || !smartlist_len(hsdirs)) {
  3048. connection_printf_to_buf(conn, "552 SERVER= option is required\r\n");
  3049. goto done;
  3050. }
  3051. memcpy(rend_query->descriptor_id, desc_id,
  3052. sizeof(rend_query->descriptor_id));
  3053. } else {
  3054. /* We can't get in here because of the first argument check. */
  3055. tor_assert(0);
  3056. }
  3057. /* We are about to trigger HSDir fetch so send the OK now because after
  3058. * that 650 event(s) are possible so better to have the 250 OK before them
  3059. * to avoid out of order replies. */
  3060. send_control_done(conn);
  3061. /* Trigger the fetch using the built rend query and possibly a lit of HS
  3062. * directory to use. This function ignores the client cache thus this will
  3063. * always send a fetch command. */
  3064. rend_client_fetch_v2_desc(rend_query, hsdirs);
  3065. done:
  3066. if (hsdirs) {
  3067. smartlist_free(hsdirs);
  3068. }
  3069. if (args) {
  3070. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3071. smartlist_free(args);
  3072. }
  3073. tor_free(rend_query);
  3074. tor_free(arg1);
  3075. return 0;
  3076. }
  3077. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  3078. int
  3079. connection_control_finished_flushing(control_connection_t *conn)
  3080. {
  3081. tor_assert(conn);
  3082. return 0;
  3083. }
  3084. /** Called when <b>conn</b> has gotten its socket closed. */
  3085. int
  3086. connection_control_reached_eof(control_connection_t *conn)
  3087. {
  3088. tor_assert(conn);
  3089. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  3090. connection_mark_for_close(TO_CONN(conn));
  3091. return 0;
  3092. }
  3093. static void lost_owning_controller(const char *owner_type,
  3094. const char *loss_manner)
  3095. ATTR_NORETURN;
  3096. /** Shut down this Tor instance in the same way that SIGINT would, but
  3097. * with a log message appropriate for the loss of an owning controller. */
  3098. static void
  3099. lost_owning_controller(const char *owner_type, const char *loss_manner)
  3100. {
  3101. log_notice(LD_CONTROL, "Owning controller %s has %s -- exiting now.",
  3102. owner_type, loss_manner);
  3103. /* XXXX Perhaps this chunk of code should be a separate function,
  3104. * called here and by process_signal(SIGINT). */
  3105. tor_cleanup();
  3106. exit(0);
  3107. }
  3108. /** Called when <b>conn</b> is being freed. */
  3109. void
  3110. connection_control_closed(control_connection_t *conn)
  3111. {
  3112. tor_assert(conn);
  3113. conn->event_mask = 0;
  3114. control_update_global_event_mask();
  3115. if (conn->is_owning_control_connection) {
  3116. lost_owning_controller("connection", "closed");
  3117. }
  3118. }
  3119. /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
  3120. * stage of the protocol. */
  3121. static int
  3122. is_valid_initial_command(control_connection_t *conn, const char *cmd)
  3123. {
  3124. if (conn->base_.state == CONTROL_CONN_STATE_OPEN)
  3125. return 1;
  3126. if (!strcasecmp(cmd, "PROTOCOLINFO"))
  3127. return (!conn->have_sent_protocolinfo &&
  3128. conn->safecookie_client_hash == NULL);
  3129. if (!strcasecmp(cmd, "AUTHCHALLENGE"))
  3130. return (conn->safecookie_client_hash == NULL);
  3131. if (!strcasecmp(cmd, "AUTHENTICATE") ||
  3132. !strcasecmp(cmd, "QUIT"))
  3133. return 1;
  3134. return 0;
  3135. }
  3136. /** Do not accept any control command of more than 1MB in length. Anything
  3137. * that needs to be anywhere near this long probably means that one of our
  3138. * interfaces is broken. */
  3139. #define MAX_COMMAND_LINE_LENGTH (1024*1024)
  3140. /** Wrapper around peek_(evbuffer|buf)_has_control0 command: presents the same
  3141. * interface as those underlying functions, but takes a connection_t intead of
  3142. * an evbuffer or a buf_t.
  3143. */
  3144. static int
  3145. peek_connection_has_control0_command(connection_t *conn)
  3146. {
  3147. IF_HAS_BUFFEREVENT(conn, {
  3148. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  3149. return peek_evbuffer_has_control0_command(input);
  3150. }) ELSE_IF_NO_BUFFEREVENT {
  3151. return peek_buf_has_control0_command(conn->inbuf);
  3152. }
  3153. }
  3154. /** Called when data has arrived on a v1 control connection: Try to fetch
  3155. * commands from conn->inbuf, and execute them.
  3156. */
  3157. int
  3158. connection_control_process_inbuf(control_connection_t *conn)
  3159. {
  3160. size_t data_len;
  3161. uint32_t cmd_data_len;
  3162. int cmd_len;
  3163. char *args;
  3164. tor_assert(conn);
  3165. tor_assert(conn->base_.state == CONTROL_CONN_STATE_OPEN ||
  3166. conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH);
  3167. if (!conn->incoming_cmd) {
  3168. conn->incoming_cmd = tor_malloc(1024);
  3169. conn->incoming_cmd_len = 1024;
  3170. conn->incoming_cmd_cur_len = 0;
  3171. }
  3172. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  3173. peek_connection_has_control0_command(TO_CONN(conn))) {
  3174. /* Detect v0 commands and send a "no more v0" message. */
  3175. size_t body_len;
  3176. char buf[128];
  3177. set_uint16(buf+2, htons(0x0000)); /* type == error */
  3178. set_uint16(buf+4, htons(0x0001)); /* code == internal error */
  3179. strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
  3180. "and later; upgrade your controller.",
  3181. sizeof(buf)-6);
  3182. body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
  3183. set_uint16(buf+0, htons(body_len));
  3184. connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
  3185. connection_mark_and_flush(TO_CONN(conn));
  3186. return 0;
  3187. }
  3188. again:
  3189. while (1) {
  3190. size_t last_idx;
  3191. int r;
  3192. /* First, fetch a line. */
  3193. do {
  3194. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  3195. r = connection_fetch_from_buf_line(TO_CONN(conn),
  3196. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  3197. &data_len);
  3198. if (r == 0)
  3199. /* Line not all here yet. Wait. */
  3200. return 0;
  3201. else if (r == -1) {
  3202. if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
  3203. connection_write_str_to_buf("500 Line too long.\r\n", conn);
  3204. connection_stop_reading(TO_CONN(conn));
  3205. connection_mark_and_flush(TO_CONN(conn));
  3206. }
  3207. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  3208. conn->incoming_cmd_len *= 2;
  3209. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  3210. conn->incoming_cmd_len);
  3211. }
  3212. } while (r != 1);
  3213. tor_assert(data_len);
  3214. last_idx = conn->incoming_cmd_cur_len;
  3215. conn->incoming_cmd_cur_len += (int)data_len;
  3216. /* We have appended a line to incoming_cmd. Is the command done? */
  3217. if (last_idx == 0 && *conn->incoming_cmd != '+')
  3218. /* One line command, didn't start with '+'. */
  3219. break;
  3220. /* XXXX this code duplication is kind of dumb. */
  3221. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  3222. tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  3223. /* Just appended ".\r\n"; we're done. Remove it. */
  3224. conn->incoming_cmd[last_idx] = '\0';
  3225. conn->incoming_cmd_cur_len -= 3;
  3226. break;
  3227. } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
  3228. tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
  3229. /* Just appended ".\n"; we're done. Remove it. */
  3230. conn->incoming_cmd[last_idx] = '\0';
  3231. conn->incoming_cmd_cur_len -= 2;
  3232. break;
  3233. }
  3234. /* Otherwise, read another line. */
  3235. }
  3236. data_len = conn->incoming_cmd_cur_len;
  3237. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  3238. * recognize it.
  3239. */
  3240. cmd_len = 0;
  3241. while ((size_t)cmd_len < data_len
  3242. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  3243. ++cmd_len;
  3244. conn->incoming_cmd[cmd_len]='\0';
  3245. args = conn->incoming_cmd+cmd_len+1;
  3246. tor_assert(data_len>(size_t)cmd_len);
  3247. data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
  3248. while (TOR_ISSPACE(*args)) {
  3249. ++args;
  3250. --data_len;
  3251. }
  3252. /* If the connection is already closing, ignore further commands */
  3253. if (TO_CONN(conn)->marked_for_close) {
  3254. return 0;
  3255. }
  3256. /* Otherwise, Quit is always valid. */
  3257. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  3258. connection_write_str_to_buf("250 closing connection\r\n", conn);
  3259. connection_mark_and_flush(TO_CONN(conn));
  3260. return 0;
  3261. }
  3262. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  3263. !is_valid_initial_command(conn, conn->incoming_cmd)) {
  3264. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  3265. connection_mark_for_close(TO_CONN(conn));
  3266. return 0;
  3267. }
  3268. if (data_len >= UINT32_MAX) {
  3269. connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
  3270. connection_mark_for_close(TO_CONN(conn));
  3271. return 0;
  3272. }
  3273. /* XXXX Why is this not implemented as a table like the GETINFO
  3274. * items are? Even handling the plus signs at the beginnings of
  3275. * commands wouldn't be very hard with proper macros. */
  3276. cmd_data_len = (uint32_t)data_len;
  3277. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  3278. if (handle_control_setconf(conn, cmd_data_len, args))
  3279. return -1;
  3280. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  3281. if (handle_control_resetconf(conn, cmd_data_len, args))
  3282. return -1;
  3283. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  3284. if (handle_control_getconf(conn, cmd_data_len, args))
  3285. return -1;
  3286. } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
  3287. if (handle_control_loadconf(conn, cmd_data_len, args))
  3288. return -1;
  3289. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  3290. if (handle_control_setevents(conn, cmd_data_len, args))
  3291. return -1;
  3292. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  3293. if (handle_control_authenticate(conn, cmd_data_len, args))
  3294. return -1;
  3295. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  3296. if (handle_control_saveconf(conn, cmd_data_len, args))
  3297. return -1;
  3298. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  3299. if (handle_control_signal(conn, cmd_data_len, args))
  3300. return -1;
  3301. } else if (!strcasecmp(conn->incoming_cmd, "TAKEOWNERSHIP")) {
  3302. if (handle_control_takeownership(conn, cmd_data_len, args))
  3303. return -1;
  3304. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  3305. if (handle_control_mapaddress(conn, cmd_data_len, args))
  3306. return -1;
  3307. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  3308. if (handle_control_getinfo(conn, cmd_data_len, args))
  3309. return -1;
  3310. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  3311. if (handle_control_extendcircuit(conn, cmd_data_len, args))
  3312. return -1;
  3313. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  3314. if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
  3315. return -1;
  3316. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  3317. connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
  3318. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  3319. if (handle_control_attachstream(conn, cmd_data_len, args))
  3320. return -1;
  3321. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  3322. if (handle_control_postdescriptor(conn, cmd_data_len, args))
  3323. return -1;
  3324. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  3325. if (handle_control_redirectstream(conn, cmd_data_len, args))
  3326. return -1;
  3327. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  3328. if (handle_control_closestream(conn, cmd_data_len, args))
  3329. return -1;
  3330. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  3331. if (handle_control_closecircuit(conn, cmd_data_len, args))
  3332. return -1;
  3333. } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
  3334. if (handle_control_usefeature(conn, cmd_data_len, args))
  3335. return -1;
  3336. } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
  3337. if (handle_control_resolve(conn, cmd_data_len, args))
  3338. return -1;
  3339. } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
  3340. if (handle_control_protocolinfo(conn, cmd_data_len, args))
  3341. return -1;
  3342. } else if (!strcasecmp(conn->incoming_cmd, "AUTHCHALLENGE")) {
  3343. if (handle_control_authchallenge(conn, cmd_data_len, args))
  3344. return -1;
  3345. } else if (!strcasecmp(conn->incoming_cmd, "DROPGUARDS")) {
  3346. if (handle_control_dropguards(conn, cmd_data_len, args))
  3347. return -1;
  3348. } else if (!strcasecmp(conn->incoming_cmd, "HSFETCH")) {
  3349. if (handle_control_hsfetch(conn, cmd_data_len, args))
  3350. return -1;
  3351. } else {
  3352. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  3353. conn->incoming_cmd);
  3354. }
  3355. conn->incoming_cmd_cur_len = 0;
  3356. goto again;
  3357. }
  3358. /** Something major has happened to circuit <b>circ</b>: tell any
  3359. * interested control connections. */
  3360. int
  3361. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
  3362. int reason_code)
  3363. {
  3364. const char *status;
  3365. char reasons[64] = "";
  3366. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  3367. return 0;
  3368. tor_assert(circ);
  3369. switch (tp)
  3370. {
  3371. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  3372. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  3373. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  3374. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  3375. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  3376. default:
  3377. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3378. tor_fragile_assert();
  3379. return 0;
  3380. }
  3381. if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
  3382. const char *reason_str = circuit_end_reason_to_control_string(reason_code);
  3383. char unk_reason_buf[16];
  3384. if (!reason_str) {
  3385. tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
  3386. reason_str = unk_reason_buf;
  3387. }
  3388. if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
  3389. tor_snprintf(reasons, sizeof(reasons),
  3390. " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
  3391. } else {
  3392. tor_snprintf(reasons, sizeof(reasons),
  3393. " REASON=%s", reason_str);
  3394. }
  3395. }
  3396. {
  3397. char *circdesc = circuit_describe_status_for_controller(circ);
  3398. const char *sp = strlen(circdesc) ? " " : "";
  3399. send_control_event(EVENT_CIRCUIT_STATUS, ALL_FORMATS,
  3400. "650 CIRC %lu %s%s%s%s\r\n",
  3401. (unsigned long)circ->global_identifier,
  3402. status, sp,
  3403. circdesc,
  3404. reasons);
  3405. tor_free(circdesc);
  3406. }
  3407. return 0;
  3408. }
  3409. /** Something minor has happened to circuit <b>circ</b>: tell any
  3410. * interested control connections. */
  3411. static int
  3412. control_event_circuit_status_minor(origin_circuit_t *circ,
  3413. circuit_status_minor_event_t e,
  3414. int purpose, const struct timeval *tv)
  3415. {
  3416. const char *event_desc;
  3417. char event_tail[160] = "";
  3418. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
  3419. return 0;
  3420. tor_assert(circ);
  3421. switch (e)
  3422. {
  3423. case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
  3424. event_desc = "PURPOSE_CHANGED";
  3425. {
  3426. /* event_tail can currently be up to 68 chars long */
  3427. const char *hs_state_str =
  3428. circuit_purpose_to_controller_hs_state_string(purpose);
  3429. tor_snprintf(event_tail, sizeof(event_tail),
  3430. " OLD_PURPOSE=%s%s%s",
  3431. circuit_purpose_to_controller_string(purpose),
  3432. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  3433. (hs_state_str != NULL) ? hs_state_str : "");
  3434. }
  3435. break;
  3436. case CIRC_MINOR_EVENT_CANNIBALIZED:
  3437. event_desc = "CANNIBALIZED";
  3438. {
  3439. /* event_tail can currently be up to 130 chars long */
  3440. const char *hs_state_str =
  3441. circuit_purpose_to_controller_hs_state_string(purpose);
  3442. const struct timeval *old_timestamp_began = tv;
  3443. char tbuf[ISO_TIME_USEC_LEN+1];
  3444. format_iso_time_nospace_usec(tbuf, old_timestamp_began);
  3445. tor_snprintf(event_tail, sizeof(event_tail),
  3446. " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
  3447. circuit_purpose_to_controller_string(purpose),
  3448. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  3449. (hs_state_str != NULL) ? hs_state_str : "",
  3450. tbuf);
  3451. }
  3452. break;
  3453. default:
  3454. log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
  3455. tor_fragile_assert();
  3456. return 0;
  3457. }
  3458. {
  3459. char *circdesc = circuit_describe_status_for_controller(circ);
  3460. const char *sp = strlen(circdesc) ? " " : "";
  3461. send_control_event(EVENT_CIRCUIT_STATUS_MINOR, ALL_FORMATS,
  3462. "650 CIRC_MINOR %lu %s%s%s%s\r\n",
  3463. (unsigned long)circ->global_identifier,
  3464. event_desc, sp,
  3465. circdesc,
  3466. event_tail);
  3467. tor_free(circdesc);
  3468. }
  3469. return 0;
  3470. }
  3471. /**
  3472. * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
  3473. * interested controllers.
  3474. */
  3475. int
  3476. control_event_circuit_purpose_changed(origin_circuit_t *circ,
  3477. int old_purpose)
  3478. {
  3479. return control_event_circuit_status_minor(circ,
  3480. CIRC_MINOR_EVENT_PURPOSE_CHANGED,
  3481. old_purpose,
  3482. NULL);
  3483. }
  3484. /**
  3485. * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
  3486. * created-time from <b>old_tv_created</b>: tell any interested controllers.
  3487. */
  3488. int
  3489. control_event_circuit_cannibalized(origin_circuit_t *circ,
  3490. int old_purpose,
  3491. const struct timeval *old_tv_created)
  3492. {
  3493. return control_event_circuit_status_minor(circ,
  3494. CIRC_MINOR_EVENT_CANNIBALIZED,
  3495. old_purpose,
  3496. old_tv_created);
  3497. }
  3498. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  3499. * <b>buf</b>, determine the address:port combination requested on
  3500. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  3501. * failure. */
  3502. static int
  3503. write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
  3504. {
  3505. char buf2[256];
  3506. if (conn->chosen_exit_name)
  3507. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  3508. return -1;
  3509. if (!conn->socks_request)
  3510. return -1;
  3511. if (tor_snprintf(buf, len, "%s%s%s:%d",
  3512. conn->socks_request->address,
  3513. conn->chosen_exit_name ? buf2 : "",
  3514. !conn->chosen_exit_name && connection_edge_is_rendezvous_stream(
  3515. ENTRY_TO_EDGE_CONN(conn)) ? ".onion" : "",
  3516. conn->socks_request->port)<0)
  3517. return -1;
  3518. return 0;
  3519. }
  3520. /** Something has happened to the stream associated with AP connection
  3521. * <b>conn</b>: tell any interested control connections. */
  3522. int
  3523. control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
  3524. int reason_code)
  3525. {
  3526. char reason_buf[64];
  3527. char addrport_buf[64];
  3528. const char *status;
  3529. circuit_t *circ;
  3530. origin_circuit_t *origin_circ = NULL;
  3531. char buf[256];
  3532. const char *purpose = "";
  3533. tor_assert(conn->socks_request);
  3534. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  3535. return 0;
  3536. if (tp == STREAM_EVENT_CLOSED &&
  3537. (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
  3538. return 0;
  3539. write_stream_target_to_buf(conn, buf, sizeof(buf));
  3540. reason_buf[0] = '\0';
  3541. switch (tp)
  3542. {
  3543. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  3544. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  3545. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  3546. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  3547. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  3548. case STREAM_EVENT_NEW: status = "NEW"; break;
  3549. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  3550. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  3551. case STREAM_EVENT_REMAP: status = "REMAP"; break;
  3552. default:
  3553. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3554. return 0;
  3555. }
  3556. if (reason_code && (tp == STREAM_EVENT_FAILED ||
  3557. tp == STREAM_EVENT_CLOSED ||
  3558. tp == STREAM_EVENT_FAILED_RETRIABLE)) {
  3559. const char *reason_str = stream_end_reason_to_control_string(reason_code);
  3560. char *r = NULL;
  3561. if (!reason_str) {
  3562. tor_asprintf(&r, " UNKNOWN_%d", reason_code);
  3563. reason_str = r;
  3564. }
  3565. if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
  3566. tor_snprintf(reason_buf, sizeof(reason_buf),
  3567. " REASON=END REMOTE_REASON=%s", reason_str);
  3568. else
  3569. tor_snprintf(reason_buf, sizeof(reason_buf),
  3570. " REASON=%s", reason_str);
  3571. tor_free(r);
  3572. } else if (reason_code && tp == STREAM_EVENT_REMAP) {
  3573. switch (reason_code) {
  3574. case REMAP_STREAM_SOURCE_CACHE:
  3575. strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
  3576. break;
  3577. case REMAP_STREAM_SOURCE_EXIT:
  3578. strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
  3579. break;
  3580. default:
  3581. tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
  3582. reason_code);
  3583. /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
  3584. break;
  3585. }
  3586. }
  3587. if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
  3588. /*
  3589. * When the control conn is an AF_UNIX socket and we have no address,
  3590. * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
  3591. * dnsserv.c.
  3592. */
  3593. if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
  3594. tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
  3595. ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
  3596. } else {
  3597. /*
  3598. * else leave it blank so control on AF_UNIX doesn't need to make
  3599. * something up.
  3600. */
  3601. addrport_buf[0] = '\0';
  3602. }
  3603. } else {
  3604. addrport_buf[0] = '\0';
  3605. }
  3606. if (tp == STREAM_EVENT_NEW_RESOLVE) {
  3607. purpose = " PURPOSE=DNS_REQUEST";
  3608. } else if (tp == STREAM_EVENT_NEW) {
  3609. if (conn->use_begindir) {
  3610. connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
  3611. int linked_dir_purpose = -1;
  3612. if (linked && linked->type == CONN_TYPE_DIR)
  3613. linked_dir_purpose = linked->purpose;
  3614. if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
  3615. purpose = " PURPOSE=DIR_UPLOAD";
  3616. else
  3617. purpose = " PURPOSE=DIR_FETCH";
  3618. } else
  3619. purpose = " PURPOSE=USER";
  3620. }
  3621. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  3622. if (circ && CIRCUIT_IS_ORIGIN(circ))
  3623. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  3624. send_control_event(EVENT_STREAM_STATUS, ALL_FORMATS,
  3625. "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
  3626. U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
  3627. status,
  3628. origin_circ?
  3629. (unsigned long)origin_circ->global_identifier : 0ul,
  3630. buf, reason_buf, addrport_buf, purpose);
  3631. /* XXX need to specify its intended exit, etc? */
  3632. return 0;
  3633. }
  3634. /** Figure out the best name for the target router of an OR connection
  3635. * <b>conn</b>, and write it into the <b>len</b>-character buffer
  3636. * <b>name</b>. */
  3637. static void
  3638. orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
  3639. {
  3640. const node_t *node = node_get_by_id(conn->identity_digest);
  3641. if (node) {
  3642. tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
  3643. node_get_verbose_nickname(node, name);
  3644. } else if (! tor_digest_is_zero(conn->identity_digest)) {
  3645. name[0] = '$';
  3646. base16_encode(name+1, len-1, conn->identity_digest,
  3647. DIGEST_LEN);
  3648. } else {
  3649. tor_snprintf(name, len, "%s:%d",
  3650. conn->base_.address, conn->base_.port);
  3651. }
  3652. }
  3653. /** Called when the status of an OR connection <b>conn</b> changes: tell any
  3654. * interested control connections. <b>tp</b> is the new status for the
  3655. * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
  3656. * may be the reason why.
  3657. */
  3658. int
  3659. control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
  3660. int reason)
  3661. {
  3662. int ncircs = 0;
  3663. const char *status;
  3664. char name[128];
  3665. char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
  3666. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  3667. return 0;
  3668. switch (tp)
  3669. {
  3670. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  3671. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  3672. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  3673. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  3674. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  3675. default:
  3676. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3677. return 0;
  3678. }
  3679. if (conn->chan) {
  3680. ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
  3681. } else {
  3682. ncircs = 0;
  3683. }
  3684. ncircs += connection_or_get_num_circuits(conn);
  3685. if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
  3686. tor_snprintf(ncircs_buf, sizeof(ncircs_buf), " NCIRCS=%d", ncircs);
  3687. }
  3688. orconn_target_get_name(name, sizeof(name), conn);
  3689. send_control_event(EVENT_OR_CONN_STATUS, ALL_FORMATS,
  3690. "650 ORCONN %s %s%s%s%s ID="U64_FORMAT"\r\n",
  3691. name, status,
  3692. reason ? " REASON=" : "",
  3693. orconn_end_reason_to_control_string(reason),
  3694. ncircs_buf,
  3695. U64_PRINTF_ARG(conn->base_.global_identifier));
  3696. return 0;
  3697. }
  3698. /**
  3699. * Print out STREAM_BW event for a single conn
  3700. */
  3701. int
  3702. control_event_stream_bandwidth(edge_connection_t *edge_conn)
  3703. {
  3704. circuit_t *circ;
  3705. origin_circuit_t *ocirc;
  3706. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  3707. if (!edge_conn->n_read && !edge_conn->n_written)
  3708. return 0;
  3709. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  3710. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  3711. U64_PRINTF_ARG(edge_conn->base_.global_identifier),
  3712. (unsigned long)edge_conn->n_read,
  3713. (unsigned long)edge_conn->n_written);
  3714. circ = circuit_get_by_edge_conn(edge_conn);
  3715. if (circ && CIRCUIT_IS_ORIGIN(circ)) {
  3716. ocirc = TO_ORIGIN_CIRCUIT(circ);
  3717. ocirc->n_read_circ_bw += edge_conn->n_read;
  3718. ocirc->n_written_circ_bw += edge_conn->n_written;
  3719. }
  3720. edge_conn->n_written = edge_conn->n_read = 0;
  3721. }
  3722. return 0;
  3723. }
  3724. /** A second or more has elapsed: tell any interested control
  3725. * connections how much bandwidth streams have used. */
  3726. int
  3727. control_event_stream_bandwidth_used(void)
  3728. {
  3729. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  3730. smartlist_t *conns = get_connection_array();
  3731. edge_connection_t *edge_conn;
  3732. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
  3733. {
  3734. if (conn->type != CONN_TYPE_AP)
  3735. continue;
  3736. edge_conn = TO_EDGE_CONN(conn);
  3737. if (!edge_conn->n_read && !edge_conn->n_written)
  3738. continue;
  3739. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  3740. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  3741. U64_PRINTF_ARG(edge_conn->base_.global_identifier),
  3742. (unsigned long)edge_conn->n_read,
  3743. (unsigned long)edge_conn->n_written);
  3744. edge_conn->n_written = edge_conn->n_read = 0;
  3745. }
  3746. SMARTLIST_FOREACH_END(conn);
  3747. }
  3748. return 0;
  3749. }
  3750. /** A second or more has elapsed: tell any interested control connections
  3751. * how much bandwidth origin circuits have used. */
  3752. int
  3753. control_event_circ_bandwidth_used(void)
  3754. {
  3755. origin_circuit_t *ocirc;
  3756. if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
  3757. return 0;
  3758. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  3759. if (!CIRCUIT_IS_ORIGIN(circ))
  3760. continue;
  3761. ocirc = TO_ORIGIN_CIRCUIT(circ);
  3762. if (!ocirc->n_read_circ_bw && !ocirc->n_written_circ_bw)
  3763. continue;
  3764. send_control_event(EVENT_CIRC_BANDWIDTH_USED, ALL_FORMATS,
  3765. "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu\r\n",
  3766. ocirc->global_identifier,
  3767. (unsigned long)ocirc->n_read_circ_bw,
  3768. (unsigned long)ocirc->n_written_circ_bw);
  3769. ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
  3770. }
  3771. SMARTLIST_FOREACH_END(circ);
  3772. return 0;
  3773. }
  3774. /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
  3775. * bandwidth counters. */
  3776. int
  3777. control_event_conn_bandwidth(connection_t *conn)
  3778. {
  3779. const char *conn_type_str;
  3780. if (!get_options()->TestingEnableConnBwEvent ||
  3781. !EVENT_IS_INTERESTING(EVENT_CONN_BW))
  3782. return 0;
  3783. if (!conn->n_read_conn_bw && !conn->n_written_conn_bw)
  3784. return 0;
  3785. switch (conn->type) {
  3786. case CONN_TYPE_OR:
  3787. conn_type_str = "OR";
  3788. break;
  3789. case CONN_TYPE_DIR:
  3790. conn_type_str = "DIR";
  3791. break;
  3792. case CONN_TYPE_EXIT:
  3793. conn_type_str = "EXIT";
  3794. break;
  3795. default:
  3796. return 0;
  3797. }
  3798. send_control_event(EVENT_CONN_BW, ALL_FORMATS,
  3799. "650 CONN_BW ID="U64_FORMAT" TYPE=%s "
  3800. "READ=%lu WRITTEN=%lu\r\n",
  3801. U64_PRINTF_ARG(conn->global_identifier),
  3802. conn_type_str,
  3803. (unsigned long)conn->n_read_conn_bw,
  3804. (unsigned long)conn->n_written_conn_bw);
  3805. conn->n_written_conn_bw = conn->n_read_conn_bw = 0;
  3806. return 0;
  3807. }
  3808. /** A second or more has elapsed: tell any interested control
  3809. * connections how much bandwidth connections have used. */
  3810. int
  3811. control_event_conn_bandwidth_used(void)
  3812. {
  3813. if (get_options()->TestingEnableConnBwEvent &&
  3814. EVENT_IS_INTERESTING(EVENT_CONN_BW)) {
  3815. SMARTLIST_FOREACH(get_connection_array(), connection_t *, conn,
  3816. control_event_conn_bandwidth(conn));
  3817. }
  3818. return 0;
  3819. }
  3820. /** Helper: iterate over cell statistics of <b>circ</b> and sum up added
  3821. * cells, removed cells, and waiting times by cell command and direction.
  3822. * Store results in <b>cell_stats</b>. Free cell statistics of the
  3823. * circuit afterwards. */
  3824. void
  3825. sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
  3826. {
  3827. memset(cell_stats, 0, sizeof(cell_stats_t));
  3828. SMARTLIST_FOREACH_BEGIN(circ->testing_cell_stats,
  3829. testing_cell_stats_entry_t *, ent) {
  3830. tor_assert(ent->command <= CELL_COMMAND_MAX_);
  3831. if (!ent->removed && !ent->exitward) {
  3832. cell_stats->added_cells_appward[ent->command] += 1;
  3833. } else if (!ent->removed && ent->exitward) {
  3834. cell_stats->added_cells_exitward[ent->command] += 1;
  3835. } else if (!ent->exitward) {
  3836. cell_stats->removed_cells_appward[ent->command] += 1;
  3837. cell_stats->total_time_appward[ent->command] += ent->waiting_time * 10;
  3838. } else {
  3839. cell_stats->removed_cells_exitward[ent->command] += 1;
  3840. cell_stats->total_time_exitward[ent->command] += ent->waiting_time * 10;
  3841. }
  3842. tor_free(ent);
  3843. } SMARTLIST_FOREACH_END(ent);
  3844. smartlist_free(circ->testing_cell_stats);
  3845. circ->testing_cell_stats = NULL;
  3846. }
  3847. /** Helper: append a cell statistics string to <code>event_parts</code>,
  3848. * prefixed with <code>key</code>=. Statistics consist of comma-separated
  3849. * key:value pairs with lower-case command strings as keys and cell
  3850. * numbers or total waiting times as values. A key:value pair is included
  3851. * if the entry in <code>include_if_non_zero</code> is not zero, but with
  3852. * the (possibly zero) entry from <code>number_to_include</code>. Both
  3853. * arrays are expected to have a length of CELL_COMMAND_MAX_ + 1. If no
  3854. * entry in <code>include_if_non_zero</code> is positive, no string will
  3855. * be added to <code>event_parts</code>. */
  3856. void
  3857. append_cell_stats_by_command(smartlist_t *event_parts, const char *key,
  3858. const uint64_t *include_if_non_zero,
  3859. const uint64_t *number_to_include)
  3860. {
  3861. smartlist_t *key_value_strings = smartlist_new();
  3862. int i;
  3863. for (i = 0; i <= CELL_COMMAND_MAX_; i++) {
  3864. if (include_if_non_zero[i] > 0) {
  3865. smartlist_add_asprintf(key_value_strings, "%s:"U64_FORMAT,
  3866. cell_command_to_string(i),
  3867. U64_PRINTF_ARG(number_to_include[i]));
  3868. }
  3869. }
  3870. if (smartlist_len(key_value_strings) > 0) {
  3871. char *joined = smartlist_join_strings(key_value_strings, ",", 0, NULL);
  3872. smartlist_add_asprintf(event_parts, "%s=%s", key, joined);
  3873. SMARTLIST_FOREACH(key_value_strings, char *, cp, tor_free(cp));
  3874. tor_free(joined);
  3875. }
  3876. smartlist_free(key_value_strings);
  3877. }
  3878. /** Helper: format <b>cell_stats</b> for <b>circ</b> for inclusion in a
  3879. * CELL_STATS event and write result string to <b>event_string</b>. */
  3880. void
  3881. format_cell_stats(char **event_string, circuit_t *circ,
  3882. cell_stats_t *cell_stats)
  3883. {
  3884. smartlist_t *event_parts = smartlist_new();
  3885. if (CIRCUIT_IS_ORIGIN(circ)) {
  3886. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  3887. smartlist_add_asprintf(event_parts, "ID=%lu",
  3888. (unsigned long)ocirc->global_identifier);
  3889. } else if (TO_OR_CIRCUIT(circ)->p_chan) {
  3890. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  3891. smartlist_add_asprintf(event_parts, "InboundQueue=%lu",
  3892. (unsigned long)or_circ->p_circ_id);
  3893. smartlist_add_asprintf(event_parts, "InboundConn="U64_FORMAT,
  3894. U64_PRINTF_ARG(or_circ->p_chan->global_identifier));
  3895. append_cell_stats_by_command(event_parts, "InboundAdded",
  3896. cell_stats->added_cells_appward,
  3897. cell_stats->added_cells_appward);
  3898. append_cell_stats_by_command(event_parts, "InboundRemoved",
  3899. cell_stats->removed_cells_appward,
  3900. cell_stats->removed_cells_appward);
  3901. append_cell_stats_by_command(event_parts, "InboundTime",
  3902. cell_stats->removed_cells_appward,
  3903. cell_stats->total_time_appward);
  3904. }
  3905. if (circ->n_chan) {
  3906. smartlist_add_asprintf(event_parts, "OutboundQueue=%lu",
  3907. (unsigned long)circ->n_circ_id);
  3908. smartlist_add_asprintf(event_parts, "OutboundConn="U64_FORMAT,
  3909. U64_PRINTF_ARG(circ->n_chan->global_identifier));
  3910. append_cell_stats_by_command(event_parts, "OutboundAdded",
  3911. cell_stats->added_cells_exitward,
  3912. cell_stats->added_cells_exitward);
  3913. append_cell_stats_by_command(event_parts, "OutboundRemoved",
  3914. cell_stats->removed_cells_exitward,
  3915. cell_stats->removed_cells_exitward);
  3916. append_cell_stats_by_command(event_parts, "OutboundTime",
  3917. cell_stats->removed_cells_exitward,
  3918. cell_stats->total_time_exitward);
  3919. }
  3920. *event_string = smartlist_join_strings(event_parts, " ", 0, NULL);
  3921. SMARTLIST_FOREACH(event_parts, char *, cp, tor_free(cp));
  3922. smartlist_free(event_parts);
  3923. }
  3924. /** A second or more has elapsed: tell any interested control connection
  3925. * how many cells have been processed for a given circuit. */
  3926. int
  3927. control_event_circuit_cell_stats(void)
  3928. {
  3929. cell_stats_t *cell_stats;
  3930. char *event_string;
  3931. if (!get_options()->TestingEnableCellStatsEvent ||
  3932. !EVENT_IS_INTERESTING(EVENT_CELL_STATS))
  3933. return 0;
  3934. cell_stats = tor_malloc(sizeof(cell_stats_t));;
  3935. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  3936. if (!circ->testing_cell_stats)
  3937. continue;
  3938. sum_up_cell_stats_by_command(circ, cell_stats);
  3939. format_cell_stats(&event_string, circ, cell_stats);
  3940. send_control_event(EVENT_CELL_STATS, ALL_FORMATS,
  3941. "650 CELL_STATS %s\r\n", event_string);
  3942. tor_free(event_string);
  3943. }
  3944. SMARTLIST_FOREACH_END(circ);
  3945. tor_free(cell_stats);
  3946. return 0;
  3947. }
  3948. /** Tokens in <b>bucket</b> have been refilled: the read bucket was empty
  3949. * for <b>read_empty_time</b> millis, the write bucket was empty for
  3950. * <b>write_empty_time</b> millis, and buckets were last refilled
  3951. * <b>milliseconds_elapsed</b> millis ago. Only emit TB_EMPTY event if
  3952. * either read or write bucket have been empty before. */
  3953. int
  3954. control_event_tb_empty(const char *bucket, uint32_t read_empty_time,
  3955. uint32_t write_empty_time,
  3956. int milliseconds_elapsed)
  3957. {
  3958. if (get_options()->TestingEnableTbEmptyEvent &&
  3959. EVENT_IS_INTERESTING(EVENT_TB_EMPTY) &&
  3960. (read_empty_time > 0 || write_empty_time > 0)) {
  3961. send_control_event(EVENT_TB_EMPTY, ALL_FORMATS,
  3962. "650 TB_EMPTY %s READ=%d WRITTEN=%d "
  3963. "LAST=%d\r\n",
  3964. bucket, read_empty_time, write_empty_time,
  3965. milliseconds_elapsed);
  3966. }
  3967. return 0;
  3968. }
  3969. /* about 5 minutes worth. */
  3970. #define N_BW_EVENTS_TO_CACHE 300
  3971. /* Index into cached_bw_events to next write. */
  3972. static int next_measurement_idx = 0;
  3973. /* number of entries set in n_measurements */
  3974. static int n_measurements = 0;
  3975. static struct cached_bw_event_s {
  3976. uint32_t n_read;
  3977. uint32_t n_written;
  3978. } cached_bw_events[N_BW_EVENTS_TO_CACHE];
  3979. /** A second or more has elapsed: tell any interested control
  3980. * connections how much bandwidth we used. */
  3981. int
  3982. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  3983. {
  3984. cached_bw_events[next_measurement_idx].n_read = n_read;
  3985. cached_bw_events[next_measurement_idx].n_written = n_written;
  3986. if (++next_measurement_idx == N_BW_EVENTS_TO_CACHE)
  3987. next_measurement_idx = 0;
  3988. if (n_measurements < N_BW_EVENTS_TO_CACHE)
  3989. ++n_measurements;
  3990. if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
  3991. send_control_event(EVENT_BANDWIDTH_USED, ALL_FORMATS,
  3992. "650 BW %lu %lu\r\n",
  3993. (unsigned long)n_read,
  3994. (unsigned long)n_written);
  3995. }
  3996. return 0;
  3997. }
  3998. STATIC char *
  3999. get_bw_samples(void)
  4000. {
  4001. int i;
  4002. int idx = (next_measurement_idx + N_BW_EVENTS_TO_CACHE - n_measurements)
  4003. % N_BW_EVENTS_TO_CACHE;
  4004. tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
  4005. smartlist_t *elements = smartlist_new();
  4006. for (i = 0; i < n_measurements; ++i) {
  4007. tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
  4008. const struct cached_bw_event_s *bwe = &cached_bw_events[idx];
  4009. smartlist_add_asprintf(elements, "%u,%u",
  4010. (unsigned)bwe->n_read,
  4011. (unsigned)bwe->n_written);
  4012. idx = (idx + 1) % N_BW_EVENTS_TO_CACHE;
  4013. }
  4014. char *result = smartlist_join_strings(elements, " ", 0, NULL);
  4015. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  4016. smartlist_free(elements);
  4017. return result;
  4018. }
  4019. /** Called when we are sending a log message to the controllers: suspend
  4020. * sending further log messages to the controllers until we're done. Used by
  4021. * CONN_LOG_PROTECT. */
  4022. void
  4023. disable_control_logging(void)
  4024. {
  4025. ++disable_log_messages;
  4026. }
  4027. /** We're done sending a log message to the controllers: re-enable controller
  4028. * logging. Used by CONN_LOG_PROTECT. */
  4029. void
  4030. enable_control_logging(void)
  4031. {
  4032. if (--disable_log_messages < 0)
  4033. tor_assert(0);
  4034. }
  4035. /** We got a log message: tell any interested control connections. */
  4036. void
  4037. control_event_logmsg(int severity, uint32_t domain, const char *msg)
  4038. {
  4039. int event;
  4040. /* Don't even think of trying to add stuff to a buffer from a cpuworker
  4041. * thread. */
  4042. if (! in_main_thread())
  4043. return;
  4044. if (disable_log_messages)
  4045. return;
  4046. if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
  4047. severity <= LOG_NOTICE) {
  4048. char *esc = esc_for_log(msg);
  4049. ++disable_log_messages;
  4050. control_event_general_status(severity, "BUG REASON=%s", esc);
  4051. --disable_log_messages;
  4052. tor_free(esc);
  4053. }
  4054. event = log_severity_to_event(severity);
  4055. if (event >= 0 && EVENT_IS_INTERESTING(event)) {
  4056. char *b = NULL;
  4057. const char *s;
  4058. if (strchr(msg, '\n')) {
  4059. char *cp;
  4060. b = tor_strdup(msg);
  4061. for (cp = b; *cp; ++cp)
  4062. if (*cp == '\r' || *cp == '\n')
  4063. *cp = ' ';
  4064. }
  4065. switch (severity) {
  4066. case LOG_DEBUG: s = "DEBUG"; break;
  4067. case LOG_INFO: s = "INFO"; break;
  4068. case LOG_NOTICE: s = "NOTICE"; break;
  4069. case LOG_WARN: s = "WARN"; break;
  4070. case LOG_ERR: s = "ERR"; break;
  4071. default: s = "UnknownLogSeverity"; break;
  4072. }
  4073. ++disable_log_messages;
  4074. send_control_event(event, ALL_FORMATS, "650 %s %s\r\n", s, b?b:msg);
  4075. --disable_log_messages;
  4076. tor_free(b);
  4077. }
  4078. }
  4079. /** Called whenever we receive new router descriptors: tell any
  4080. * interested control connections. <b>routers</b> is a list of
  4081. * routerinfo_t's.
  4082. */
  4083. int
  4084. control_event_descriptors_changed(smartlist_t *routers)
  4085. {
  4086. char *msg;
  4087. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  4088. return 0;
  4089. {
  4090. smartlist_t *names = smartlist_new();
  4091. char *ids;
  4092. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  4093. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  4094. router_get_verbose_nickname(b, ri);
  4095. smartlist_add(names, b);
  4096. });
  4097. ids = smartlist_join_strings(names, " ", 0, NULL);
  4098. tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
  4099. send_control_event_string(EVENT_NEW_DESC, ALL_FORMATS, msg);
  4100. tor_free(ids);
  4101. tor_free(msg);
  4102. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  4103. smartlist_free(names);
  4104. }
  4105. return 0;
  4106. }
  4107. /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
  4108. * <b>expires</b> values less than 3 are special; see connection_edge.c. If
  4109. * <b>error</b> is non-NULL, it is an error code describing the failure
  4110. * mode of the mapping.
  4111. */
  4112. int
  4113. control_event_address_mapped(const char *from, const char *to, time_t expires,
  4114. const char *error, const int cached)
  4115. {
  4116. if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
  4117. return 0;
  4118. if (expires < 3 || expires == TIME_MAX)
  4119. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  4120. "650 ADDRMAP %s %s NEVER %s%s"
  4121. "CACHED=\"%s\"\r\n",
  4122. from, to, error?error:"", error?" ":"",
  4123. cached?"YES":"NO");
  4124. else {
  4125. char buf[ISO_TIME_LEN+1];
  4126. char buf2[ISO_TIME_LEN+1];
  4127. format_local_iso_time(buf,expires);
  4128. format_iso_time(buf2,expires);
  4129. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  4130. "650 ADDRMAP %s %s \"%s\""
  4131. " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
  4132. from, to, buf,
  4133. error?error:"", error?" ":"",
  4134. buf2, cached?"YES":"NO");
  4135. }
  4136. return 0;
  4137. }
  4138. /** The authoritative dirserver has received a new descriptor that
  4139. * has passed basic syntax checks and is properly self-signed.
  4140. *
  4141. * Notify any interested party of the new descriptor and what has
  4142. * been done with it, and also optionally give an explanation/reason. */
  4143. int
  4144. control_event_or_authdir_new_descriptor(const char *action,
  4145. const char *desc, size_t desclen,
  4146. const char *msg)
  4147. {
  4148. char firstline[1024];
  4149. char *buf;
  4150. size_t totallen;
  4151. char *esc = NULL;
  4152. size_t esclen;
  4153. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  4154. return 0;
  4155. tor_snprintf(firstline, sizeof(firstline),
  4156. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  4157. action,
  4158. msg ? msg : "");
  4159. /* Escape the server descriptor properly */
  4160. esclen = write_escaped_data(desc, desclen, &esc);
  4161. totallen = strlen(firstline) + esclen + 1;
  4162. buf = tor_malloc(totallen);
  4163. strlcpy(buf, firstline, totallen);
  4164. strlcpy(buf+strlen(firstline), esc, totallen);
  4165. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  4166. buf);
  4167. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  4168. "650 OK\r\n");
  4169. tor_free(esc);
  4170. tor_free(buf);
  4171. return 0;
  4172. }
  4173. /** Helper function for NS-style events. Constructs and sends an event
  4174. * of type <b>event</b> with string <b>event_string</b> out of the set of
  4175. * networkstatuses <b>statuses</b>. Currently it is used for NS events
  4176. * and NEWCONSENSUS events. */
  4177. static int
  4178. control_event_networkstatus_changed_helper(smartlist_t *statuses,
  4179. uint16_t event,
  4180. const char *event_string)
  4181. {
  4182. smartlist_t *strs;
  4183. char *s, *esc = NULL;
  4184. if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
  4185. return 0;
  4186. strs = smartlist_new();
  4187. smartlist_add(strs, tor_strdup("650+"));
  4188. smartlist_add(strs, tor_strdup(event_string));
  4189. smartlist_add(strs, tor_strdup("\r\n"));
  4190. SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
  4191. {
  4192. s = networkstatus_getinfo_helper_single(rs);
  4193. if (!s) continue;
  4194. smartlist_add(strs, s);
  4195. });
  4196. s = smartlist_join_strings(strs, "", 0, NULL);
  4197. write_escaped_data(s, strlen(s), &esc);
  4198. SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
  4199. smartlist_free(strs);
  4200. tor_free(s);
  4201. send_control_event_string(event, ALL_FORMATS, esc);
  4202. send_control_event_string(event, ALL_FORMATS,
  4203. "650 OK\r\n");
  4204. tor_free(esc);
  4205. return 0;
  4206. }
  4207. /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
  4208. * an NS event to any controller that cares. */
  4209. int
  4210. control_event_networkstatus_changed(smartlist_t *statuses)
  4211. {
  4212. return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
  4213. }
  4214. /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
  4215. * event consisting of an NS-style line for each relay in the consensus. */
  4216. int
  4217. control_event_newconsensus(const networkstatus_t *consensus)
  4218. {
  4219. if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
  4220. return 0;
  4221. return control_event_networkstatus_changed_helper(
  4222. consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
  4223. }
  4224. /** Called when we compute a new circuitbuildtimeout */
  4225. int
  4226. control_event_buildtimeout_set(buildtimeout_set_event_t type,
  4227. const char *args)
  4228. {
  4229. const char *type_string = NULL;
  4230. if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
  4231. return 0;
  4232. switch (type) {
  4233. case BUILDTIMEOUT_SET_EVENT_COMPUTED:
  4234. type_string = "COMPUTED";
  4235. break;
  4236. case BUILDTIMEOUT_SET_EVENT_RESET:
  4237. type_string = "RESET";
  4238. break;
  4239. case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
  4240. type_string = "SUSPENDED";
  4241. break;
  4242. case BUILDTIMEOUT_SET_EVENT_DISCARD:
  4243. type_string = "DISCARD";
  4244. break;
  4245. case BUILDTIMEOUT_SET_EVENT_RESUME:
  4246. type_string = "RESUME";
  4247. break;
  4248. default:
  4249. type_string = "UNKNOWN";
  4250. break;
  4251. }
  4252. send_control_event(EVENT_BUILDTIMEOUT_SET, ALL_FORMATS,
  4253. "650 BUILDTIMEOUT_SET %s %s\r\n",
  4254. type_string, args);
  4255. return 0;
  4256. }
  4257. /** Called when a signal has been processed from signal_callback */
  4258. int
  4259. control_event_signal(uintptr_t signal)
  4260. {
  4261. const char *signal_string = NULL;
  4262. if (!control_event_is_interesting(EVENT_SIGNAL))
  4263. return 0;
  4264. switch (signal) {
  4265. case SIGHUP:
  4266. signal_string = "RELOAD";
  4267. break;
  4268. case SIGUSR1:
  4269. signal_string = "DUMP";
  4270. break;
  4271. case SIGUSR2:
  4272. signal_string = "DEBUG";
  4273. break;
  4274. case SIGNEWNYM:
  4275. signal_string = "NEWNYM";
  4276. break;
  4277. case SIGCLEARDNSCACHE:
  4278. signal_string = "CLEARDNSCACHE";
  4279. break;
  4280. case SIGHEARTBEAT:
  4281. signal_string = "HEARTBEAT";
  4282. break;
  4283. default:
  4284. log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
  4285. (unsigned long)signal);
  4286. return -1;
  4287. }
  4288. send_control_event(EVENT_SIGNAL, ALL_FORMATS, "650 SIGNAL %s\r\n",
  4289. signal_string);
  4290. return 0;
  4291. }
  4292. /** Called when a single local_routerstatus_t has changed: Sends an NS event
  4293. * to any controller that cares. */
  4294. int
  4295. control_event_networkstatus_changed_single(const routerstatus_t *rs)
  4296. {
  4297. smartlist_t *statuses;
  4298. int r;
  4299. if (!EVENT_IS_INTERESTING(EVENT_NS))
  4300. return 0;
  4301. statuses = smartlist_new();
  4302. smartlist_add(statuses, (void*)rs);
  4303. r = control_event_networkstatus_changed(statuses);
  4304. smartlist_free(statuses);
  4305. return r;
  4306. }
  4307. /** Our own router descriptor has changed; tell any controllers that care.
  4308. */
  4309. int
  4310. control_event_my_descriptor_changed(void)
  4311. {
  4312. send_control_event(EVENT_DESCCHANGED, ALL_FORMATS, "650 DESCCHANGED\r\n");
  4313. return 0;
  4314. }
  4315. /** Helper: sends a status event where <b>type</b> is one of
  4316. * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
  4317. * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
  4318. * string corresponding to <b>args</b>. */
  4319. static int
  4320. control_event_status(int type, int severity, const char *format, va_list args)
  4321. {
  4322. char *user_buf = NULL;
  4323. char format_buf[160];
  4324. const char *status, *sev;
  4325. switch (type) {
  4326. case EVENT_STATUS_GENERAL:
  4327. status = "STATUS_GENERAL";
  4328. break;
  4329. case EVENT_STATUS_CLIENT:
  4330. status = "STATUS_CLIENT";
  4331. break;
  4332. case EVENT_STATUS_SERVER:
  4333. status = "STATUS_SERVER";
  4334. break;
  4335. default:
  4336. log_warn(LD_BUG, "Unrecognized status type %d", type);
  4337. return -1;
  4338. }
  4339. switch (severity) {
  4340. case LOG_NOTICE:
  4341. sev = "NOTICE";
  4342. break;
  4343. case LOG_WARN:
  4344. sev = "WARN";
  4345. break;
  4346. case LOG_ERR:
  4347. sev = "ERR";
  4348. break;
  4349. default:
  4350. log_warn(LD_BUG, "Unrecognized status severity %d", severity);
  4351. return -1;
  4352. }
  4353. if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
  4354. status, sev)<0) {
  4355. log_warn(LD_BUG, "Format string too long.");
  4356. return -1;
  4357. }
  4358. tor_vasprintf(&user_buf, format, args);
  4359. send_control_event(type, ALL_FORMATS, "%s %s\r\n", format_buf, user_buf);
  4360. tor_free(user_buf);
  4361. return 0;
  4362. }
  4363. /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
  4364. * by formatting the arguments using the printf-style <b>format</b>. */
  4365. int
  4366. control_event_general_status(int severity, const char *format, ...)
  4367. {
  4368. va_list ap;
  4369. int r;
  4370. if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
  4371. return 0;
  4372. va_start(ap, format);
  4373. r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
  4374. va_end(ap);
  4375. return r;
  4376. }
  4377. /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
  4378. * by formatting the arguments using the printf-style <b>format</b>. */
  4379. int
  4380. control_event_client_status(int severity, const char *format, ...)
  4381. {
  4382. va_list ap;
  4383. int r;
  4384. if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
  4385. return 0;
  4386. va_start(ap, format);
  4387. r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
  4388. va_end(ap);
  4389. return r;
  4390. }
  4391. /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
  4392. * by formatting the arguments using the printf-style <b>format</b>. */
  4393. int
  4394. control_event_server_status(int severity, const char *format, ...)
  4395. {
  4396. va_list ap;
  4397. int r;
  4398. if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
  4399. return 0;
  4400. va_start(ap, format);
  4401. r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
  4402. va_end(ap);
  4403. return r;
  4404. }
  4405. /** Called when the status of an entry guard with the given <b>nickname</b>
  4406. * and identity <b>digest</b> has changed to <b>status</b>: tells any
  4407. * controllers that care. */
  4408. int
  4409. control_event_guard(const char *nickname, const char *digest,
  4410. const char *status)
  4411. {
  4412. char hbuf[HEX_DIGEST_LEN+1];
  4413. base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
  4414. if (!EVENT_IS_INTERESTING(EVENT_GUARD))
  4415. return 0;
  4416. {
  4417. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  4418. const node_t *node = node_get_by_id(digest);
  4419. if (node) {
  4420. node_get_verbose_nickname(node, buf);
  4421. } else {
  4422. tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
  4423. }
  4424. send_control_event(EVENT_GUARD, ALL_FORMATS,
  4425. "650 GUARD ENTRY %s %s\r\n", buf, status);
  4426. }
  4427. return 0;
  4428. }
  4429. /** Called when a configuration option changes. This is generally triggered
  4430. * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
  4431. * a smartlist_t containing (key, value, ...) pairs in sequence.
  4432. * <b>value</b> can be NULL. */
  4433. int
  4434. control_event_conf_changed(const smartlist_t *elements)
  4435. {
  4436. int i;
  4437. char *result;
  4438. smartlist_t *lines;
  4439. if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) ||
  4440. smartlist_len(elements) == 0) {
  4441. return 0;
  4442. }
  4443. lines = smartlist_new();
  4444. for (i = 0; i < smartlist_len(elements); i += 2) {
  4445. char *k = smartlist_get(elements, i);
  4446. char *v = smartlist_get(elements, i+1);
  4447. if (v == NULL) {
  4448. smartlist_add_asprintf(lines, "650-%s", k);
  4449. } else {
  4450. smartlist_add_asprintf(lines, "650-%s=%s", k, v);
  4451. }
  4452. }
  4453. result = smartlist_join_strings(lines, "\r\n", 0, NULL);
  4454. send_control_event(EVENT_CONF_CHANGED, 0,
  4455. "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
  4456. tor_free(result);
  4457. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  4458. smartlist_free(lines);
  4459. return 0;
  4460. }
  4461. /** Helper: Return a newly allocated string containing a path to the
  4462. * file where we store our authentication cookie. */
  4463. char *
  4464. get_controller_cookie_file_name(void)
  4465. {
  4466. const or_options_t *options = get_options();
  4467. if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
  4468. return tor_strdup(options->CookieAuthFile);
  4469. } else {
  4470. return get_datadir_fname("control_auth_cookie");
  4471. }
  4472. }
  4473. /* Initialize the cookie-based authentication system of the
  4474. * ControlPort. If <b>enabled</b> is 0, then disable the cookie
  4475. * authentication system. */
  4476. int
  4477. init_control_cookie_authentication(int enabled)
  4478. {
  4479. char *fname = NULL;
  4480. int retval;
  4481. if (!enabled) {
  4482. authentication_cookie_is_set = 0;
  4483. return 0;
  4484. }
  4485. fname = get_controller_cookie_file_name();
  4486. retval = init_cookie_authentication(fname, "", /* no header */
  4487. AUTHENTICATION_COOKIE_LEN,
  4488. get_options()->CookieAuthFileGroupReadable,
  4489. &authentication_cookie,
  4490. &authentication_cookie_is_set);
  4491. tor_free(fname);
  4492. return retval;
  4493. }
  4494. /** A copy of the process specifier of Tor's owning controller, or
  4495. * NULL if this Tor instance is not currently owned by a process. */
  4496. static char *owning_controller_process_spec = NULL;
  4497. /** A process-termination monitor for Tor's owning controller, or NULL
  4498. * if this Tor instance is not currently owned by a process. */
  4499. static tor_process_monitor_t *owning_controller_process_monitor = NULL;
  4500. static void owning_controller_procmon_cb(void *unused) ATTR_NORETURN;
  4501. /** Process-termination monitor callback for Tor's owning controller
  4502. * process. */
  4503. static void
  4504. owning_controller_procmon_cb(void *unused)
  4505. {
  4506. (void)unused;
  4507. lost_owning_controller("process", "vanished");
  4508. }
  4509. /** Set <b>process_spec</b> as Tor's owning controller process.
  4510. * Exit on failure. */
  4511. void
  4512. monitor_owning_controller_process(const char *process_spec)
  4513. {
  4514. const char *msg;
  4515. tor_assert((owning_controller_process_spec == NULL) ==
  4516. (owning_controller_process_monitor == NULL));
  4517. if (owning_controller_process_spec != NULL) {
  4518. if ((process_spec != NULL) && !strcmp(process_spec,
  4519. owning_controller_process_spec)) {
  4520. /* Same process -- return now, instead of disposing of and
  4521. * recreating the process-termination monitor. */
  4522. return;
  4523. }
  4524. /* We are currently owned by a process, and we should no longer be
  4525. * owned by it. Free the process-termination monitor. */
  4526. tor_process_monitor_free(owning_controller_process_monitor);
  4527. owning_controller_process_monitor = NULL;
  4528. tor_free(owning_controller_process_spec);
  4529. owning_controller_process_spec = NULL;
  4530. }
  4531. tor_assert((owning_controller_process_spec == NULL) &&
  4532. (owning_controller_process_monitor == NULL));
  4533. if (process_spec == NULL)
  4534. return;
  4535. owning_controller_process_spec = tor_strdup(process_spec);
  4536. owning_controller_process_monitor =
  4537. tor_process_monitor_new(tor_libevent_get_base(),
  4538. owning_controller_process_spec,
  4539. LD_CONTROL,
  4540. owning_controller_procmon_cb, NULL,
  4541. &msg);
  4542. if (owning_controller_process_monitor == NULL) {
  4543. log_err(LD_BUG, "Couldn't create process-termination monitor for "
  4544. "owning controller: %s. Exiting.",
  4545. msg);
  4546. owning_controller_process_spec = NULL;
  4547. tor_cleanup();
  4548. exit(0);
  4549. }
  4550. }
  4551. /** Convert the name of a bootstrapping phase <b>s</b> into strings
  4552. * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
  4553. static int
  4554. bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
  4555. const char **summary)
  4556. {
  4557. switch (s) {
  4558. case BOOTSTRAP_STATUS_UNDEF:
  4559. *tag = "undef";
  4560. *summary = "Undefined";
  4561. break;
  4562. case BOOTSTRAP_STATUS_STARTING:
  4563. *tag = "starting";
  4564. *summary = "Starting";
  4565. break;
  4566. case BOOTSTRAP_STATUS_CONN_DIR:
  4567. *tag = "conn_dir";
  4568. *summary = "Connecting to directory server";
  4569. break;
  4570. case BOOTSTRAP_STATUS_HANDSHAKE:
  4571. *tag = "status_handshake";
  4572. *summary = "Finishing handshake";
  4573. break;
  4574. case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
  4575. *tag = "handshake_dir";
  4576. *summary = "Finishing handshake with directory server";
  4577. break;
  4578. case BOOTSTRAP_STATUS_ONEHOP_CREATE:
  4579. *tag = "onehop_create";
  4580. *summary = "Establishing an encrypted directory connection";
  4581. break;
  4582. case BOOTSTRAP_STATUS_REQUESTING_STATUS:
  4583. *tag = "requesting_status";
  4584. *summary = "Asking for networkstatus consensus";
  4585. break;
  4586. case BOOTSTRAP_STATUS_LOADING_STATUS:
  4587. *tag = "loading_status";
  4588. *summary = "Loading networkstatus consensus";
  4589. break;
  4590. case BOOTSTRAP_STATUS_LOADING_KEYS:
  4591. *tag = "loading_keys";
  4592. *summary = "Loading authority key certs";
  4593. break;
  4594. case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
  4595. *tag = "requesting_descriptors";
  4596. /* XXXX this appears to incorrectly report internal on most loads */
  4597. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  4598. "Asking for relay descriptors for internal paths" :
  4599. "Asking for relay descriptors";
  4600. break;
  4601. /* If we're sure there are no exits in the consensus,
  4602. * inform the controller by adding "internal"
  4603. * to the status summaries.
  4604. * (We only check this while loading descriptors,
  4605. * so we may not know in the earlier stages.)
  4606. * But if there are exits, we can't be sure whether
  4607. * we're creating internal or exit paths/circuits.
  4608. * XXXX Or should be use different tags or statuses
  4609. * for internal and exit/all? */
  4610. case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
  4611. *tag = "loading_descriptors";
  4612. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  4613. "Loading relay descriptors for internal paths" :
  4614. "Loading relay descriptors";
  4615. break;
  4616. case BOOTSTRAP_STATUS_CONN_OR:
  4617. *tag = "conn_or";
  4618. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  4619. "Connecting to the Tor network internally" :
  4620. "Connecting to the Tor network";
  4621. break;
  4622. case BOOTSTRAP_STATUS_HANDSHAKE_OR:
  4623. *tag = "handshake_or";
  4624. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  4625. "Finishing handshake with first hop of internal circuit" :
  4626. "Finishing handshake with first hop";
  4627. break;
  4628. case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
  4629. *tag = "circuit_create";
  4630. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  4631. "Establishing an internal Tor circuit" :
  4632. "Establishing a Tor circuit";
  4633. break;
  4634. case BOOTSTRAP_STATUS_DONE:
  4635. *tag = "done";
  4636. *summary = "Done";
  4637. break;
  4638. default:
  4639. // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
  4640. *tag = *summary = "unknown";
  4641. return -1;
  4642. }
  4643. return 0;
  4644. }
  4645. /** What percentage through the bootstrap process are we? We remember
  4646. * this so we can avoid sending redundant bootstrap status events, and
  4647. * so we can guess context for the bootstrap messages which are
  4648. * ambiguous. It starts at 'undef', but gets set to 'starting' while
  4649. * Tor initializes. */
  4650. static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
  4651. /** As bootstrap_percent, but holds the bootstrapping level at which we last
  4652. * logged a NOTICE-level message. We use this, plus BOOTSTRAP_PCT_INCREMENT,
  4653. * to avoid flooding the log with a new message every time we get a few more
  4654. * microdescriptors */
  4655. static int notice_bootstrap_percent = 0;
  4656. /** How many problems have we had getting to the next bootstrapping phase?
  4657. * These include failure to establish a connection to a Tor relay,
  4658. * failures to finish the TLS handshake, failures to validate the
  4659. * consensus document, etc. */
  4660. static int bootstrap_problems = 0;
  4661. /** We only tell the controller once we've hit a threshold of problems
  4662. * for the current phase. */
  4663. #define BOOTSTRAP_PROBLEM_THRESHOLD 10
  4664. /** When our bootstrapping progress level changes, but our bootstrapping
  4665. * status has not advanced, we only log at NOTICE when we have made at least
  4666. * this much progress.
  4667. */
  4668. #define BOOTSTRAP_PCT_INCREMENT 5
  4669. /** Called when Tor has made progress at bootstrapping its directory
  4670. * information and initial circuits.
  4671. *
  4672. * <b>status</b> is the new status, that is, what task we will be doing
  4673. * next. <b>progress</b> is zero if we just started this task, else it
  4674. * represents progress on the task.
  4675. *
  4676. * Return true if we logged a message at level NOTICE, and false otherwise.
  4677. */
  4678. int
  4679. control_event_bootstrap(bootstrap_status_t status, int progress)
  4680. {
  4681. const char *tag, *summary;
  4682. char buf[BOOTSTRAP_MSG_LEN];
  4683. if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
  4684. return 0; /* already bootstrapped; nothing to be done here. */
  4685. /* special case for handshaking status, since our TLS handshaking code
  4686. * can't distinguish what the connection is going to be for. */
  4687. if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
  4688. if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
  4689. status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
  4690. } else {
  4691. status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
  4692. }
  4693. }
  4694. if (status > bootstrap_percent ||
  4695. (progress && progress > bootstrap_percent)) {
  4696. int loglevel = LOG_NOTICE;
  4697. bootstrap_status_to_string(status, &tag, &summary);
  4698. if (status <= bootstrap_percent &&
  4699. (progress < notice_bootstrap_percent + BOOTSTRAP_PCT_INCREMENT)) {
  4700. /* We log the message at info if the status hasn't advanced, and if less
  4701. * than BOOTSTRAP_PCT_INCREMENT progress has been made.
  4702. */
  4703. loglevel = LOG_INFO;
  4704. }
  4705. tor_log(loglevel, LD_CONTROL,
  4706. "Bootstrapped %d%%: %s", progress ? progress : status, summary);
  4707. tor_snprintf(buf, sizeof(buf),
  4708. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
  4709. progress ? progress : status, tag, summary);
  4710. tor_snprintf(last_sent_bootstrap_message,
  4711. sizeof(last_sent_bootstrap_message),
  4712. "NOTICE %s", buf);
  4713. control_event_client_status(LOG_NOTICE, "%s", buf);
  4714. if (status > bootstrap_percent) {
  4715. bootstrap_percent = status; /* new milestone reached */
  4716. }
  4717. if (progress > bootstrap_percent) {
  4718. /* incremental progress within a milestone */
  4719. bootstrap_percent = progress;
  4720. bootstrap_problems = 0; /* Progress! Reset our problem counter. */
  4721. }
  4722. if (loglevel == LOG_NOTICE &&
  4723. bootstrap_percent > notice_bootstrap_percent) {
  4724. /* Remember that we gave a notice at this level. */
  4725. notice_bootstrap_percent = bootstrap_percent;
  4726. }
  4727. return loglevel == LOG_NOTICE;
  4728. }
  4729. return 0;
  4730. }
  4731. /** Called when Tor has failed to make bootstrapping progress in a way
  4732. * that indicates a problem. <b>warn</b> gives a hint as to why, and
  4733. * <b>reason</b> provides an "or_conn_end_reason" tag. <b>or_conn</b>
  4734. * is the connection that caused this problem.
  4735. */
  4736. MOCK_IMPL(void,
  4737. control_event_bootstrap_problem, (const char *warn, int reason,
  4738. or_connection_t *or_conn))
  4739. {
  4740. int status = bootstrap_percent;
  4741. const char *tag = "", *summary = "";
  4742. char buf[BOOTSTRAP_MSG_LEN];
  4743. const char *recommendation = "ignore";
  4744. int severity;
  4745. /* bootstrap_percent must not be in "undefined" state here. */
  4746. tor_assert(status >= 0);
  4747. if (or_conn->have_noted_bootstrap_problem)
  4748. return;
  4749. or_conn->have_noted_bootstrap_problem = 1;
  4750. if (bootstrap_percent == 100)
  4751. return; /* already bootstrapped; nothing to be done here. */
  4752. bootstrap_problems++;
  4753. if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
  4754. recommendation = "warn";
  4755. if (reason == END_OR_CONN_REASON_NO_ROUTE)
  4756. recommendation = "warn";
  4757. /* If we are using bridges and all our OR connections are now
  4758. closed, it means that we totally failed to connect to our
  4759. bridges. Throw a warning. */
  4760. if (get_options()->UseBridges && !any_other_active_or_conns(or_conn))
  4761. recommendation = "warn";
  4762. if (we_are_hibernating())
  4763. recommendation = "ignore";
  4764. while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
  4765. status--; /* find a recognized status string based on current progress */
  4766. status = bootstrap_percent; /* set status back to the actual number */
  4767. severity = !strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO;
  4768. log_fn(severity,
  4769. LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
  4770. "count %d; recommendation %s; host %s at %s:%d)",
  4771. status, summary, warn,
  4772. orconn_end_reason_to_control_string(reason),
  4773. bootstrap_problems, recommendation,
  4774. hex_str(or_conn->identity_digest, DIGEST_LEN),
  4775. or_conn->base_.address,
  4776. or_conn->base_.port);
  4777. connection_or_report_broken_states(severity, LD_HANDSHAKE);
  4778. tor_snprintf(buf, sizeof(buf),
  4779. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
  4780. "COUNT=%d RECOMMENDATION=%s HOSTID=\"%s\" HOSTADDR=\"%s:%d\"",
  4781. bootstrap_percent, tag, summary, warn,
  4782. orconn_end_reason_to_control_string(reason), bootstrap_problems,
  4783. recommendation,
  4784. hex_str(or_conn->identity_digest, DIGEST_LEN),
  4785. or_conn->base_.address,
  4786. (int)or_conn->base_.port);
  4787. tor_snprintf(last_sent_bootstrap_message,
  4788. sizeof(last_sent_bootstrap_message),
  4789. "WARN %s", buf);
  4790. control_event_client_status(LOG_WARN, "%s", buf);
  4791. }
  4792. /** We just generated a new summary of which countries we've seen clients
  4793. * from recently. Send a copy to the controller in case it wants to
  4794. * display it for the user. */
  4795. void
  4796. control_event_clients_seen(const char *controller_str)
  4797. {
  4798. send_control_event(EVENT_CLIENTS_SEEN, 0,
  4799. "650 CLIENTS_SEEN %s\r\n", controller_str);
  4800. }
  4801. /** A new pluggable transport called <b>transport_name</b> was
  4802. * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
  4803. * "server" or "client" depending on the mode of the pluggable
  4804. * transport.
  4805. * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
  4806. */
  4807. void
  4808. control_event_transport_launched(const char *mode, const char *transport_name,
  4809. tor_addr_t *addr, uint16_t port)
  4810. {
  4811. send_control_event(EVENT_TRANSPORT_LAUNCHED, ALL_FORMATS,
  4812. "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
  4813. mode, transport_name, fmt_addr(addr), port);
  4814. }
  4815. /** Convert rendezvous auth type to string for HS_DESC control events
  4816. */
  4817. const char *
  4818. rend_auth_type_to_string(rend_auth_type_t auth_type)
  4819. {
  4820. const char *str;
  4821. switch (auth_type) {
  4822. case REND_NO_AUTH:
  4823. str = "NO_AUTH";
  4824. break;
  4825. case REND_BASIC_AUTH:
  4826. str = "BASIC_AUTH";
  4827. break;
  4828. case REND_STEALTH_AUTH:
  4829. str = "STEALTH_AUTH";
  4830. break;
  4831. default:
  4832. str = "UNKNOWN";
  4833. }
  4834. return str;
  4835. }
  4836. /** Return a longname the node whose identity is <b>id_digest</b>. If
  4837. * node_get_by_id() returns NULL, base 16 encoding of <b>id_digest</b> is
  4838. * returned instead.
  4839. *
  4840. * This function is not thread-safe. Each call to this function invalidates
  4841. * previous values returned by this function.
  4842. */
  4843. MOCK_IMPL(const char *,
  4844. node_describe_longname_by_id,(const char *id_digest))
  4845. {
  4846. static char longname[MAX_VERBOSE_NICKNAME_LEN+1];
  4847. node_get_verbose_nickname_by_id(id_digest, longname);
  4848. return longname;
  4849. }
  4850. /** Return either the onion address if the given pointer is a non empty
  4851. * string else the unknown string. */
  4852. static const char *
  4853. rend_hsaddress_str_or_unknown(const char *onion_address)
  4854. {
  4855. static const char *str_unknown = "UNKNOWN";
  4856. const char *str_ret = str_unknown;
  4857. /* No valid pointer, unknown it is. */
  4858. if (!onion_address) {
  4859. goto end;
  4860. }
  4861. /* Empty onion address thus we don't know, unknown it is. */
  4862. if (onion_address[0] == '\0') {
  4863. goto end;
  4864. }
  4865. /* All checks are good so return the given onion address. */
  4866. str_ret = onion_address;
  4867. end:
  4868. return str_ret;
  4869. }
  4870. /** send HS_DESC requested event.
  4871. *
  4872. * <b>rend_query</b> is used to fetch requested onion address and auth type.
  4873. * <b>hs_dir</b> is the description of contacting hs directory.
  4874. * <b>desc_id_base32</b> is the ID of requested hs descriptor.
  4875. */
  4876. void
  4877. control_event_hs_descriptor_requested(const rend_data_t *rend_query,
  4878. const char *id_digest,
  4879. const char *desc_id_base32)
  4880. {
  4881. if (!id_digest || !rend_query || !desc_id_base32) {
  4882. log_warn(LD_BUG, "Called with rend_query==%p, "
  4883. "id_digest==%p, desc_id_base32==%p",
  4884. rend_query, id_digest, desc_id_base32);
  4885. return;
  4886. }
  4887. send_control_event(EVENT_HS_DESC, ALL_FORMATS,
  4888. "650 HS_DESC REQUESTED %s %s %s %s\r\n",
  4889. rend_hsaddress_str_or_unknown(rend_query->onion_address),
  4890. rend_auth_type_to_string(rend_query->auth_type),
  4891. node_describe_longname_by_id(id_digest),
  4892. desc_id_base32);
  4893. }
  4894. /** send HS_DESC event after got response from hs directory.
  4895. *
  4896. * NOTE: this is an internal function used by following functions:
  4897. * control_event_hs_descriptor_received
  4898. * control_event_hs_descriptor_failed
  4899. *
  4900. * So do not call this function directly.
  4901. */
  4902. void
  4903. control_event_hs_descriptor_receive_end(const char *action,
  4904. const char *onion_address,
  4905. rend_auth_type_t auth_type,
  4906. const char *id_digest,
  4907. const char *reason)
  4908. {
  4909. char *reason_field = NULL;
  4910. if (!action || !id_digest || !onion_address) {
  4911. log_warn(LD_BUG, "Called with action==%p, id_digest==%p "
  4912. "onion_address==%p", action, id_digest, onion_address);
  4913. return;
  4914. }
  4915. if (reason) {
  4916. tor_asprintf(&reason_field, " REASON=%s", reason);
  4917. }
  4918. send_control_event(EVENT_HS_DESC, ALL_FORMATS,
  4919. "650 HS_DESC %s %s %s %s%s\r\n",
  4920. action,
  4921. rend_hsaddress_str_or_unknown(onion_address),
  4922. rend_auth_type_to_string(auth_type),
  4923. node_describe_longname_by_id(id_digest),
  4924. reason_field ? reason_field : "");
  4925. tor_free(reason_field);
  4926. }
  4927. /** send HS_DESC RECEIVED event
  4928. *
  4929. * called when a we successfully received a hidden service descriptor.
  4930. */
  4931. void
  4932. control_event_hs_descriptor_received(const char *onion_address,
  4933. rend_auth_type_t auth_type,
  4934. const char *id_digest)
  4935. {
  4936. if (!id_digest) {
  4937. log_warn(LD_BUG, "Called with id_digest==%p", id_digest);
  4938. return;
  4939. }
  4940. control_event_hs_descriptor_receive_end("RECEIVED", onion_address,
  4941. auth_type, id_digest, NULL);
  4942. }
  4943. /** Send HS_DESC event to inform controller that query <b>rend_query</b>
  4944. * failed to retrieve hidden service descriptor identified by
  4945. * <b>id_digest</b>. If <b>reason</b> is not NULL, add it to REASON=
  4946. * field.
  4947. */
  4948. void
  4949. control_event_hs_descriptor_failed(const char *onion_address,
  4950. rend_auth_type_t auth_type,
  4951. const char *id_digest,
  4952. const char *reason)
  4953. {
  4954. if (!id_digest) {
  4955. log_warn(LD_BUG, "Called with id_digest==%p", id_digest);
  4956. return;
  4957. }
  4958. control_event_hs_descriptor_receive_end("FAILED", onion_address, auth_type,
  4959. id_digest, reason);
  4960. }
  4961. /** send HS_DESC_CONTENT event after completion of a successful fetch from
  4962. * hs directory. */
  4963. void
  4964. control_event_hs_descriptor_content(const char *onion_address,
  4965. const char *desc_id,
  4966. const char *hsdir_id_digest,
  4967. const char *content)
  4968. {
  4969. static const char *event_name = "HS_DESC_CONTENT";
  4970. char *esc_content = NULL;
  4971. if (!onion_address || !desc_id || !hsdir_id_digest || !content) {
  4972. log_warn(LD_BUG, "Called with onion_address==%p, desc_id==%p, "
  4973. "hsdir_id_digest==%p, content==%p", onion_address, desc_id,
  4974. hsdir_id_digest, content);
  4975. return;
  4976. }
  4977. write_escaped_data(content, strlen(content), &esc_content);
  4978. send_control_event(EVENT_HS_DESC_CONTENT, ALL_FORMATS,
  4979. "650+%s %s %s %s\r\n%s650 OK\r\n",
  4980. event_name,
  4981. rend_hsaddress_str_or_unknown(onion_address),
  4982. desc_id,
  4983. node_describe_longname_by_id(hsdir_id_digest),
  4984. esc_content);
  4985. tor_free(esc_content);
  4986. }
  4987. /** Free any leftover allocated memory of the control.c subsystem. */
  4988. void
  4989. control_free_all(void)
  4990. {
  4991. if (authentication_cookie) /* Free the auth cookie */
  4992. tor_free(authentication_cookie);
  4993. }
  4994. #ifdef TOR_UNIT_TESTS
  4995. /* For testing: change the value of global_event_mask */
  4996. void
  4997. control_testing_set_global_event_mask(uint64_t mask)
  4998. {
  4999. global_event_mask = mask;
  5000. }
  5001. #endif