control.c 157 KB

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