control.c 176 KB

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