control.c 135 KB

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