control.c 167 KB

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