control.c 156 KB

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