control.c 157 KB

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