control.c 157 KB

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