control.c 155 KB

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