control.c 173 KB

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