control.c 157 KB

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