control.c 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346
  1. /* Copyright 2004-2007 Roger Dingledine, Nick Mathewson. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. const char control_c_id[] =
  5. "$Id$";
  6. /**
  7. * \file control.c
  8. * \brief Implementation for Tor's control-socket interface.
  9. * See doc/spec/control-spec.txt for full details on protocol.
  10. **/
  11. #define CONTROL_PRIVATE
  12. #include "or.h"
  13. /** Yield true iff <b>s</b> is the state of a control_connection_t that has
  14. * finished authentication and is accepting commands. */
  15. #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
  16. /* Recognized asynchronous event types. It's okay to expand this list
  17. * because it is used both as a list of v0 event types, and as indices
  18. * into the bitfield to determine which controllers want which events.
  19. */
  20. #define _EVENT_MIN 0x0001
  21. #define EVENT_CIRCUIT_STATUS 0x0001
  22. #define EVENT_STREAM_STATUS 0x0002
  23. #define EVENT_OR_CONN_STATUS 0x0003
  24. #define EVENT_BANDWIDTH_USED 0x0004
  25. #define EVENT_LOG_OBSOLETE 0x0005 /* Can reclaim this. */
  26. #define EVENT_NEW_DESC 0x0006
  27. #define EVENT_DEBUG_MSG 0x0007
  28. #define EVENT_INFO_MSG 0x0008
  29. #define EVENT_NOTICE_MSG 0x0009
  30. #define EVENT_WARN_MSG 0x000A
  31. #define EVENT_ERR_MSG 0x000B
  32. #define EVENT_ADDRMAP 0x000C
  33. // #define EVENT_AUTHDIR_NEWDESCS 0x000D
  34. #define EVENT_DESCCHANGED 0x000E
  35. #define EVENT_NS 0x000F
  36. #define EVENT_STATUS_CLIENT 0x0010
  37. #define EVENT_STATUS_SERVER 0x0011
  38. #define EVENT_STATUS_GENERAL 0x0012
  39. #define EVENT_GUARD 0x0013
  40. #define EVENT_STREAM_BANDWIDTH_USED 0x0014
  41. #define _EVENT_MAX 0x0014
  42. /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
  43. /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
  44. * connection is interested in events of type <b>e</b>. We use this
  45. * so that we can decide to skip generating event messages that nobody
  46. * has interest in without having to walk over the global connection
  47. * list to find out.
  48. **/
  49. typedef uint32_t event_mask_t;
  50. static event_mask_t global_event_mask1long = 0;
  51. static event_mask_t global_event_mask1short = 0;
  52. /** True iff we have disabled log messages from being sent to the controller */
  53. static int disable_log_messages = 0;
  54. /** Macro: true if any control connection is interested in events of type
  55. * <b>e</b>. */
  56. #define EVENT_IS_INTERESTING(e) \
  57. ((global_event_mask1long|global_event_mask1short) & (1<<(e)))
  58. #define EVENT_IS_INTERESTING1L(e) (global_event_mask1long & (1<<(e)))
  59. #define EVENT_IS_INTERESTING1S(e) (global_event_mask1short & (1<<(e)))
  60. /** If we're using cookie-type authentication, how long should our cookies be?
  61. */
  62. #define AUTHENTICATION_COOKIE_LEN 32
  63. /** If true, we've set authentication_cookie to a secret code and
  64. * stored it to disk. */
  65. static int authentication_cookie_is_set = 0;
  66. static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
  67. #define SHORT_NAMES 1
  68. #define LONG_NAMES 2
  69. #define ALL_NAMES (SHORT_NAMES|LONG_NAMES)
  70. #define EXTENDED_FORMAT 4
  71. #define NONEXTENDED_FORMAT 8
  72. #define ALL_FORMATS (EXTENDED_FORMAT|NONEXTENDED_FORMAT)
  73. typedef int event_format_t;
  74. static void connection_printf_to_buf(control_connection_t *conn,
  75. const char *format, ...)
  76. CHECK_PRINTF(2,3);
  77. static void send_control_done(control_connection_t *conn);
  78. static void send_control_event(uint16_t event, event_format_t which,
  79. const char *format, ...)
  80. CHECK_PRINTF(3,4);
  81. static void send_control_event_extended(uint16_t event, event_format_t which,
  82. const char *format, ...)
  83. CHECK_PRINTF(3,4);
  84. static int handle_control_setconf(control_connection_t *conn, uint32_t len,
  85. char *body);
  86. static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
  87. char *body);
  88. static int handle_control_getconf(control_connection_t *conn, uint32_t len,
  89. const char *body);
  90. static int handle_control_setevents(control_connection_t *conn, uint32_t len,
  91. const char *body);
  92. static int handle_control_authenticate(control_connection_t *conn,
  93. uint32_t len,
  94. const char *body);
  95. static int handle_control_saveconf(control_connection_t *conn, uint32_t len,
  96. const char *body);
  97. static int handle_control_signal(control_connection_t *conn, uint32_t len,
  98. const char *body);
  99. static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  100. const char *body);
  101. static char *list_getinfo_options(void);
  102. static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
  103. const char *body);
  104. static int handle_control_extendcircuit(control_connection_t *conn,
  105. uint32_t len,
  106. const char *body);
  107. static int handle_control_setpurpose(control_connection_t *conn,
  108. int for_circuits,
  109. uint32_t len, const char *body);
  110. static int handle_control_attachstream(control_connection_t *conn,
  111. uint32_t len,
  112. const char *body);
  113. static int handle_control_postdescriptor(control_connection_t *conn,
  114. uint32_t len,
  115. const char *body);
  116. static int handle_control_redirectstream(control_connection_t *conn,
  117. uint32_t len,
  118. const char *body);
  119. static int handle_control_closestream(control_connection_t *conn, uint32_t len,
  120. const char *body);
  121. static int handle_control_closecircuit(control_connection_t *conn,
  122. uint32_t len,
  123. const char *body);
  124. static int handle_control_resolve(control_connection_t *conn, uint32_t len,
  125. const char *body);
  126. static int handle_control_usefeature(control_connection_t *conn,
  127. uint32_t len,
  128. const char *body);
  129. static int write_stream_target_to_buf(edge_connection_t *conn, char *buf,
  130. size_t len);
  131. static void orconn_target_get_name(int long_names, char *buf, size_t len,
  132. or_connection_t *conn);
  133. /** Given a control event code for a message event, return the corresponding
  134. * log severity. */
  135. static INLINE int
  136. event_to_log_severity(int event)
  137. {
  138. switch (event) {
  139. case EVENT_DEBUG_MSG: return LOG_DEBUG;
  140. case EVENT_INFO_MSG: return LOG_INFO;
  141. case EVENT_NOTICE_MSG: return LOG_NOTICE;
  142. case EVENT_WARN_MSG: return LOG_WARN;
  143. case EVENT_ERR_MSG: return LOG_ERR;
  144. default: return -1;
  145. }
  146. }
  147. /** Given a log severity, return the corresponding control event code. */
  148. static INLINE int
  149. log_severity_to_event(int severity)
  150. {
  151. switch (severity) {
  152. case LOG_DEBUG: return EVENT_DEBUG_MSG;
  153. case LOG_INFO: return EVENT_INFO_MSG;
  154. case LOG_NOTICE: return EVENT_NOTICE_MSG;
  155. case LOG_WARN: return EVENT_WARN_MSG;
  156. case LOG_ERR: return EVENT_ERR_MSG;
  157. default: return -1;
  158. }
  159. }
  160. /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
  161. * connection's event_mask field. */
  162. void
  163. control_update_global_event_mask(void)
  164. {
  165. smartlist_t *conns = get_connection_array();
  166. event_mask_t old_mask, new_mask;
  167. old_mask = global_event_mask1short;
  168. old_mask |= global_event_mask1long;
  169. global_event_mask1short = 0;
  170. global_event_mask1long = 0;
  171. SMARTLIST_FOREACH(conns, connection_t *, _conn,
  172. {
  173. if (_conn->type == CONN_TYPE_CONTROL &&
  174. STATE_IS_OPEN(_conn->state)) {
  175. control_connection_t *conn = TO_CONTROL_CONN(_conn);
  176. if (conn->use_long_names)
  177. global_event_mask1long |= conn->event_mask;
  178. else
  179. global_event_mask1short |= conn->event_mask;
  180. }
  181. });
  182. new_mask = global_event_mask1short;
  183. new_mask |= global_event_mask1long;
  184. /* Handle the aftermath. Set up the log callback to tell us only what
  185. * we want to hear...*/
  186. control_adjust_event_log_severity();
  187. /* ...then, if we've started logging stream bw, clear the appropriate
  188. * fields. */
  189. if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
  190. (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
  191. SMARTLIST_FOREACH(conns, connection_t *, conn,
  192. {
  193. if (conn->type == CONN_TYPE_AP) {
  194. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  195. edge_conn->n_written = edge_conn->n_read = 0;
  196. }
  197. });
  198. }
  199. }
  200. /** Adjust the log severities that result in control_event_logmsg being called
  201. * to match the severity of log messages that any controllers are interested
  202. * in. */
  203. void
  204. control_adjust_event_log_severity(void)
  205. {
  206. int i;
  207. int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
  208. for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
  209. if (EVENT_IS_INTERESTING(i)) {
  210. min_log_event = i;
  211. break;
  212. }
  213. }
  214. for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
  215. if (EVENT_IS_INTERESTING(i)) {
  216. max_log_event = i;
  217. break;
  218. }
  219. }
  220. if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE) ||
  221. EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
  222. if (min_log_event > EVENT_NOTICE_MSG)
  223. min_log_event = EVENT_NOTICE_MSG;
  224. if (max_log_event < EVENT_ERR_MSG)
  225. max_log_event = EVENT_ERR_MSG;
  226. }
  227. change_callback_log_severity(event_to_log_severity(min_log_event),
  228. event_to_log_severity(max_log_event),
  229. control_event_logmsg);
  230. }
  231. /** Return true iff the event with code <b>c</b> is being sent to any current
  232. * control connection. This is useful if the amount of work needed to prepare
  233. * to call the appropriate control_event_...() function is high.
  234. */
  235. int
  236. control_event_is_interesting(int event)
  237. {
  238. return EVENT_IS_INTERESTING(event);
  239. }
  240. /** Append a NUL-terminated string <b>s</b> to the end of
  241. * <b>conn</b>-\>outbuf
  242. */
  243. static INLINE void
  244. connection_write_str_to_buf(const char *s, control_connection_t *conn)
  245. {
  246. size_t len = strlen(s);
  247. connection_write_to_buf(s, len, TO_CONN(conn));
  248. }
  249. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  250. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  251. * the contents of <b>data</b> into *<b>out</b>, adding a period
  252. * before any period that that appears at the start of a line, and
  253. * adding a period-CRLF line at the end. If <b>translate_newlines</b>
  254. * is true, replace all LF characters sequences with CRLF. Return the
  255. * number of bytes in *<b>out</b>.
  256. */
  257. /* static */ size_t
  258. write_escaped_data(const char *data, size_t len, int translate_newlines,
  259. char **out)
  260. {
  261. size_t sz_out = len+8;
  262. char *outp;
  263. const char *end;
  264. int i;
  265. int start_of_line;
  266. for (i=0; i<(int)len; ++i) {
  267. if (data[i]== '\n')
  268. sz_out += 2; /* Maybe add a CR; maybe add a dot. */
  269. }
  270. *out = outp = tor_malloc(sz_out+1);
  271. end = data+len;
  272. start_of_line = 1;
  273. while (data < end) {
  274. if (*data == '\n') {
  275. if (translate_newlines)
  276. *outp++ = '\r';
  277. start_of_line = 1;
  278. } else if (*data == '.') {
  279. if (start_of_line) {
  280. start_of_line = 0;
  281. *outp++ = '.';
  282. }
  283. } else {
  284. start_of_line = 0;
  285. }
  286. *outp++ = *data++;
  287. }
  288. if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
  289. *outp++ = '\r';
  290. *outp++ = '\n';
  291. }
  292. *outp++ = '.';
  293. *outp++ = '\r';
  294. *outp++ = '\n';
  295. *outp = '\0'; /* NUL-terminate just in case. */
  296. tor_assert((outp - *out) <= (int)sz_out);
  297. return outp - *out;
  298. }
  299. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  300. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  301. * the contents of <b>data</b> into *<b>out</b>, removing any period
  302. * that appears at the start of a line. If <b>translate_newlines</b>
  303. * is true, replace all CRLF sequences with LF. Return the number of
  304. * bytes in *<b>out</b>. */
  305. /* static */ size_t
  306. read_escaped_data(const char *data, size_t len, int translate_newlines,
  307. char **out)
  308. {
  309. char *outp;
  310. const char *next;
  311. const char *end;
  312. *out = outp = tor_malloc(len+1);
  313. end = data+len;
  314. while (data < end) {
  315. if (*data == '.')
  316. ++data;
  317. if (translate_newlines)
  318. next = tor_memmem(data, end-data, "\r\n", 2);
  319. else
  320. next = tor_memmem(data, end-data, "\r\n.", 3);
  321. if (next) {
  322. memcpy(outp, data, next-data);
  323. outp += (next-data);
  324. data = next+2;
  325. } else {
  326. memcpy(outp, data, end-data);
  327. outp += (end-data);
  328. *outp = '\0';
  329. return outp - *out;
  330. }
  331. if (translate_newlines) {
  332. *outp++ = '\n';
  333. } else {
  334. *outp++ = '\r';
  335. *outp++ = '\n';
  336. }
  337. }
  338. *outp = '\0';
  339. return outp - *out;
  340. }
  341. /** Given a pointer to a string starting at <b>start</b> containing
  342. * <b>in_len_max</b> characters, decode a string beginning with a single
  343. * quote, containing any number of non-quote characters or characters escaped
  344. * with a backslash, and ending with a final quote. Place the resulting
  345. * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
  346. * store its length in <b>out_len</b>. On success, return a pointer to the
  347. * character immediately following the escaped string. On failure, return
  348. * NULL. */
  349. static const char *
  350. get_escaped_string(const char *start, size_t in_len_max,
  351. char **out, size_t *out_len)
  352. {
  353. const char *cp, *end;
  354. char *outp;
  355. size_t len=0;
  356. if (*start != '\"')
  357. return NULL;
  358. cp = start+1;
  359. end = start+in_len_max;
  360. /* Calculate length. */
  361. while (1) {
  362. if (cp >= end)
  363. return NULL;
  364. else if (*cp == '\\') {
  365. if (++cp == end)
  366. return NULL; /* Can't escape EOS. */
  367. ++cp;
  368. ++len;
  369. } else if (*cp == '\"') {
  370. break;
  371. } else {
  372. ++cp;
  373. ++len;
  374. }
  375. }
  376. end = cp;
  377. outp = *out = tor_malloc(len+1);
  378. *out_len = len;
  379. cp = start+1;
  380. while (cp < end) {
  381. if (*cp == '\\')
  382. ++cp;
  383. *outp++ = *cp++;
  384. }
  385. *outp = '\0';
  386. tor_assert((outp - *out) == (int)*out_len);
  387. return end+1;
  388. }
  389. /** Acts like sprintf, but writes its formatted string to the end of
  390. * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
  391. * but it will always end with a CRLF sequence.
  392. *
  393. * Currently the length of the message is limited to 1024 (including the
  394. * ending \r\n\0. */
  395. static void
  396. connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
  397. {
  398. #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
  399. va_list ap;
  400. char buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE];
  401. int r;
  402. size_t len;
  403. va_start(ap,format);
  404. r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  405. va_end(ap);
  406. if (r<0) {
  407. log_warn(LD_BUG, "Unable to format string for controller.");
  408. return;
  409. }
  410. len = strlen(buf);
  411. if (memcmp("\r\n\0", buf+len-2, 3)) {
  412. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-1] = '\0';
  413. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-2] = '\n';
  414. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-3] = '\r';
  415. }
  416. connection_write_to_buf(buf, len, TO_CONN(conn));
  417. }
  418. /** Send a "DONE" message down the control connection <b>conn</b> */
  419. static void
  420. send_control_done(control_connection_t *conn)
  421. {
  422. connection_write_str_to_buf("250 OK\r\n", conn);
  423. }
  424. /* Send an event to all v1 controllers that are listening for code
  425. * <b>event</b>. The event's body is given by <b>msg</b>.
  426. *
  427. * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
  428. * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
  429. * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
  430. * to contollers that <em>have</em> enabled VERBOSE_NAMES.
  431. *
  432. * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
  433. * respect to the EXTENDED_EVENTS feature. */
  434. static void
  435. send_control_event_string(uint16_t event, event_format_t which,
  436. const char *msg)
  437. {
  438. smartlist_t *conns = get_connection_array();
  439. tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);
  440. SMARTLIST_FOREACH(conns, connection_t *, conn,
  441. {
  442. if (conn->type == CONN_TYPE_CONTROL &&
  443. !conn->marked_for_close &&
  444. conn->state == CONTROL_CONN_STATE_OPEN) {
  445. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  446. if (control_conn->use_long_names) {
  447. if (!(which & LONG_NAMES))
  448. continue;
  449. } else {
  450. if (!(which & SHORT_NAMES))
  451. continue;
  452. }
  453. if (control_conn->use_extended_events) {
  454. if (!(which & EXTENDED_FORMAT))
  455. continue;
  456. } else {
  457. if (!(which & NONEXTENDED_FORMAT))
  458. continue;
  459. }
  460. if (control_conn->event_mask & (1<<event)) {
  461. int is_err = 0;
  462. connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
  463. if (event == EVENT_ERR_MSG)
  464. is_err = 1;
  465. else if (event == EVENT_STATUS_GENERAL)
  466. is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
  467. else if (event == EVENT_STATUS_CLIENT)
  468. is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
  469. else if (event == EVENT_STATUS_SERVER)
  470. is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
  471. if (is_err)
  472. connection_handle_write(TO_CONN(control_conn), 1);
  473. }
  474. }
  475. });
  476. }
  477. /** Helper for send_control1_event and send_control1_event_extended:
  478. * Send an event to all v1 controllers that are listening for code
  479. * <b>event</b>. The event's body is created by the printf-style format in
  480. * <b>format</b>, and other arguments as provided.
  481. *
  482. * If <b>extended</b> is true, and the format contains a single '@' character,
  483. * it will be replaced with a space and all text after that character will be
  484. * sent only to controllers that have enabled extended events.
  485. *
  486. * Currently the length of the message is limited to 1024 (including the
  487. * ending \n\r\0). */
  488. static void
  489. send_control_event_impl(uint16_t event, event_format_t which, int extended,
  490. const char *format, va_list ap)
  491. {
  492. /* This is just a little longer than the longest allowed log message */
  493. #define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
  494. int r;
  495. char buf[SEND_CONTROL1_EVENT_BUFFERSIZE];
  496. size_t len;
  497. char *cp;
  498. r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  499. if (r<0) {
  500. log_warn(LD_BUG, "Unable to format event for controller.");
  501. return;
  502. }
  503. len = strlen(buf);
  504. if (memcmp("\r\n\0", buf+len-2, 3)) {
  505. /* if it is not properly terminated, do it now */
  506. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-1] = '\0';
  507. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-2] = '\n';
  508. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-3] = '\r';
  509. }
  510. if (extended && (cp = strchr(buf, '@'))) {
  511. which &= ~ALL_FORMATS;
  512. *cp = ' ';
  513. send_control_event_string(event, which|EXTENDED_FORMAT, buf);
  514. memcpy(cp, "\r\n\0", 3);
  515. send_control_event_string(event, which|NONEXTENDED_FORMAT, buf);
  516. } else {
  517. send_control_event_string(event, which|ALL_FORMATS, buf);
  518. }
  519. }
  520. /* Send an event to all v1 controllers that are listening for code
  521. * <b>event</b>. The event's body is created by the printf-style format in
  522. * <b>format</b>, and other arguments as provided.
  523. *
  524. * Currently the length of the message is limited to 1024 (including the
  525. * ending \n\r\0. */
  526. static void
  527. send_control_event(uint16_t event, event_format_t which,
  528. const char *format, ...)
  529. {
  530. va_list ap;
  531. va_start(ap, format);
  532. send_control_event_impl(event, which, 0, format, ap);
  533. va_end(ap);
  534. }
  535. /* Send an event to all v1 controllers that are listening for code
  536. * <b>event</b>. The event's body is created by the printf-style format in
  537. * <b>format</b>, and other arguments as provided.
  538. *
  539. * If the format contains a single '@' character, it will be replaced with a
  540. * space and all text after that character will be sent only to controllers
  541. * that have enabled extended events.
  542. *
  543. * Currently the length of the message is limited to 1024 (including the
  544. * ending \n\r\0. */
  545. static void
  546. send_control_event_extended(uint16_t event, event_format_t which,
  547. const char *format, ...)
  548. {
  549. va_list ap;
  550. va_start(ap, format);
  551. send_control_event_impl(event, which, 1, format, ap);
  552. va_end(ap);
  553. }
  554. /** Given a text circuit <b>id</b>, return the corresponding circuit. */
  555. static origin_circuit_t *
  556. get_circ(const char *id)
  557. {
  558. unsigned long n_id;
  559. int ok;
  560. n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
  561. if (!ok)
  562. return NULL;
  563. return circuit_get_by_global_id(n_id);
  564. }
  565. /** Given a text stream <b>id</b>, return the corresponding AP connection. */
  566. static edge_connection_t *
  567. get_stream(const char *id)
  568. {
  569. unsigned long n_id;
  570. int ok;
  571. edge_connection_t *conn;
  572. n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
  573. if (!ok)
  574. return NULL;
  575. conn = connection_get_by_global_id(n_id);
  576. if (!conn || conn->_base.type != CONN_TYPE_AP)
  577. return NULL;
  578. return conn;
  579. }
  580. /** Helper for setconf and resetconf. Acts like setconf, except
  581. * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
  582. * contents of body.
  583. */
  584. static int
  585. control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
  586. int use_defaults)
  587. {
  588. int r;
  589. config_line_t *lines=NULL;
  590. char *start = body;
  591. char *errstring = NULL;
  592. const int clear_first = 1;
  593. char *config;
  594. smartlist_t *entries = smartlist_create();
  595. /* We have a string, "body", of the format '(key(=val|="val")?)' entries
  596. * separated by space. break it into a list of configuration entries. */
  597. while (*body) {
  598. char *eq = body;
  599. char *key;
  600. char *entry;
  601. while (!TOR_ISSPACE(*eq) && *eq != '=')
  602. ++eq;
  603. key = tor_strndup(body, eq-body);
  604. body = eq+1;
  605. if (*eq == '=') {
  606. char *val;
  607. size_t val_len;
  608. size_t ent_len;
  609. if (*body != '\"') {
  610. char *val_start = body;
  611. while (!TOR_ISSPACE(*body))
  612. body++;
  613. val = tor_strndup(val_start, body-val_start);
  614. val_len = strlen(val);
  615. } else {
  616. body = (char*)get_escaped_string(body, (len - (body-start)),
  617. &val, &val_len);
  618. if (!body) {
  619. connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
  620. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  621. smartlist_free(entries);
  622. return 0;
  623. }
  624. }
  625. ent_len = strlen(key)+val_len+3;
  626. entry = tor_malloc(ent_len+1);
  627. tor_snprintf(entry, ent_len, "%s %s", key, val);
  628. tor_free(key);
  629. tor_free(val);
  630. } else {
  631. entry = key;
  632. }
  633. smartlist_add(entries, entry);
  634. while (TOR_ISSPACE(*body))
  635. ++body;
  636. }
  637. smartlist_add(entries, tor_strdup(""));
  638. config = smartlist_join_strings(entries, "\n", 0, NULL);
  639. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  640. smartlist_free(entries);
  641. if (config_get_lines(config, &lines) < 0) {
  642. log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
  643. connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
  644. conn);
  645. tor_free(config);
  646. return 0;
  647. }
  648. tor_free(config);
  649. if ((r=options_trial_assign(lines, use_defaults,
  650. clear_first, &errstring)) < 0) {
  651. const char *msg;
  652. log_warn(LD_CONTROL,
  653. "Controller gave us config lines that didn't validate: %s.",
  654. errstring);
  655. switch (r) {
  656. case -1:
  657. msg = "552 Unrecognized option";
  658. break;
  659. case -2:
  660. msg = "513 Unacceptable option value";
  661. break;
  662. case -3:
  663. msg = "553 Transition not allowed";
  664. break;
  665. case -4:
  666. default:
  667. msg = "553 Unable to set option";
  668. break;
  669. }
  670. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  671. config_free_lines(lines);
  672. tor_free(errstring);
  673. return 0;
  674. }
  675. config_free_lines(lines);
  676. send_control_done(conn);
  677. return 0;
  678. }
  679. /** Called when we receive a SETCONF message: parse the body and try
  680. * to update our configuration. Reply with a DONE or ERROR message.
  681. * Modifies the contents of body.*/
  682. static int
  683. handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
  684. {
  685. return control_setconf_helper(conn, len, body, 0);
  686. }
  687. /** Called when we receive a RESETCONF message: parse the body and try
  688. * to update our configuration. Reply with a DONE or ERROR message.
  689. * Modifies the contents of body. */
  690. static int
  691. handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
  692. {
  693. return control_setconf_helper(conn, len, body, 1);
  694. }
  695. /** Called when we receive a GETCONF message. Parse the request, and
  696. * reply with a CONFVALUE or an ERROR message */
  697. static int
  698. handle_control_getconf(control_connection_t *conn, uint32_t body_len,
  699. const char *body)
  700. {
  701. smartlist_t *questions = NULL;
  702. smartlist_t *answers = NULL;
  703. smartlist_t *unrecognized = NULL;
  704. char *msg = NULL;
  705. size_t msg_len;
  706. or_options_t *options = get_options();
  707. int i, len;
  708. questions = smartlist_create();
  709. (void) body_len; /* body is nul-terminated; so we can ignore len. */
  710. smartlist_split_string(questions, body, " ",
  711. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  712. answers = smartlist_create();
  713. unrecognized = smartlist_create();
  714. SMARTLIST_FOREACH(questions, char *, q,
  715. {
  716. if (!option_is_recognized(q)) {
  717. smartlist_add(unrecognized, q);
  718. } else {
  719. config_line_t *answer = option_get_assignment(options,q);
  720. if (!answer) {
  721. const char *name = option_get_canonical_name(q);
  722. size_t alen = strlen(name)+8;
  723. char *astr = tor_malloc(alen);
  724. tor_snprintf(astr, alen, "250-%s\r\n", name);
  725. smartlist_add(answers, astr);
  726. }
  727. while (answer) {
  728. config_line_t *next;
  729. size_t alen = strlen(answer->key)+strlen(answer->value)+8;
  730. char *astr = tor_malloc(alen);
  731. tor_snprintf(astr, alen, "250-%s=%s\r\n",
  732. answer->key, answer->value);
  733. smartlist_add(answers, astr);
  734. next = answer->next;
  735. tor_free(answer->key);
  736. tor_free(answer->value);
  737. tor_free(answer);
  738. answer = next;
  739. }
  740. }
  741. });
  742. if ((len = smartlist_len(unrecognized))) {
  743. for (i=0; i < len-1; ++i)
  744. connection_printf_to_buf(conn,
  745. "552-Unrecognized configuration key \"%s\"\r\n",
  746. (char*)smartlist_get(unrecognized, i));
  747. connection_printf_to_buf(conn,
  748. "552 Unrecognized configuration key \"%s\"\r\n",
  749. (char*)smartlist_get(unrecognized, len-1));
  750. } else if ((len = smartlist_len(answers))) {
  751. char *tmp = smartlist_get(answers, len-1);
  752. tor_assert(strlen(tmp)>4);
  753. tmp[3] = ' ';
  754. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  755. connection_write_to_buf(msg, msg_len, TO_CONN(conn));
  756. } else {
  757. connection_write_str_to_buf("250 OK\r\n", conn);
  758. }
  759. if (answers) {
  760. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  761. smartlist_free(answers);
  762. }
  763. if (questions) {
  764. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  765. smartlist_free(questions);
  766. }
  767. smartlist_free(unrecognized);
  768. tor_free(msg);
  769. return 0;
  770. }
  771. /** Called when we get a SETEVENTS message: update conn->event_mask,
  772. * and reply with DONE or ERROR. */
  773. static int
  774. handle_control_setevents(control_connection_t *conn, uint32_t len,
  775. const char *body)
  776. {
  777. uint16_t event_code;
  778. uint32_t event_mask = 0;
  779. unsigned int extended = 0;
  780. smartlist_t *events = smartlist_create();
  781. (void) len;
  782. smartlist_split_string(events, body, " ",
  783. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  784. SMARTLIST_FOREACH(events, const char *, ev,
  785. {
  786. if (!strcasecmp(ev, "EXTENDED")) {
  787. extended = 1;
  788. continue;
  789. } else if (!strcasecmp(ev, "CIRC"))
  790. event_code = EVENT_CIRCUIT_STATUS;
  791. else if (!strcasecmp(ev, "STREAM"))
  792. event_code = EVENT_STREAM_STATUS;
  793. else if (!strcasecmp(ev, "ORCONN"))
  794. event_code = EVENT_OR_CONN_STATUS;
  795. else if (!strcasecmp(ev, "BW"))
  796. event_code = EVENT_BANDWIDTH_USED;
  797. else if (!strcasecmp(ev, "DEBUG"))
  798. event_code = EVENT_DEBUG_MSG;
  799. else if (!strcasecmp(ev, "INFO"))
  800. event_code = EVENT_INFO_MSG;
  801. else if (!strcasecmp(ev, "NOTICE"))
  802. event_code = EVENT_NOTICE_MSG;
  803. else if (!strcasecmp(ev, "WARN"))
  804. event_code = EVENT_WARN_MSG;
  805. else if (!strcasecmp(ev, "ERR"))
  806. event_code = EVENT_ERR_MSG;
  807. else if (!strcasecmp(ev, "NEWDESC"))
  808. event_code = EVENT_NEW_DESC;
  809. else if (!strcasecmp(ev, "ADDRMAP"))
  810. event_code = EVENT_ADDRMAP;
  811. else if (!strcasecmp(ev, "AUTHDIR_NEWDESCS"))
  812. event_code = EVENT_AUTHDIR_NEWDESCS;
  813. else if (!strcasecmp(ev, "DESCCHANGED"))
  814. event_code = EVENT_DESCCHANGED;
  815. else if (!strcasecmp(ev, "NS"))
  816. event_code = EVENT_NS;
  817. else if (!strcasecmp(ev, "STATUS_GENERAL"))
  818. event_code = EVENT_STATUS_GENERAL;
  819. else if (!strcasecmp(ev, "STATUS_CLIENT"))
  820. event_code = EVENT_STATUS_CLIENT;
  821. else if (!strcasecmp(ev, "STATUS_SERVER"))
  822. event_code = EVENT_STATUS_SERVER;
  823. else if (!strcasecmp(ev, "GUARD"))
  824. event_code = EVENT_GUARD;
  825. else if (!strcasecmp(ev, "GUARDS")) {
  826. /* XXXX021 This check is here to tolerate the controllers that
  827. * depended on the buggy spec in 0.1.2.5-alpha through 0.1.2.10-rc.
  828. * Once those versions are obsolete, stop supporting this. */
  829. log_warn(LD_CONTROL, "Controller used obsolete 'GUARDS' event name; "
  830. "use GUARD instead.");
  831. event_code = EVENT_GUARD;
  832. } else if (!strcasecmp(ev, "STREAM_BW"))
  833. event_code = EVENT_STREAM_BANDWIDTH_USED;
  834. else {
  835. connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
  836. ev);
  837. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  838. smartlist_free(events);
  839. return 0;
  840. }
  841. event_mask |= (1 << event_code);
  842. });
  843. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  844. smartlist_free(events);
  845. conn->event_mask = event_mask;
  846. if (extended)
  847. conn->use_extended_events = 1;
  848. control_update_global_event_mask();
  849. send_control_done(conn);
  850. return 0;
  851. }
  852. /** Decode the hashed, base64'd password stored in <b>hashed</b>. If
  853. * <b>buf</b> is provided, store the hashed password in the first
  854. * S2K_SPECIFIER_LEN+DIGEST_LEN bytes of <b>buf</b>. Return 0 on
  855. * success, -1 on failure.
  856. */
  857. int
  858. decode_hashed_password(char *buf, const char *hashed)
  859. {
  860. char decoded[64];
  861. if (!strcmpstart(hashed, "16:")) {
  862. if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
  863. || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
  864. return -1;
  865. }
  866. } else {
  867. if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
  868. != S2K_SPECIFIER_LEN+DIGEST_LEN) {
  869. return -1;
  870. }
  871. }
  872. if (buf)
  873. memcpy(buf, decoded, S2K_SPECIFIER_LEN+DIGEST_LEN);
  874. return 0;
  875. }
  876. /** Called when we get an AUTHENTICATE message. Check whether the
  877. * authentication is valid, and if so, update the connection's state to
  878. * OPEN. Reply with DONE or ERROR.
  879. */
  880. static int
  881. handle_control_authenticate(control_connection_t *conn, uint32_t len,
  882. const char *body)
  883. {
  884. int used_quoted_string = 0;
  885. or_options_t *options = get_options();
  886. const char *errstr = NULL;
  887. char *password;
  888. size_t password_len;
  889. const char *cp;
  890. int i;
  891. if (TOR_ISXDIGIT(body[0])) {
  892. cp = body;
  893. while (TOR_ISXDIGIT(*cp))
  894. ++cp;
  895. i = cp - body;
  896. tor_assert(i>0);
  897. password_len = i/2;
  898. password = tor_malloc(password_len + 1);
  899. if (base16_decode(password, password_len+1, body, i)<0) {
  900. connection_write_str_to_buf(
  901. "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
  902. "password? If so, the standard requires that you put it in "
  903. "double quotes.\r\n", conn);
  904. tor_free(password);
  905. return 0;
  906. }
  907. } else if (TOR_ISSPACE(body[0])) {
  908. password = tor_strdup("");
  909. password_len = 0;
  910. } else {
  911. if (!get_escaped_string(body, len, &password, &password_len)) {
  912. connection_write_str_to_buf("551 Invalid quoted string. You need "
  913. "to put the password in double quotes.\r\n", conn);
  914. return 0;
  915. }
  916. used_quoted_string = 1;
  917. }
  918. if (options->CookieAuthentication && authentication_cookie_is_set) {
  919. if (password_len != AUTHENTICATION_COOKIE_LEN) {
  920. log_warn(LD_CONTROL, "Got authentication cookie with wrong length (%d)",
  921. (int)password_len);
  922. errstr = "Wrong length on authentication cookie.";
  923. goto err;
  924. } else if (memcmp(authentication_cookie, password, password_len)) {
  925. log_warn(LD_CONTROL, "Got mismatched authentication cookie");
  926. errstr = "Authentication cookie did not match expected value.";
  927. goto err;
  928. } else {
  929. goto ok;
  930. }
  931. } else if (options->HashedControlPassword) {
  932. char expected[S2K_SPECIFIER_LEN+DIGEST_LEN];
  933. char received[DIGEST_LEN];
  934. if (decode_hashed_password(expected, options->HashedControlPassword)<0) {
  935. log_warn(LD_CONTROL,
  936. "Couldn't decode HashedControlPassword: invalid base16");
  937. errstr = "Couldn't decode HashedControlPassword value in configuration.";
  938. goto err;
  939. }
  940. secret_to_key(received,DIGEST_LEN,password,password_len,expected);
  941. if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
  942. goto ok;
  943. if (used_quoted_string)
  944. errstr = "Password did not match HashedControlPassword value from "
  945. "configuration";
  946. else
  947. errstr = "Password did not match HashedControlPassword value from "
  948. "configuration. Maybe you tried a plain text password? "
  949. "If so, the standard requires that you put it in double quotes.";
  950. goto err;
  951. } else {
  952. /* if Tor doesn't demand any stronger authentication, then
  953. * the controller can get in with anything. */
  954. goto ok;
  955. }
  956. err:
  957. tor_free(password);
  958. if (!errstr)
  959. errstr = "Unknown reason.";
  960. connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n",
  961. errstr);
  962. return 0;
  963. ok:
  964. log_info(LD_CONTROL, "Authenticated control connection (%d)", conn->_base.s);
  965. send_control_done(conn);
  966. conn->_base.state = CONTROL_CONN_STATE_OPEN;
  967. tor_free(password);
  968. return 0;
  969. }
  970. /** Called when we get a SAVECONF command. Try to flush the current options to
  971. * disk, and report success or failure. */
  972. static int
  973. handle_control_saveconf(control_connection_t *conn, uint32_t len,
  974. const char *body)
  975. {
  976. (void) len;
  977. (void) body;
  978. if (options_save_current()<0) {
  979. connection_write_str_to_buf(
  980. "551 Unable to write configuration to disk.\r\n", conn);
  981. } else {
  982. send_control_done(conn);
  983. }
  984. return 0;
  985. }
  986. /** Called when we get a SIGNAL command. React to the provided signal, and
  987. * report success or failure. (If the signal results in a shutdown, success
  988. * may not be reported.) */
  989. static int
  990. handle_control_signal(control_connection_t *conn, uint32_t len,
  991. const char *body)
  992. {
  993. int sig;
  994. int n = 0;
  995. char *s;
  996. (void) len;
  997. while (body[n] && ! TOR_ISSPACE(body[n]))
  998. ++n;
  999. s = tor_strndup(body, n);
  1000. if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
  1001. sig = SIGHUP;
  1002. else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
  1003. sig = SIGINT;
  1004. else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
  1005. sig = SIGUSR1;
  1006. else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
  1007. sig = SIGUSR2;
  1008. else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
  1009. sig = SIGTERM;
  1010. else if (!strcasecmp(s, "NEWNYM"))
  1011. sig = SIGNEWNYM;
  1012. else if (!strcasecmp(s, "CLEARDNSCACHE"))
  1013. sig = SIGCLEARDNSCACHE;
  1014. else {
  1015. connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
  1016. s);
  1017. sig = -1;
  1018. }
  1019. tor_free(s);
  1020. if (sig<0)
  1021. return 0;
  1022. /* Send DONE first, in case the signal makes us shut down. */
  1023. send_control_done(conn);
  1024. control_signal_act(sig);
  1025. return 0;
  1026. }
  1027. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  1028. * and report success or failrue. */
  1029. static int
  1030. handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  1031. const char *body)
  1032. {
  1033. smartlist_t *elts;
  1034. smartlist_t *lines;
  1035. smartlist_t *reply;
  1036. char *r;
  1037. size_t sz;
  1038. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1039. lines = smartlist_create();
  1040. elts = smartlist_create();
  1041. reply = smartlist_create();
  1042. smartlist_split_string(lines, body, " ",
  1043. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1044. SMARTLIST_FOREACH(lines, char *, line,
  1045. {
  1046. tor_strlower(line);
  1047. smartlist_split_string(elts, line, "=", 0, 2);
  1048. if (smartlist_len(elts) == 2) {
  1049. const char *from = smartlist_get(elts,0);
  1050. const char *to = smartlist_get(elts,1);
  1051. size_t anslen = strlen(line)+512;
  1052. char *ans = tor_malloc(anslen);
  1053. if (address_is_invalid_destination(to, 1)) {
  1054. tor_snprintf(ans, anslen,
  1055. "512-syntax error: invalid address '%s'", to);
  1056. smartlist_add(reply, ans);
  1057. log_warn(LD_CONTROL,
  1058. "Skipping invalid argument '%s' in MapAddress msg", to);
  1059. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
  1060. const char *address = addressmap_register_virtual_address(
  1061. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
  1062. tor_strdup(to));
  1063. if (!address) {
  1064. tor_snprintf(ans, anslen,
  1065. "451-resource exhausted: skipping '%s'", line);
  1066. smartlist_add(reply, ans);
  1067. log_warn(LD_CONTROL,
  1068. "Unable to allocate address for '%s' in MapAddress msg",
  1069. safe_str(line));
  1070. } else {
  1071. tor_snprintf(ans, anslen, "250-%s=%s", address, to);
  1072. smartlist_add(reply, ans);
  1073. }
  1074. } else {
  1075. addressmap_register(from, tor_strdup(to), 1);
  1076. tor_snprintf(ans, anslen, "250-%s", line);
  1077. smartlist_add(reply, ans);
  1078. }
  1079. } else {
  1080. size_t anslen = strlen(line)+256;
  1081. char *ans = tor_malloc(anslen);
  1082. tor_snprintf(ans, anslen, "512-syntax error: mapping '%s' is "
  1083. "not of expected form 'foo=bar'.", line);
  1084. smartlist_add(reply, ans);
  1085. log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
  1086. "number of items.", safe_str(line));
  1087. }
  1088. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1089. smartlist_clear(elts);
  1090. });
  1091. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1092. smartlist_free(lines);
  1093. smartlist_free(elts);
  1094. if (smartlist_len(reply)) {
  1095. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1096. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1097. connection_write_to_buf(r, sz, TO_CONN(conn));
  1098. tor_free(r);
  1099. } else {
  1100. const char *response =
  1101. "512 syntax error: not enough arguments to mapaddress.\r\n";
  1102. connection_write_to_buf(response, strlen(response), TO_CONN(conn));
  1103. }
  1104. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1105. smartlist_free(reply);
  1106. return 0;
  1107. }
  1108. /** Implementation helper for GETINFO: knows the answers for various
  1109. * trivial-to-implement questions. */
  1110. static int
  1111. getinfo_helper_misc(control_connection_t *conn, const char *question,
  1112. char **answer)
  1113. {
  1114. (void) conn;
  1115. if (!strcmp(question, "version")) {
  1116. *answer = tor_strdup(get_version());
  1117. } else if (!strcmp(question, "config-file")) {
  1118. *answer = tor_strdup(get_torrc_fname());
  1119. } else if (!strcmp(question, "info/names")) {
  1120. *answer = list_getinfo_options();
  1121. } else if (!strcmp(question, "events/names")) {
  1122. *answer = tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
  1123. "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
  1124. "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
  1125. "GUARD STREAM_BW");
  1126. } else if (!strcmp(question, "features/names")) {
  1127. *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
  1128. } else if (!strcmp(question, "address")) {
  1129. uint32_t addr;
  1130. if (router_pick_published_address(get_options(), &addr) < 0)
  1131. return -1;
  1132. *answer = tor_dup_addr(addr);
  1133. } else if (!strcmp(question, "dir-usage")) {
  1134. *answer = directory_dump_request_log();
  1135. } else if (!strcmp(question, "fingerprint")) {
  1136. routerinfo_t *me = router_get_my_routerinfo();
  1137. if (!me)
  1138. return -1;
  1139. *answer = tor_malloc(HEX_DIGEST_LEN+1);
  1140. base16_encode(*answer, HEX_DIGEST_LEN+1, me->cache_info.identity_digest,
  1141. DIGEST_LEN);
  1142. }
  1143. return 0;
  1144. }
  1145. /** Implementation helper for GETINFO: knows the answers for questions about
  1146. * directory information. */
  1147. static int
  1148. getinfo_helper_dir(control_connection_t *control_conn,
  1149. const char *question, char **answer)
  1150. {
  1151. if (!strcmpstart(question, "desc/id/")) {
  1152. routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
  1153. if (ri) {
  1154. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1155. if (body)
  1156. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1157. }
  1158. } else if (!strcmpstart(question, "desc/name/")) {
  1159. routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
  1160. if (ri) {
  1161. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1162. if (body)
  1163. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1164. }
  1165. } else if (!strcmp(question, "desc/all-recent")) {
  1166. routerlist_t *routerlist = router_get_routerlist();
  1167. smartlist_t *sl = smartlist_create();
  1168. if (routerlist && routerlist->routers) {
  1169. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  1170. {
  1171. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1172. if (body)
  1173. smartlist_add(sl,
  1174. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1175. });
  1176. }
  1177. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1178. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1179. smartlist_free(sl);
  1180. } else if (!strcmpstart(question, "dir/server/")) {
  1181. size_t answer_len = 0, url_len = strlen(question)+2;
  1182. char *url = tor_malloc(url_len);
  1183. smartlist_t *descs = smartlist_create();
  1184. const char *msg;
  1185. int res;
  1186. char *cp;
  1187. tor_snprintf(url, url_len, "/tor/%s", question+4);
  1188. res = dirserv_get_routerdescs(descs, url, &msg);
  1189. if (res) {
  1190. log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
  1191. return -1;
  1192. }
  1193. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1194. answer_len += sd->signed_descriptor_len);
  1195. cp = *answer = tor_malloc(answer_len+1);
  1196. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1197. {
  1198. memcpy(cp, signed_descriptor_get_body(sd),
  1199. sd->signed_descriptor_len);
  1200. cp += sd->signed_descriptor_len;
  1201. });
  1202. *cp = '\0';
  1203. tor_free(url);
  1204. smartlist_free(descs);
  1205. } else if (!strcmpstart(question, "dir/status/")) {
  1206. if (get_options()->DirPort) {
  1207. size_t len=0;
  1208. char *cp;
  1209. smartlist_t *status_list = smartlist_create();
  1210. dirserv_get_networkstatus_v2(status_list,
  1211. question+strlen("dir/status/"));
  1212. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
  1213. cp = *answer = tor_malloc(len+1);
  1214. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
  1215. memcpy(cp, d->dir, d->dir_len);
  1216. cp += d->dir_len;
  1217. });
  1218. *cp = '\0';
  1219. smartlist_free(status_list);
  1220. } else {
  1221. smartlist_t *fp_list = smartlist_create();
  1222. smartlist_t *status_list = smartlist_create();
  1223. size_t fn_len = strlen(get_options()->DataDirectory)+HEX_DIGEST_LEN+32;
  1224. char *fn = tor_malloc(fn_len+1);
  1225. char hex_id[HEX_DIGEST_LEN+1];
  1226. dirserv_get_networkstatus_v2_fingerprints(
  1227. fp_list, question+strlen("dir/status/"));
  1228. SMARTLIST_FOREACH(fp_list, const char *, fp, {
  1229. char *s;
  1230. base16_encode(hex_id, sizeof(hex_id), fp, DIGEST_LEN);
  1231. tor_snprintf(fn, fn_len, "%s/cached-status/%s",
  1232. get_options()->DataDirectory, hex_id);
  1233. s = read_file_to_str(fn, 0, NULL);
  1234. if (s)
  1235. smartlist_add(status_list, s);
  1236. });
  1237. SMARTLIST_FOREACH(fp_list, char *, fp, tor_free(fp));
  1238. smartlist_free(fp_list);
  1239. *answer = smartlist_join_strings(status_list, "", 0, NULL);
  1240. SMARTLIST_FOREACH(status_list, char *, s, tor_free(s));
  1241. smartlist_free(status_list);
  1242. }
  1243. } else if (!strcmp(question, "network-status")) {
  1244. routerlist_t *routerlist = router_get_routerlist();
  1245. int verbose = control_conn->use_long_names;
  1246. if (!routerlist || !routerlist->routers ||
  1247. list_server_status(routerlist->routers, answer, verbose ? 2 : 1) < 0) {
  1248. return -1;
  1249. }
  1250. }
  1251. return 0;
  1252. }
  1253. /** Implementation helper for GETINFO: knows how to generate summaries of the
  1254. * current states of things we send events about. */
  1255. static int
  1256. getinfo_helper_events(control_connection_t *control_conn,
  1257. const char *question, char **answer)
  1258. {
  1259. if (!strcmp(question, "circuit-status")) {
  1260. circuit_t *circ;
  1261. smartlist_t *status = smartlist_create();
  1262. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  1263. char *s, *path;
  1264. size_t slen;
  1265. const char *state;
  1266. if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
  1267. continue;
  1268. if (control_conn->use_long_names)
  1269. path = circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ));
  1270. else
  1271. path = circuit_list_path(TO_ORIGIN_CIRCUIT(circ),0);
  1272. if (circ->state == CIRCUIT_STATE_OPEN)
  1273. state = "BUILT";
  1274. else if (strlen(path))
  1275. state = "EXTENDED";
  1276. else
  1277. state = "LAUNCHED";
  1278. slen = strlen(path)+strlen(state)+20;
  1279. s = tor_malloc(slen+1);
  1280. tor_snprintf(s, slen, "%lu %s %s",
  1281. (unsigned long)TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  1282. state, path);
  1283. smartlist_add(status, s);
  1284. tor_free(path);
  1285. }
  1286. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1287. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1288. smartlist_free(status);
  1289. } else if (!strcmp(question, "stream-status")) {
  1290. smartlist_t *conns = get_connection_array();
  1291. smartlist_t *status = smartlist_create();
  1292. char buf[256];
  1293. SMARTLIST_FOREACH(conns, connection_t *, base_conn,
  1294. {
  1295. const char *state;
  1296. edge_connection_t *conn;
  1297. char *s;
  1298. size_t slen;
  1299. circuit_t *circ;
  1300. origin_circuit_t *origin_circ = NULL;
  1301. if (base_conn->type != CONN_TYPE_AP ||
  1302. base_conn->marked_for_close ||
  1303. base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
  1304. base_conn->state == AP_CONN_STATE_NATD_WAIT)
  1305. continue;
  1306. conn = TO_EDGE_CONN(base_conn);
  1307. switch (conn->_base.state)
  1308. {
  1309. case AP_CONN_STATE_CONTROLLER_WAIT:
  1310. case AP_CONN_STATE_CIRCUIT_WAIT:
  1311. if (conn->socks_request &&
  1312. SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  1313. state = "NEWRESOLVE";
  1314. else
  1315. state = "NEW";
  1316. break;
  1317. case AP_CONN_STATE_RENDDESC_WAIT:
  1318. case AP_CONN_STATE_CONNECT_WAIT:
  1319. state = "SENTCONNECT"; break;
  1320. case AP_CONN_STATE_RESOLVE_WAIT:
  1321. state = "SENTRESOLVE"; break;
  1322. case AP_CONN_STATE_OPEN:
  1323. state = "SUCCEEDED"; break;
  1324. default:
  1325. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  1326. conn->_base.state);
  1327. continue;
  1328. }
  1329. circ = circuit_get_by_edge_conn(conn);
  1330. if (circ && CIRCUIT_IS_ORIGIN(circ))
  1331. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1332. write_stream_target_to_buf(conn, buf, sizeof(buf));
  1333. slen = strlen(buf)+strlen(state)+32;
  1334. s = tor_malloc(slen+1);
  1335. tor_snprintf(s, slen, "%lu %s %lu %s",
  1336. (unsigned long) conn->global_identifier,state,
  1337. origin_circ?
  1338. (unsigned long)origin_circ->global_identifier : 0ul,
  1339. buf);
  1340. smartlist_add(status, s);
  1341. });
  1342. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1343. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1344. smartlist_free(status);
  1345. } else if (!strcmp(question, "orconn-status")) {
  1346. smartlist_t *conns = get_connection_array();
  1347. smartlist_t *status = smartlist_create();
  1348. SMARTLIST_FOREACH(conns, connection_t *, base_conn,
  1349. {
  1350. const char *state;
  1351. char *s;
  1352. char name[128];
  1353. size_t slen;
  1354. or_connection_t *conn;
  1355. if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
  1356. continue;
  1357. conn = TO_OR_CONN(base_conn);
  1358. if (conn->_base.state == OR_CONN_STATE_OPEN)
  1359. state = "CONNECTED";
  1360. else if (conn->nickname)
  1361. state = "LAUNCHED";
  1362. else
  1363. state = "NEW";
  1364. orconn_target_get_name(control_conn->use_long_names, name, sizeof(name),
  1365. conn);
  1366. slen = strlen(name)+strlen(state)+2;
  1367. s = tor_malloc(slen+1);
  1368. tor_snprintf(s, slen, "%s %s", name, state);
  1369. smartlist_add(status, s);
  1370. });
  1371. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1372. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1373. smartlist_free(status);
  1374. } else if (!strcmpstart(question, "addr-mappings/")) {
  1375. time_t min_e, max_e;
  1376. smartlist_t *mappings;
  1377. if (!strcmp(question, "addr-mappings/all")) {
  1378. min_e = 0; max_e = TIME_MAX;
  1379. } else if (!strcmp(question, "addr-mappings/cache")) {
  1380. min_e = 2; max_e = TIME_MAX;
  1381. } else if (!strcmp(question, "addr-mappings/config")) {
  1382. min_e = 0; max_e = 0;
  1383. } else if (!strcmp(question, "addr-mappings/control")) {
  1384. min_e = 1; max_e = 1;
  1385. } else {
  1386. return 0;
  1387. }
  1388. mappings = smartlist_create();
  1389. addressmap_get_mappings(mappings, min_e, max_e);
  1390. *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
  1391. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  1392. smartlist_free(mappings);
  1393. } else if (!strcmpstart(question, "status/")) {
  1394. /* Note that status/ is not a catch-all for events; there's only supposed
  1395. * to be a status GETINFO if there's a corresponding STATUS event. */
  1396. if (!strcmp(question, "status/circuit-established")) {
  1397. *answer = tor_strdup(has_completed_circuit ? "1" : "0");
  1398. } else if (!strcmp(question, "status/enough-dir-info")) {
  1399. *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
  1400. } else if (!strcmpstart(question, "status/version/")) {
  1401. combined_version_status_t st;
  1402. int is_server = server_mode(get_options());
  1403. char *recommended;
  1404. recommended = compute_recommended_versions(time(NULL),
  1405. !is_server, VERSION, &st);
  1406. if (!strcmp(question, "status/version/recommended")) {
  1407. *answer = recommended;
  1408. return 0;
  1409. }
  1410. tor_free(recommended);
  1411. if (!strcmp(question, "status/version/current")) {
  1412. switch (st.consensus)
  1413. {
  1414. case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
  1415. case VS_OLD: *answer = tor_strdup("obsolete"); break;
  1416. case VS_NEW: *answer = tor_strdup("new"); break;
  1417. case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
  1418. case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
  1419. default: tor_fragile_assert();
  1420. }
  1421. } else if (!strcmp(question, "status/version/num-versioning")) {
  1422. char s[33];
  1423. tor_snprintf(s, sizeof(s), "%d", st.n_versioning);
  1424. *answer = tor_strdup(s);
  1425. } else if (!strcmp(question, "status/version/num-concurring")) {
  1426. char s[33];
  1427. tor_snprintf(s, sizeof(s), "%d", st.n_concurring);
  1428. *answer = tor_strdup(s);
  1429. }
  1430. } else {
  1431. return 0;
  1432. }
  1433. }
  1434. return 0;
  1435. }
  1436. /** Callback function for GETINFO: on a given control connection, try to
  1437. * answer the question <b>q</b> and store the newly-allocated answer in
  1438. * *<b>a</b>. If there's no answer, or an error occurs, just don't set
  1439. * <b>a</b>. Return 0.
  1440. */
  1441. typedef int (*getinfo_helper_t)(control_connection_t *,
  1442. const char *q, char **a);
  1443. /** A single item for the GETINFO question-to-answer-function table. */
  1444. typedef struct getinfo_item_t {
  1445. const char *varname; /**< The value (or prefix) of the question. */
  1446. getinfo_helper_t fn; /**< The function that knows the answer: NULL if
  1447. * this entry is documentation-only. */
  1448. const char *desc; /**< Description of the variable. */
  1449. int is_prefix; /** Must varname match exactly, or must it be a prefix? */
  1450. } getinfo_item_t;
  1451. #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
  1452. #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
  1453. #define DOC(name, desc) { name, NULL, desc, 0 }
  1454. /** Table mapping questions accepted by GETINFO to the functions that know how
  1455. * to answer them. */
  1456. static const getinfo_item_t getinfo_items[] = {
  1457. ITEM("version", misc, "The current version of Tor."),
  1458. ITEM("config-file", misc, "Current location of the \"torrc\" file."),
  1459. ITEM("accounting/bytes", accounting,
  1460. "Number of bytes read/written so far in the accounting interval."),
  1461. ITEM("accounting/bytes-left", accounting,
  1462. "Number of bytes left to write/read so far in the accounting interval."),
  1463. ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
  1464. ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
  1465. ITEM("accounting/interval-start", accounting,
  1466. "Time when the accounting period starts."),
  1467. ITEM("accounting/interval-end", accounting,
  1468. "Time when the accounting period ends."),
  1469. ITEM("accounting/interval-wake", accounting,
  1470. "Time to wake up in this accounting period."),
  1471. ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
  1472. ITEM("entry-guards", entry_guards,
  1473. "Which nodes are we using as entry guards?"),
  1474. ITEM("fingerprint", misc, NULL),
  1475. PREFIX("config/", config, "Current configuration values."),
  1476. DOC("config/names",
  1477. "List of configuration options, types, and documentation."),
  1478. ITEM("info/names", misc,
  1479. "List of GETINFO options, types, and documentation."),
  1480. ITEM("events/names", misc,
  1481. "Events that the controller can ask for with SETEVENTS."),
  1482. ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
  1483. PREFIX("desc/id/", dir, "Router descriptors by ID."),
  1484. PREFIX("desc/name/", dir, "Router descriptors by nickname."),
  1485. ITEM("desc/all-recent", dir,
  1486. "All non-expired, non-superseded router descriptors."),
  1487. ITEM("ns/all", networkstatus,
  1488. "Brief summary of router status (v2 directory format)"),
  1489. PREFIX("ns/id/", networkstatus,
  1490. "Brief summary of router status by ID (v2 directory format)."),
  1491. PREFIX("ns/name/", networkstatus,
  1492. "Brief summary of router status by nickname (v2 directory format)."),
  1493. PREFIX("unregisterd-servers-", dirserv_unregistered, NULL),
  1494. ITEM("network-status", dir,
  1495. "Brief summary of router status (v1 directory format)"),
  1496. ITEM("circuit-status", events, "List of current circuits originating here."),
  1497. ITEM("stream-status", events,"List of current streams."),
  1498. ITEM("orconn-status", events, "A list of current OR connections."),
  1499. PREFIX("addr-mappings/", events, NULL),
  1500. DOC("addr-mappings/all", "Current address mappings."),
  1501. DOC("addr-mappings/cache", "Current cached DNS replies."),
  1502. DOC("addr-mappings/config", "Current address mappings from configuration."),
  1503. DOC("addr-mappings/control", "Current address mappings from controller."),
  1504. PREFIX("status/", events, NULL),
  1505. DOC("status/circuit-established",
  1506. "Whether we think client functionality is working."),
  1507. DOC("status/enough-dir-info",
  1508. "Whether we have enough up-to-date directory information to build "
  1509. "circuits."),
  1510. /* DOCDOC specify status/version/ */
  1511. DOC("status/version/recommended", "List of currently recommended versions."),
  1512. DOC("status/version/current", "Status of the current version."),
  1513. DOC("status/version/num-versioning", "Number of versioning authorities."),
  1514. DOC("status/version/num-concurring",
  1515. "Number of versioning authorities agreeing on the status of the "
  1516. "current version"),
  1517. ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
  1518. ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
  1519. PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
  1520. PREFIX("dir/status/", dir,"Networkstatus docs as retrieved from a DirPort."),
  1521. PREFIX("exit-policy/default", policies,
  1522. "The default value appended to the configured exit policy."),
  1523. { NULL, NULL, NULL, 0 }
  1524. };
  1525. /** Allocate and return a list of recognized GETINFO options. */
  1526. static char *
  1527. list_getinfo_options(void)
  1528. {
  1529. int i;
  1530. char buf[300];
  1531. smartlist_t *lines = smartlist_create();
  1532. char *ans;
  1533. for (i = 0; getinfo_items[i].varname; ++i) {
  1534. if (!getinfo_items[i].desc)
  1535. continue;
  1536. tor_snprintf(buf, sizeof(buf), "%s%s -- %s\n",
  1537. getinfo_items[i].varname,
  1538. getinfo_items[i].is_prefix ? "*" : "",
  1539. getinfo_items[i].desc);
  1540. smartlist_add(lines, tor_strdup(buf));
  1541. }
  1542. smartlist_sort_strings(lines);
  1543. ans = smartlist_join_strings(lines, "", 0, NULL);
  1544. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1545. smartlist_free(lines);
  1546. return ans;
  1547. }
  1548. /** Lookup the 'getinfo' entry <b>question</b>, and return
  1549. * the answer in <b>*answer</b> (or NULL if key not recognized).
  1550. * Return 0 if success or unrecognized, or -1 if recognized but
  1551. * internal error. */
  1552. static int
  1553. handle_getinfo_helper(control_connection_t *control_conn,
  1554. const char *question, char **answer)
  1555. {
  1556. int i;
  1557. *answer = NULL; /* unrecognized key by default */
  1558. for (i = 0; getinfo_items[i].varname; ++i) {
  1559. int match;
  1560. if (getinfo_items[i].is_prefix)
  1561. match = !strcmpstart(question, getinfo_items[i].varname);
  1562. else
  1563. match = !strcmp(question, getinfo_items[i].varname);
  1564. if (match) {
  1565. tor_assert(getinfo_items[i].fn);
  1566. return getinfo_items[i].fn(control_conn, question, answer);
  1567. }
  1568. }
  1569. return 0; /* unrecognized */
  1570. }
  1571. /** Called when we receive a GETINFO command. Try to fetch all requested
  1572. * information, and reply with information or error message. */
  1573. static int
  1574. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  1575. const char *body)
  1576. {
  1577. smartlist_t *questions = NULL;
  1578. smartlist_t *answers = NULL;
  1579. smartlist_t *unrecognized = NULL;
  1580. char *msg = NULL, *ans = NULL;
  1581. int i;
  1582. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1583. questions = smartlist_create();
  1584. smartlist_split_string(questions, body, " ",
  1585. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1586. answers = smartlist_create();
  1587. unrecognized = smartlist_create();
  1588. SMARTLIST_FOREACH(questions, const char *, q,
  1589. {
  1590. if (handle_getinfo_helper(conn, q, &ans) < 0) {
  1591. connection_write_str_to_buf("551 Internal error\r\n", conn);
  1592. goto done;
  1593. }
  1594. if (!ans) {
  1595. smartlist_add(unrecognized, (char*)q);
  1596. } else {
  1597. smartlist_add(answers, tor_strdup(q));
  1598. smartlist_add(answers, ans);
  1599. }
  1600. });
  1601. if (smartlist_len(unrecognized)) {
  1602. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  1603. connection_printf_to_buf(conn,
  1604. "552-Unrecognized key \"%s\"\r\n",
  1605. (char*)smartlist_get(unrecognized, i));
  1606. connection_printf_to_buf(conn,
  1607. "552 Unrecognized key \"%s\"\r\n",
  1608. (char*)smartlist_get(unrecognized, i));
  1609. goto done;
  1610. }
  1611. for (i = 0; i < smartlist_len(answers); i += 2) {
  1612. char *k = smartlist_get(answers, i);
  1613. char *v = smartlist_get(answers, i+1);
  1614. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  1615. connection_printf_to_buf(conn, "250-%s=", k);
  1616. connection_write_str_to_buf(v, conn);
  1617. connection_write_str_to_buf("\r\n", conn);
  1618. } else {
  1619. char *esc = NULL;
  1620. size_t esc_len;
  1621. esc_len = write_escaped_data(v, strlen(v), 1, &esc);
  1622. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  1623. connection_write_to_buf(esc, esc_len, TO_CONN(conn));
  1624. tor_free(esc);
  1625. }
  1626. }
  1627. connection_write_str_to_buf("250 OK\r\n", conn);
  1628. done:
  1629. if (answers) {
  1630. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  1631. smartlist_free(answers);
  1632. }
  1633. if (questions) {
  1634. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  1635. smartlist_free(questions);
  1636. }
  1637. smartlist_free(unrecognized);
  1638. tor_free(msg);
  1639. return 0;
  1640. }
  1641. /** If *<b>string</b> contains a recognized purpose (for
  1642. * circuits if <b>for_circuits</b> is 1, else for routers),
  1643. * possibly prefaced with the string "purpose=", then assign it
  1644. * and return 0. Otherwise return -1.
  1645. *
  1646. * If it's prefaced with "purpose=", then set *<b>string</b> to
  1647. * the remainder of the string. */
  1648. static int
  1649. get_purpose(char **string, int for_circuits, uint8_t *purpose)
  1650. {
  1651. if (!strcmpstart(*string, "purpose="))
  1652. *string += strlen("purpose=");
  1653. if (!strcmp(*string, "general"))
  1654. *purpose = for_circuits ? CIRCUIT_PURPOSE_C_GENERAL :
  1655. ROUTER_PURPOSE_GENERAL;
  1656. else if (!strcmp(*string, "controller"))
  1657. *purpose = for_circuits ? CIRCUIT_PURPOSE_CONTROLLER :
  1658. ROUTER_PURPOSE_CONTROLLER;
  1659. else { /* not a recognized purpose */
  1660. return -1;
  1661. }
  1662. return 0;
  1663. }
  1664. /** Return a newly allocated smartlist containing the arguments to the command
  1665. * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
  1666. * or if <b>max_args</b> is nonnegative and there are more than
  1667. * <b>max_args</b> arguments, send a 512 error to the controller, using
  1668. * <b>command</b> as the command name in the error message. */
  1669. static smartlist_t *
  1670. getargs_helper(const char *command, control_connection_t *conn,
  1671. const char *body, int min_args, int max_args)
  1672. {
  1673. smartlist_t *args = smartlist_create();
  1674. smartlist_split_string(args, body, " ",
  1675. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1676. if (smartlist_len(args) < min_args) {
  1677. connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
  1678. goto err;
  1679. } else if (max_args >= 0 && smartlist_len(args) > max_args) {
  1680. connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
  1681. goto err;
  1682. }
  1683. return args;
  1684. err:
  1685. SMARTLIST_FOREACH(args, char *, s, tor_free(s));
  1686. smartlist_free(args);
  1687. return NULL;
  1688. }
  1689. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  1690. * circuit, and report success or failure. */
  1691. static int
  1692. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  1693. const char *body)
  1694. {
  1695. smartlist_t *router_nicknames=NULL, *routers=NULL;
  1696. origin_circuit_t *circ = NULL;
  1697. int zero_circ;
  1698. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  1699. smartlist_t *args;
  1700. (void) len;
  1701. router_nicknames = smartlist_create();
  1702. args = getargs_helper("EXTENDCIRCUIT", conn, body, 2, -1);
  1703. if (!args)
  1704. goto done;
  1705. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  1706. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  1707. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1708. (char*)smartlist_get(args, 0));
  1709. }
  1710. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  1711. if (zero_circ && smartlist_len(args)>2) {
  1712. char *purp = smartlist_get(args,2);
  1713. if (get_purpose(&purp, 1, &intended_purpose) < 0) {
  1714. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  1715. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1716. smartlist_free(args);
  1717. goto done;
  1718. }
  1719. }
  1720. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1721. smartlist_free(args);
  1722. if (!zero_circ && !circ) {
  1723. goto done;
  1724. }
  1725. routers = smartlist_create();
  1726. SMARTLIST_FOREACH(router_nicknames, const char *, n,
  1727. {
  1728. routerinfo_t *r = router_get_by_nickname(n, 1);
  1729. if (!r) {
  1730. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  1731. goto done;
  1732. }
  1733. smartlist_add(routers, r);
  1734. });
  1735. if (!smartlist_len(routers)) {
  1736. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  1737. goto done;
  1738. }
  1739. if (zero_circ) {
  1740. /* start a new circuit */
  1741. circ = origin_circuit_init(intended_purpose, 0, 0, 0, 0);
  1742. }
  1743. /* now circ refers to something that is ready to be extended */
  1744. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  1745. {
  1746. extend_info_t *info = extend_info_from_router(r);
  1747. circuit_append_new_exit(circ, info);
  1748. extend_info_free(info);
  1749. });
  1750. /* now that we've populated the cpath, start extending */
  1751. if (zero_circ) {
  1752. int err_reason = 0;
  1753. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  1754. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1755. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  1756. goto done;
  1757. }
  1758. } else {
  1759. if (circ->_base.state == CIRCUIT_STATE_OPEN) {
  1760. int err_reason = 0;
  1761. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1762. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  1763. log_info(LD_CONTROL,
  1764. "send_next_onion_skin failed; circuit marked for closing.");
  1765. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1766. connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
  1767. goto done;
  1768. }
  1769. }
  1770. }
  1771. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  1772. (unsigned long)circ->global_identifier);
  1773. if (zero_circ) /* send a 'launched' event, for completeness */
  1774. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  1775. done:
  1776. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  1777. smartlist_free(router_nicknames);
  1778. if (routers)
  1779. smartlist_free(routers);
  1780. return 0;
  1781. }
  1782. /** Called when we get a SETCIRCUITPURPOSE (if <b>for_circuits</b>
  1783. * is 1) or SETROUTERPURPOSE message. If we can find
  1784. * the circuit/router and it's a valid purpose, change it. */
  1785. static int
  1786. handle_control_setpurpose(control_connection_t *conn, int for_circuits,
  1787. uint32_t len, const char *body)
  1788. {
  1789. origin_circuit_t *circ = NULL;
  1790. routerinfo_t *ri = NULL;
  1791. uint8_t new_purpose;
  1792. smartlist_t *args;
  1793. const char *command =
  1794. for_circuits ? "SETCIRCUITPURPOSE" : "SETROUTERPURPOSE";
  1795. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1796. args = getargs_helper(command, conn, body, 2, -1);
  1797. if (!args)
  1798. goto done;
  1799. if (for_circuits) {
  1800. if (!(circ = get_circ(smartlist_get(args,0)))) {
  1801. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1802. (char*)smartlist_get(args, 0));
  1803. goto done;
  1804. }
  1805. } else {
  1806. if (!(ri = router_get_by_nickname(smartlist_get(args,0), 0))) {
  1807. connection_printf_to_buf(conn, "552 Unknown router \"%s\"\r\n",
  1808. (char*)smartlist_get(args, 0));
  1809. goto done;
  1810. }
  1811. }
  1812. {
  1813. char *purp = smartlist_get(args,1);
  1814. if (get_purpose(&purp, for_circuits, &new_purpose) < 0) {
  1815. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  1816. goto done;
  1817. }
  1818. }
  1819. if (for_circuits)
  1820. circ->_base.purpose = new_purpose;
  1821. else
  1822. ri->purpose = new_purpose;
  1823. connection_write_str_to_buf("250 OK\r\n", conn);
  1824. done:
  1825. if (args) {
  1826. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1827. smartlist_free(args);
  1828. }
  1829. return 0;
  1830. }
  1831. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  1832. * stream, and report success or failure. */
  1833. static int
  1834. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  1835. const char *body)
  1836. {
  1837. edge_connection_t *ap_conn = NULL;
  1838. origin_circuit_t *circ = NULL;
  1839. int zero_circ;
  1840. smartlist_t *args;
  1841. crypt_path_t *cpath=NULL;
  1842. int hop=0, hop_line_ok=1;
  1843. (void) len;
  1844. args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
  1845. if (!args)
  1846. return 0;
  1847. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  1848. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  1849. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1850. (char*)smartlist_get(args, 0));
  1851. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  1852. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1853. (char*)smartlist_get(args, 1));
  1854. } else if (circ && smartlist_len(args) > 2) {
  1855. char *hopstring = smartlist_get(args, 2);
  1856. if (!strcasecmpstart(hopstring, "HOP=")) {
  1857. hopstring += strlen("HOP=");
  1858. hop = tor_parse_ulong(hopstring, 10, 0, ULONG_MAX,
  1859. &hop_line_ok, NULL);
  1860. if (!hop_line_ok) { /* broken hop line */
  1861. connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
  1862. }
  1863. }
  1864. }
  1865. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1866. smartlist_free(args);
  1867. if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
  1868. return 0;
  1869. if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT &&
  1870. ap_conn->_base.state != AP_CONN_STATE_CONNECT_WAIT &&
  1871. ap_conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
  1872. connection_write_str_to_buf(
  1873. "555 Connection is not managed by controller.\r\n",
  1874. conn);
  1875. return 0;
  1876. }
  1877. /* Do we need to detach it first? */
  1878. if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT) {
  1879. circuit_t *tmpcirc = circuit_get_by_edge_conn(ap_conn);
  1880. connection_edge_end(ap_conn, END_STREAM_REASON_TIMEOUT);
  1881. /* Un-mark it as ending, since we're going to reuse it. */
  1882. ap_conn->_base.edge_has_sent_end = 0;
  1883. ap_conn->end_reason = 0;
  1884. if (tmpcirc)
  1885. circuit_detach_stream(tmpcirc,ap_conn);
  1886. ap_conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  1887. }
  1888. if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
  1889. connection_write_str_to_buf(
  1890. "551 Can't attach stream to non-open origin circuit\r\n",
  1891. conn);
  1892. return 0;
  1893. }
  1894. if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
  1895. connection_write_str_to_buf(
  1896. "551 Can't attach stream to one-hop circuit.\r\n", conn);
  1897. return 0;
  1898. }
  1899. if (circ && hop>0) {
  1900. /* find this hop in the circuit, and set cpath */
  1901. cpath = circuit_get_cpath_hop(circ, hop);
  1902. if (!cpath) {
  1903. connection_printf_to_buf(conn,
  1904. "551 Circuit doesn't have %d hops.\r\n", hop);
  1905. return 0;
  1906. }
  1907. }
  1908. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
  1909. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  1910. return 0;
  1911. }
  1912. send_control_done(conn);
  1913. return 0;
  1914. }
  1915. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  1916. * descriptor, and report success or failure. */
  1917. static int
  1918. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  1919. const char *body)
  1920. {
  1921. char *desc;
  1922. const char *msg=NULL;
  1923. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  1924. char *cp = memchr(body, '\n', len);
  1925. smartlist_t *args = smartlist_create();
  1926. tor_assert(cp);
  1927. *cp++ = '\0';
  1928. smartlist_split_string(args, body, " ",
  1929. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1930. if (smartlist_len(args)) {
  1931. char *purp = smartlist_get(args,0);
  1932. if (get_purpose(&purp, 0, &purpose) < 0) {
  1933. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  1934. purp);
  1935. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  1936. smartlist_free(args);
  1937. return 0;
  1938. }
  1939. }
  1940. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  1941. smartlist_free(args);
  1942. read_escaped_data(cp, len-(cp-body), 1, &desc);
  1943. switch (router_load_single_router(desc, purpose, &msg)) {
  1944. case -1:
  1945. if (!msg) msg = "Could not parse descriptor";
  1946. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  1947. break;
  1948. case 0:
  1949. if (!msg) msg = "Descriptor not added";
  1950. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  1951. break;
  1952. case 1:
  1953. send_control_done(conn);
  1954. break;
  1955. }
  1956. tor_free(desc);
  1957. return 0;
  1958. }
  1959. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  1960. * address of the named AP stream, and report success or failure. */
  1961. static int
  1962. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  1963. const char *body)
  1964. {
  1965. edge_connection_t *ap_conn = NULL;
  1966. char *new_addr = NULL;
  1967. uint16_t new_port = 0;
  1968. smartlist_t *args;
  1969. (void) len;
  1970. args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
  1971. if (!args)
  1972. return 0;
  1973. if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  1974. || !ap_conn->socks_request) {
  1975. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1976. (char*)smartlist_get(args, 0));
  1977. } else {
  1978. int ok;
  1979. if (smartlist_len(args) > 2) { /* they included a port too */
  1980. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  1981. 10, 1, 65535, &ok, NULL);
  1982. }
  1983. if (!ok) {
  1984. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  1985. (char*)smartlist_get(args, 2));
  1986. } else {
  1987. new_addr = tor_strdup(smartlist_get(args, 1));
  1988. }
  1989. }
  1990. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1991. smartlist_free(args);
  1992. if (!new_addr)
  1993. return 0;
  1994. strlcpy(ap_conn->socks_request->address, new_addr,
  1995. sizeof(ap_conn->socks_request->address));
  1996. if (new_port)
  1997. ap_conn->socks_request->port = new_port;
  1998. tor_free(new_addr);
  1999. send_control_done(conn);
  2000. return 0;
  2001. }
  2002. /** Called when we get a CLOSESTREAM command; try to close the named stream
  2003. * and report success or failure. */
  2004. static int
  2005. handle_control_closestream(control_connection_t *conn, uint32_t len,
  2006. const char *body)
  2007. {
  2008. edge_connection_t *ap_conn=NULL;
  2009. uint8_t reason=0;
  2010. smartlist_t *args;
  2011. int ok;
  2012. (void) len;
  2013. args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
  2014. if (!args)
  2015. return 0;
  2016. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  2017. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2018. (char*)smartlist_get(args, 0));
  2019. else {
  2020. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  2021. &ok, NULL);
  2022. if (!ok) {
  2023. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  2024. (char*)smartlist_get(args, 1));
  2025. ap_conn = NULL;
  2026. }
  2027. }
  2028. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2029. smartlist_free(args);
  2030. if (!ap_conn)
  2031. return 0;
  2032. connection_mark_unattached_ap(ap_conn, reason);
  2033. send_control_done(conn);
  2034. return 0;
  2035. }
  2036. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  2037. * and report success or failure. */
  2038. static int
  2039. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  2040. const char *body)
  2041. {
  2042. origin_circuit_t *circ = NULL;
  2043. int safe = 0;
  2044. smartlist_t *args;
  2045. (void) len;
  2046. args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
  2047. if (!args)
  2048. return 0;
  2049. if (!(circ=get_circ(smartlist_get(args, 0))))
  2050. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2051. (char*)smartlist_get(args, 0));
  2052. else {
  2053. int i;
  2054. for (i=1; i < smartlist_len(args); ++i) {
  2055. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  2056. safe = 1;
  2057. else
  2058. log_info(LD_CONTROL, "Skipping unknown option %s",
  2059. (char*)smartlist_get(args,i));
  2060. }
  2061. }
  2062. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2063. smartlist_free(args);
  2064. if (!circ)
  2065. return 0;
  2066. if (!safe || !circ->p_streams) {
  2067. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
  2068. }
  2069. send_control_done(conn);
  2070. return 0;
  2071. }
  2072. static int
  2073. handle_control_resolve(control_connection_t *conn, uint32_t len,
  2074. const char *body)
  2075. {
  2076. smartlist_t *args;
  2077. int is_reverse = 0;
  2078. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2079. if (!(conn->event_mask & (1L<<EVENT_ADDRMAP))) {
  2080. log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
  2081. "isn't listening for ADDRMAP events. It probably won't see "
  2082. "the answer.");
  2083. }
  2084. args = smartlist_create();
  2085. smartlist_split_string(args, body, " ",
  2086. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2087. if (smartlist_len(args) &&
  2088. !strcasecmp(smartlist_get(args, 0), "mode=reverse")) {
  2089. char *cp = smartlist_get(args, 0);
  2090. smartlist_del_keeporder(args, 0);
  2091. tor_free(cp);
  2092. is_reverse = 1;
  2093. }
  2094. SMARTLIST_FOREACH(args, const char *, arg, {
  2095. dnsserv_launch_request(arg, is_reverse);
  2096. });
  2097. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2098. smartlist_free(args);
  2099. send_control_done(conn);
  2100. return 0;
  2101. }
  2102. /** Called when we get a USEFEATURE command: parse the feature list, and
  2103. * set up the control_connection's options properly. */
  2104. static int
  2105. handle_control_usefeature(control_connection_t *conn,
  2106. uint32_t len,
  2107. const char *body)
  2108. {
  2109. smartlist_t *args;
  2110. int verbose_names = 0, extended_events = 0;
  2111. int bad = 0;
  2112. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2113. args = smartlist_create();
  2114. smartlist_split_string(args, body, " ",
  2115. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2116. SMARTLIST_FOREACH(args, const char *, arg, {
  2117. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  2118. verbose_names = 1;
  2119. else if (!strcasecmp(arg, "EXTENDED_EVENTS")) /* <- documented */
  2120. extended_events = 1;
  2121. else if (!strcasecmp(arg, "EXTENDED_FORMAT")) {
  2122. /* remove this in 0.1.2.4; EXTENDED_FORMAT only ever worked for a
  2123. * little while during 0.1.2.2-alpha-dev. */
  2124. log_warn(LD_GENERAL,
  2125. "EXTENDED_FORMAT is deprecated; use EXTENDED_EVENTS "
  2126. "instead.");
  2127. extended_events = 1;
  2128. } else {
  2129. connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
  2130. arg);
  2131. bad = 1;
  2132. break;
  2133. }
  2134. });
  2135. if (!bad) {
  2136. if (verbose_names) {
  2137. conn->use_long_names = 1;
  2138. control_update_global_event_mask();
  2139. }
  2140. if (extended_events)
  2141. conn->use_extended_events = 1;
  2142. send_control_done(conn);
  2143. }
  2144. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2145. smartlist_free(args);
  2146. return 0;
  2147. }
  2148. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  2149. int
  2150. connection_control_finished_flushing(control_connection_t *conn)
  2151. {
  2152. tor_assert(conn);
  2153. connection_stop_writing(TO_CONN(conn));
  2154. return 0;
  2155. }
  2156. /** Called when <b>conn</b> has gotten its socket closed. */
  2157. int
  2158. connection_control_reached_eof(control_connection_t *conn)
  2159. {
  2160. tor_assert(conn);
  2161. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  2162. connection_mark_for_close(TO_CONN(conn));
  2163. return 0;
  2164. }
  2165. /** Called when data has arrived on a v1 control connection: Try to fetch
  2166. * commands from conn->inbuf, and execute them.
  2167. */
  2168. int
  2169. connection_control_process_inbuf(control_connection_t *conn)
  2170. {
  2171. size_t data_len;
  2172. int cmd_len;
  2173. char *args;
  2174. tor_assert(conn);
  2175. tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN ||
  2176. conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH);
  2177. if (!conn->incoming_cmd) {
  2178. conn->incoming_cmd = tor_malloc(1024);
  2179. conn->incoming_cmd_len = 1024;
  2180. conn->incoming_cmd_cur_len = 0;
  2181. }
  2182. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
  2183. peek_buf_has_control0_command(conn->_base.inbuf)) {
  2184. /* Detect v0 commands and send a "no more v0" message. */
  2185. size_t body_len;
  2186. char buf[128];
  2187. set_uint16(buf+2, htons(0x0000)); /* type == error */
  2188. set_uint16(buf+4, htons(0x0001)); /* code == internal error */
  2189. strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.2.0.x "
  2190. "and later; use Tor 0.1.2.x or upgrade your controller",
  2191. sizeof(buf)-6);
  2192. body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
  2193. set_uint16(buf+0, htons(body_len));
  2194. connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
  2195. connection_mark_for_close(TO_CONN(conn));
  2196. conn->_base.hold_open_until_flushed = 1;
  2197. return 0;
  2198. }
  2199. again:
  2200. while (1) {
  2201. size_t last_idx;
  2202. int r;
  2203. /* First, fetch a line. */
  2204. do {
  2205. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  2206. r = fetch_from_buf_line(conn->_base.inbuf,
  2207. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  2208. &data_len);
  2209. if (r == 0)
  2210. /* Line not all here yet. Wait. */
  2211. return 0;
  2212. else if (r == -1) {
  2213. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  2214. conn->incoming_cmd_len *= 2;
  2215. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  2216. conn->incoming_cmd_len);
  2217. }
  2218. } while (r != 1);
  2219. tor_assert(data_len);
  2220. last_idx = conn->incoming_cmd_cur_len;
  2221. conn->incoming_cmd_cur_len += data_len;
  2222. /* We have appended a line to incoming_cmd. Is the command done? */
  2223. if (last_idx == 0 && *conn->incoming_cmd != '+')
  2224. /* One line command, didn't start with '+'. */
  2225. break;
  2226. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  2227. !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  2228. /* Just appended ".\r\n"; we're done. Remove it. */
  2229. conn->incoming_cmd_cur_len -= 3;
  2230. break;
  2231. }
  2232. /* Otherwise, read another line. */
  2233. }
  2234. data_len = conn->incoming_cmd_cur_len;
  2235. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  2236. * recognize it.
  2237. */
  2238. cmd_len = 0;
  2239. while ((size_t)cmd_len < data_len
  2240. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  2241. ++cmd_len;
  2242. data_len -= cmd_len;
  2243. conn->incoming_cmd[cmd_len]='\0';
  2244. args = conn->incoming_cmd+cmd_len+1;
  2245. while (*args == ' ' || *args == '\t') {
  2246. ++args;
  2247. --data_len;
  2248. }
  2249. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  2250. connection_write_str_to_buf("250 closing connection\r\n", conn);
  2251. connection_mark_for_close(TO_CONN(conn));
  2252. return 0;
  2253. }
  2254. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
  2255. strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2256. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  2257. conn->incoming_cmd_cur_len = 0;
  2258. goto again;
  2259. }
  2260. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  2261. if (handle_control_setconf(conn, data_len, args))
  2262. return -1;
  2263. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  2264. if (handle_control_resetconf(conn, data_len, args))
  2265. return -1;
  2266. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  2267. if (handle_control_getconf(conn, data_len, args))
  2268. return -1;
  2269. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  2270. if (handle_control_setevents(conn, data_len, args))
  2271. return -1;
  2272. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2273. if (handle_control_authenticate(conn, data_len, args))
  2274. return -1;
  2275. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  2276. if (handle_control_saveconf(conn, data_len, args))
  2277. return -1;
  2278. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  2279. if (handle_control_signal(conn, data_len, args))
  2280. return -1;
  2281. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  2282. if (handle_control_mapaddress(conn, data_len, args))
  2283. return -1;
  2284. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  2285. if (handle_control_getinfo(conn, data_len, args))
  2286. return -1;
  2287. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  2288. if (handle_control_extendcircuit(conn, data_len, args))
  2289. return -1;
  2290. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  2291. if (handle_control_setpurpose(conn, 1, data_len, args))
  2292. return -1;
  2293. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  2294. if (handle_control_setpurpose(conn, 0, data_len, args))
  2295. return -1;
  2296. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  2297. if (handle_control_attachstream(conn, data_len, args))
  2298. return -1;
  2299. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  2300. if (handle_control_postdescriptor(conn, data_len, args))
  2301. return -1;
  2302. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  2303. if (handle_control_redirectstream(conn, data_len, args))
  2304. return -1;
  2305. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  2306. if (handle_control_closestream(conn, data_len, args))
  2307. return -1;
  2308. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  2309. if (handle_control_closecircuit(conn, data_len, args))
  2310. return -1;
  2311. } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
  2312. if (handle_control_usefeature(conn, data_len, args))
  2313. return -1;
  2314. } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
  2315. if (handle_control_resolve(conn, data_len, args))
  2316. return -1;
  2317. } else {
  2318. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  2319. conn->incoming_cmd);
  2320. }
  2321. conn->incoming_cmd_cur_len = 0;
  2322. goto again;
  2323. }
  2324. /** Convert a numeric reason for destroying a circuit into a string for a
  2325. * CIRCUIT event. */
  2326. static const char *
  2327. circuit_end_reason_to_string(int reason)
  2328. {
  2329. if (reason >= 0 && reason & END_CIRC_REASON_FLAG_REMOTE)
  2330. reason &= ~END_CIRC_REASON_FLAG_REMOTE;
  2331. switch (reason) {
  2332. case END_CIRC_AT_ORIGIN:
  2333. /* This shouldn't get passed here; it's a catch-all reason. */
  2334. return "ORIGIN";
  2335. case END_CIRC_REASON_NONE:
  2336. /* This shouldn't get passed here; it's a catch-all reason. */
  2337. return "NONE";
  2338. case END_CIRC_REASON_TORPROTOCOL:
  2339. return "TORPROTOCOL";
  2340. case END_CIRC_REASON_INTERNAL:
  2341. return "INTERNAL";
  2342. case END_CIRC_REASON_REQUESTED:
  2343. return "REQUESTED";
  2344. case END_CIRC_REASON_HIBERNATING:
  2345. return "HIBERNATING";
  2346. case END_CIRC_REASON_RESOURCELIMIT:
  2347. return "RESOURCELIMIT";
  2348. case END_CIRC_REASON_CONNECTFAILED:
  2349. return "CONNECTFAILED";
  2350. case END_CIRC_REASON_OR_IDENTITY:
  2351. return "OR_IDENTITY";
  2352. case END_CIRC_REASON_OR_CONN_CLOSED:
  2353. return "OR_CONN_CLOSED";
  2354. case END_CIRC_REASON_FINISHED:
  2355. return "FINISHED";
  2356. case END_CIRC_REASON_TIMEOUT:
  2357. return "TIMEOUT";
  2358. case END_CIRC_REASON_DESTROYED:
  2359. return "DESTROYED";
  2360. case END_CIRC_REASON_NOPATH:
  2361. return "NOPATH";
  2362. case END_CIRC_REASON_NOSUCHSERVICE:
  2363. return "NOSUCHSERVICE";
  2364. default:
  2365. log_warn(LD_BUG, "Unrecognized reason code %d", (int)reason);
  2366. return NULL;
  2367. }
  2368. }
  2369. /** Something has happened to circuit <b>circ</b>: tell any interested
  2370. * control connections. */
  2371. int
  2372. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
  2373. int reason_code)
  2374. {
  2375. const char *status;
  2376. char reason_buf[64];
  2377. int providing_reason=0;
  2378. char *path=NULL;
  2379. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  2380. return 0;
  2381. tor_assert(circ);
  2382. if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS))
  2383. path = circuit_list_path(circ,0);
  2384. switch (tp)
  2385. {
  2386. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2387. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  2388. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  2389. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  2390. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  2391. default:
  2392. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2393. return 0;
  2394. }
  2395. if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
  2396. const char *reason_str = circuit_end_reason_to_string(reason_code);
  2397. char *reason = NULL;
  2398. providing_reason=1;
  2399. if (!reason_str) {
  2400. reason = tor_malloc(16);
  2401. tor_snprintf(reason, 16, "UNKNOWN_%d", reason_code);
  2402. reason_str = reason;
  2403. }
  2404. if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
  2405. tor_snprintf(reason_buf, sizeof(reason_buf),
  2406. "REASON=DESTROYED REMOTE_REASON=%s", reason_str);
  2407. } else {
  2408. tor_snprintf(reason_buf, sizeof(reason_buf),
  2409. "REASON=%s", reason_str);
  2410. }
  2411. tor_free(reason);
  2412. }
  2413. if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS)) {
  2414. const char *sp = strlen(path) ? " " : "";
  2415. if (providing_reason)
  2416. send_control_event_extended(EVENT_CIRCUIT_STATUS, SHORT_NAMES,
  2417. "650 CIRC %lu %s%s%s@%s\r\n",
  2418. (unsigned long)circ->global_identifier,
  2419. status, sp, path, reason_buf);
  2420. else
  2421. send_control_event_extended(EVENT_CIRCUIT_STATUS, SHORT_NAMES,
  2422. "650 CIRC %lu %s%s%s\r\n",
  2423. (unsigned long)circ->global_identifier,
  2424. status, sp, path);
  2425. }
  2426. if (EVENT_IS_INTERESTING1L(EVENT_CIRCUIT_STATUS)) {
  2427. char *vpath = circuit_list_path_for_controller(circ);
  2428. const char *sp = strlen(vpath) ? " " : "";
  2429. if (providing_reason)
  2430. send_control_event_extended(EVENT_CIRCUIT_STATUS, LONG_NAMES,
  2431. "650 CIRC %lu %s%s%s@%s\r\n",
  2432. (unsigned long)circ->global_identifier,
  2433. status, sp, vpath, reason_buf);
  2434. else
  2435. send_control_event_extended(EVENT_CIRCUIT_STATUS, LONG_NAMES,
  2436. "650 CIRC %lu %s%s%s\r\n",
  2437. (unsigned long)circ->global_identifier,
  2438. status, sp, vpath);
  2439. tor_free(vpath);
  2440. }
  2441. tor_free(path);
  2442. return 0;
  2443. }
  2444. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  2445. * <b>buf</b>, determine the address:port combination requested on
  2446. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  2447. * failure. */
  2448. static int
  2449. write_stream_target_to_buf(edge_connection_t *conn, char *buf, size_t len)
  2450. {
  2451. char buf2[256];
  2452. if (conn->chosen_exit_name)
  2453. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  2454. return -1;
  2455. if (tor_snprintf(buf, len, "%s%s%s:%d",
  2456. conn->socks_request->address,
  2457. conn->chosen_exit_name ? buf2 : "",
  2458. !conn->chosen_exit_name &&
  2459. connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
  2460. conn->socks_request->port)<0)
  2461. return -1;
  2462. return 0;
  2463. }
  2464. /** Convert the reason for ending a stream <b>reason</b> into the format used
  2465. * in STREAM events. Return NULL if the reason is unrecognized. */
  2466. static const char *
  2467. stream_end_reason_to_string(int reason)
  2468. {
  2469. reason &= END_STREAM_REASON_MASK;
  2470. switch (reason) {
  2471. case END_STREAM_REASON_MISC: return "MISC";
  2472. case END_STREAM_REASON_RESOLVEFAILED: return "RESOLVEFAILED";
  2473. case END_STREAM_REASON_CONNECTREFUSED: return "CONNECTREFUSED";
  2474. case END_STREAM_REASON_EXITPOLICY: return "EXITPOLICY";
  2475. case END_STREAM_REASON_DESTROY: return "DESTROY";
  2476. case END_STREAM_REASON_DONE: return "DONE";
  2477. case END_STREAM_REASON_TIMEOUT: return "TIMEOUT";
  2478. case END_STREAM_REASON_HIBERNATING: return "HIBERNATING";
  2479. case END_STREAM_REASON_INTERNAL: return "INTERNAL";
  2480. case END_STREAM_REASON_RESOURCELIMIT: return "RESOURCELIMIT";
  2481. case END_STREAM_REASON_CONNRESET: return "CONNRESET";
  2482. case END_STREAM_REASON_TORPROTOCOL: return "TORPROTOCOL";
  2483. case END_STREAM_REASON_NOTDIRECTORY: return "NOTDIRECTORY";
  2484. case END_STREAM_REASON_CANT_ATTACH: return "CANT_ATTACH";
  2485. case END_STREAM_REASON_NET_UNREACHABLE: return "NET_UNREACHABLE";
  2486. case END_STREAM_REASON_SOCKSPROTOCOL: return "SOCKS_PROTOCOL";
  2487. default: return NULL;
  2488. }
  2489. }
  2490. /** Something has happened to the stream associated with AP connection
  2491. * <b>conn</b>: tell any interested control connections. */
  2492. int
  2493. control_event_stream_status(edge_connection_t *conn, stream_status_event_t tp,
  2494. int reason_code)
  2495. {
  2496. char reason_buf[64];
  2497. char addrport_buf[64];
  2498. const char *status;
  2499. circuit_t *circ;
  2500. origin_circuit_t *origin_circ = NULL;
  2501. char buf[256];
  2502. tor_assert(conn->socks_request);
  2503. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  2504. return 0;
  2505. if (tp == STREAM_EVENT_CLOSED &&
  2506. (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
  2507. return 0;
  2508. write_stream_target_to_buf(conn, buf, sizeof(buf));
  2509. reason_buf[0] = '\0';
  2510. switch (tp)
  2511. {
  2512. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  2513. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  2514. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  2515. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  2516. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  2517. case STREAM_EVENT_NEW: status = "NEW"; break;
  2518. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  2519. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  2520. case STREAM_EVENT_REMAP: status = "REMAP"; break;
  2521. default:
  2522. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2523. return 0;
  2524. }
  2525. if (reason_code && (tp == STREAM_EVENT_FAILED ||
  2526. tp == STREAM_EVENT_CLOSED ||
  2527. tp == STREAM_EVENT_FAILED_RETRIABLE)) {
  2528. const char *reason_str = stream_end_reason_to_string(reason_code);
  2529. char *r = NULL;
  2530. if (!reason_str) {
  2531. r = tor_malloc(16);
  2532. tor_snprintf(r, 16, "UNKNOWN_%d", reason_code);
  2533. reason_str = r;
  2534. }
  2535. if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
  2536. tor_snprintf(reason_buf, sizeof(reason_buf),
  2537. "REASON=END REMOTE_REASON=%s", reason_str);
  2538. else
  2539. tor_snprintf(reason_buf, sizeof(reason_buf),
  2540. "REASON=%s", reason_str);
  2541. tor_free(r);
  2542. } else if (reason_code && tp == STREAM_EVENT_REMAP) {
  2543. switch (reason_code) {
  2544. case REMAP_STREAM_SOURCE_CACHE:
  2545. strlcpy(reason_buf, "SOURCE=CACHE", sizeof(reason_buf));
  2546. break;
  2547. case REMAP_STREAM_SOURCE_EXIT:
  2548. strlcpy(reason_buf, "SOURCE=EXIT", sizeof(reason_buf));
  2549. break;
  2550. default:
  2551. tor_snprintf(reason_buf, sizeof(reason_buf), "REASON=UNKNOWN_%d",
  2552. reason_code);
  2553. break;
  2554. }
  2555. }
  2556. if (tp == STREAM_EVENT_NEW) {
  2557. tor_snprintf(addrport_buf,sizeof(addrport_buf), "%sSOURCE_ADDR=%s:%d",
  2558. strlen(reason_buf) ? " " : "",
  2559. TO_CONN(conn)->address, TO_CONN(conn)->port );
  2560. } else {
  2561. addrport_buf[0] = '\0';
  2562. }
  2563. circ = circuit_get_by_edge_conn(conn);
  2564. if (circ && CIRCUIT_IS_ORIGIN(circ))
  2565. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2566. send_control_event_extended(EVENT_STREAM_STATUS, ALL_NAMES,
  2567. "650 STREAM %lu %s %lu %s@%s%s\r\n",
  2568. (unsigned long)conn->global_identifier, status,
  2569. origin_circ?
  2570. (unsigned long)origin_circ->global_identifier : 0ul,
  2571. buf, reason_buf, addrport_buf);
  2572. /* XXX need to specify its intended exit, etc? */
  2573. return 0;
  2574. }
  2575. /** Figure out the best name for the target router of an OR connection
  2576. * <b>conn</b>, and write it into the <b>len</b>-character buffer
  2577. * <b>name</b>. Use verbose names if <b>long_names</b> is set. */
  2578. static void
  2579. orconn_target_get_name(int long_names,
  2580. char *name, size_t len, or_connection_t *conn)
  2581. {
  2582. if (! long_names) {
  2583. if (conn->nickname)
  2584. strlcpy(name, conn->nickname, len);
  2585. else
  2586. tor_snprintf(name, len, "%s:%d",
  2587. conn->_base.address, conn->_base.port);
  2588. } else {
  2589. routerinfo_t *ri = router_get_by_digest(conn->identity_digest);
  2590. if (ri) {
  2591. tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
  2592. router_get_verbose_nickname(name, ri);
  2593. } else if (! tor_digest_is_zero(conn->identity_digest)) {
  2594. name[0] = '$';
  2595. base16_encode(name+1, len-1, conn->identity_digest,
  2596. DIGEST_LEN);
  2597. } else {
  2598. tor_snprintf(name, len, "%s:%d",
  2599. conn->_base.address, conn->_base.port);
  2600. }
  2601. }
  2602. }
  2603. /** Convert a TOR_TLS_* error code into an END_OR_CONN_* reason. */
  2604. int
  2605. control_tls_error_to_reason(int e)
  2606. {
  2607. switch (e) {
  2608. case TOR_TLS_ERROR_IO:
  2609. return END_OR_CONN_REASON_TLS_IO_ERROR;
  2610. case TOR_TLS_ERROR_CONNREFUSED:
  2611. return END_OR_CONN_REASON_TCP_REFUSED;
  2612. case TOR_TLS_ERROR_CONNRESET:
  2613. return END_OR_CONN_REASON_TLS_CONNRESET;
  2614. case TOR_TLS_ERROR_NO_ROUTE:
  2615. return END_OR_CONN_REASON_TLS_NO_ROUTE;
  2616. case TOR_TLS_ERROR_TIMEOUT:
  2617. return END_OR_CONN_REASON_TLS_TIMEOUT;
  2618. case TOR_TLS_WANTREAD:
  2619. case TOR_TLS_WANTWRITE:
  2620. case TOR_TLS_CLOSE:
  2621. case TOR_TLS_DONE:
  2622. return END_OR_CONN_REASON_DONE;
  2623. default:
  2624. return END_OR_CONN_REASON_TLS_MISC;
  2625. }
  2626. }
  2627. /** Convert the reason for ending an OR connection <b>r</b> into the format
  2628. * used in ORCONN events. Return NULL if the reason is unrecognized. */
  2629. static const char *
  2630. or_conn_end_reason_to_string(int r)
  2631. {
  2632. switch (r) {
  2633. case END_OR_CONN_REASON_DONE:
  2634. return "REASON=DONE";
  2635. case END_OR_CONN_REASON_TCP_REFUSED:
  2636. return "REASON=CONNECTREFUSED";
  2637. case END_OR_CONN_REASON_OR_IDENTITY:
  2638. return "REASON=IDENTITY";
  2639. case END_OR_CONN_REASON_TLS_CONNRESET:
  2640. return "REASON=CONNECTRESET";
  2641. case END_OR_CONN_REASON_TLS_TIMEOUT:
  2642. return "REASON=TIMEOUT";
  2643. case END_OR_CONN_REASON_TLS_NO_ROUTE:
  2644. return "REASON=NOROUTE";
  2645. case END_OR_CONN_REASON_TLS_IO_ERROR:
  2646. return "REASON=IOERROR";
  2647. case END_OR_CONN_REASON_TLS_MISC:
  2648. return "REASON=MISC";
  2649. case 0:
  2650. return "";
  2651. default:
  2652. log_warn(LD_BUG, "Unrecognized or_conn reason code %d", r);
  2653. return "REASON=BOGUS";
  2654. }
  2655. }
  2656. /** Called when the status of an OR connection <b>conn</b> changes: tell any
  2657. * interested control connections. <b>tp</b> is the new status for the
  2658. * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
  2659. * may be the reason why.
  2660. */
  2661. int
  2662. control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
  2663. int reason)
  2664. {
  2665. int ncircs = 0;
  2666. const char *status;
  2667. char name[128];
  2668. char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
  2669. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  2670. return 0;
  2671. switch (tp)
  2672. {
  2673. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2674. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  2675. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  2676. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  2677. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  2678. default:
  2679. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2680. return 0;
  2681. }
  2682. ncircs = circuit_count_pending_on_or_conn(conn);
  2683. ncircs += conn->n_circuits;
  2684. if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
  2685. tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
  2686. reason ? " " : "", ncircs);
  2687. }
  2688. if (EVENT_IS_INTERESTING1S(EVENT_OR_CONN_STATUS)) {
  2689. orconn_target_get_name(0, name, sizeof(name), conn);
  2690. send_control_event_extended(EVENT_OR_CONN_STATUS, SHORT_NAMES,
  2691. "650 ORCONN %s %s@%s%s\r\n",
  2692. name, status,
  2693. or_conn_end_reason_to_string(reason), ncircs_buf);
  2694. }
  2695. if (EVENT_IS_INTERESTING1L(EVENT_OR_CONN_STATUS)) {
  2696. orconn_target_get_name(1, name, sizeof(name), conn);
  2697. send_control_event_extended(EVENT_OR_CONN_STATUS, LONG_NAMES,
  2698. "650 ORCONN %s %s@%s%s\r\n",
  2699. name, status,
  2700. or_conn_end_reason_to_string(reason), ncircs_buf);
  2701. }
  2702. return 0;
  2703. }
  2704. /** A second or more has elapsed: tell any interested control
  2705. * connections how much bandwidth streams have used. */
  2706. int
  2707. control_event_stream_bandwidth_used(void)
  2708. {
  2709. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  2710. smartlist_t *conns = get_connection_array();
  2711. edge_connection_t *edge_conn;
  2712. SMARTLIST_FOREACH(conns, connection_t *, conn,
  2713. {
  2714. if (conn->type != CONN_TYPE_AP)
  2715. continue;
  2716. edge_conn = TO_EDGE_CONN(conn);
  2717. if (!edge_conn->n_read && !edge_conn->n_written)
  2718. continue;
  2719. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_NAMES,
  2720. "650 STREAM_BW %lu %lu %lu\r\n",
  2721. (unsigned long)edge_conn->global_identifier,
  2722. (unsigned long)edge_conn->n_read,
  2723. (unsigned long)edge_conn->n_written);
  2724. edge_conn->n_written = edge_conn->n_read = 0;
  2725. });
  2726. }
  2727. return 0;
  2728. }
  2729. /** A second or more has elapsed: tell any interested control
  2730. * connections how much bandwidth we used. */
  2731. int
  2732. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  2733. {
  2734. if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
  2735. send_control_event(EVENT_BANDWIDTH_USED, ALL_NAMES,
  2736. "650 BW %lu %lu\r\n",
  2737. (unsigned long)n_read,
  2738. (unsigned long)n_written);
  2739. }
  2740. return 0;
  2741. }
  2742. /** Called when we are sending a log message to the controllers: suspend
  2743. * sending further log messages to the controllers until we're done. Used by
  2744. * CONN_LOG_PROTECT. */
  2745. void
  2746. disable_control_logging(void)
  2747. {
  2748. ++disable_log_messages;
  2749. }
  2750. /** We're done sending a log message to the controllers: re-enable controller
  2751. * logging. Used by CONN_LOG_PROTECT. */
  2752. void
  2753. enable_control_logging(void)
  2754. {
  2755. if (--disable_log_messages < 0)
  2756. tor_assert(0);
  2757. }
  2758. /** We got a log message: tell any interested control connections. */
  2759. void
  2760. control_event_logmsg(int severity, uint32_t domain, const char *msg)
  2761. {
  2762. int event;
  2763. if (disable_log_messages)
  2764. return;
  2765. if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
  2766. severity <= LOG_NOTICE) {
  2767. char *esc = esc_for_log(msg);
  2768. ++disable_log_messages;
  2769. control_event_general_status(severity, "BUG REASON=\"%s\"", esc);
  2770. --disable_log_messages;
  2771. tor_free(esc);
  2772. }
  2773. event = log_severity_to_event(severity);
  2774. if (event >= 0 && EVENT_IS_INTERESTING(event)) {
  2775. char *b = NULL;
  2776. const char *s;
  2777. if (strchr(msg, '\n')) {
  2778. char *cp;
  2779. b = tor_strdup(msg);
  2780. for (cp = b; *cp; ++cp)
  2781. if (*cp == '\r' || *cp == '\n')
  2782. *cp = ' ';
  2783. }
  2784. switch (severity) {
  2785. case LOG_DEBUG: s = "DEBUG"; break;
  2786. case LOG_INFO: s = "INFO"; break;
  2787. case LOG_NOTICE: s = "NOTICE"; break;
  2788. case LOG_WARN: s = "WARN"; break;
  2789. case LOG_ERR: s = "ERR"; break;
  2790. default: s = "UnknownLogSeverity"; break;
  2791. }
  2792. ++disable_log_messages;
  2793. send_control_event(event, ALL_NAMES, "650 %s %s\r\n", s, b?b:msg);
  2794. --disable_log_messages;
  2795. tor_free(b);
  2796. }
  2797. }
  2798. /** Called whenever we receive new router descriptors: tell any
  2799. * interested control connections. <b>routers</b> is a list of
  2800. * DIGEST_LEN-byte identity digests.
  2801. */
  2802. int
  2803. control_event_descriptors_changed(smartlist_t *routers)
  2804. {
  2805. size_t len;
  2806. char *msg;
  2807. smartlist_t *identities = NULL;
  2808. char buf[HEX_DIGEST_LEN+1];
  2809. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  2810. return 0;
  2811. if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC)) {
  2812. identities = smartlist_create();
  2813. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  2814. {
  2815. base16_encode(buf,sizeof(buf),r->cache_info.identity_digest,DIGEST_LEN);
  2816. smartlist_add(identities, tor_strdup(buf));
  2817. });
  2818. }
  2819. if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC)) {
  2820. char *ids = smartlist_join_strings(identities, " ", 0, &len);
  2821. size_t ids_len = strlen(ids)+32;
  2822. msg = tor_malloc(ids_len);
  2823. tor_snprintf(msg, ids_len, "650 NEWDESC %s\r\n", ids);
  2824. send_control_event_string(EVENT_NEW_DESC, SHORT_NAMES|ALL_FORMATS, msg);
  2825. tor_free(ids);
  2826. tor_free(msg);
  2827. }
  2828. if (EVENT_IS_INTERESTING1L(EVENT_NEW_DESC)) {
  2829. smartlist_t *names = smartlist_create();
  2830. char *ids;
  2831. size_t names_len;
  2832. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  2833. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  2834. router_get_verbose_nickname(b, ri);
  2835. smartlist_add(names, b);
  2836. });
  2837. ids = smartlist_join_strings(names, " ", 0, &names_len);
  2838. names_len = strlen(ids)+32;
  2839. msg = tor_malloc(names_len);
  2840. tor_snprintf(msg, names_len, "650 NEWDESC %s\r\n", ids);
  2841. send_control_event_string(EVENT_NEW_DESC, LONG_NAMES|ALL_FORMATS, msg);
  2842. tor_free(ids);
  2843. tor_free(msg);
  2844. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  2845. smartlist_free(names);
  2846. }
  2847. if (identities) {
  2848. SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
  2849. smartlist_free(identities);
  2850. }
  2851. return 0;
  2852. }
  2853. /** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
  2854. * <b>expires</b> values less than 3 are special; see connection_edge.c.
  2855. * DOCDOC source. */
  2856. int
  2857. control_event_address_mapped(const char *from, const char *to, time_t expires,
  2858. const char *error)
  2859. {
  2860. if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
  2861. return 0;
  2862. if (expires < 3 || expires == TIME_MAX)
  2863. send_control_event_extended(EVENT_ADDRMAP, ALL_NAMES,
  2864. "650 ADDRMAP %s %s NEVER@%s\r\n", from, to,
  2865. error);
  2866. else {
  2867. char buf[ISO_TIME_LEN+1];
  2868. format_local_iso_time(buf,expires);
  2869. send_control_event_extended(EVENT_ADDRMAP, ALL_NAMES,
  2870. "650 ADDRMAP %s %s \"%s\"@%s\r\n",
  2871. from, to, buf, error);
  2872. }
  2873. return 0;
  2874. }
  2875. /** The authoritative dirserver has received a new descriptor that
  2876. * has passed basic syntax checks and is properly self-signed.
  2877. *
  2878. * Notify any interested party of the new descriptor and what has
  2879. * been done with it, and also optionally give an explanation/reason. */
  2880. int
  2881. control_event_or_authdir_new_descriptor(const char *action,
  2882. const char *desc, size_t desclen,
  2883. const char *msg)
  2884. {
  2885. char firstline[1024];
  2886. char *buf;
  2887. int totallen;
  2888. char *esc = NULL;
  2889. size_t esclen;
  2890. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  2891. return 0;
  2892. tor_snprintf(firstline, sizeof(firstline),
  2893. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  2894. action,
  2895. msg ? msg : "");
  2896. /* Escape the server descriptor properly */
  2897. esclen = write_escaped_data(desc, desclen, 1, &esc);
  2898. totallen = strlen(firstline) + esclen + 1;
  2899. buf = tor_malloc(totallen);
  2900. strlcpy(buf, firstline, totallen);
  2901. strlcpy(buf+strlen(firstline), esc, totallen);
  2902. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_NAMES|ALL_FORMATS,
  2903. buf);
  2904. tor_free(esc);
  2905. tor_free(buf);
  2906. return 0;
  2907. }
  2908. /** Called when the local_routerstatus_ts <b>statuses</b> have changed: sends
  2909. * an NS event to any controller that cares. */
  2910. int
  2911. control_event_networkstatus_changed(smartlist_t *statuses)
  2912. {
  2913. smartlist_t *strs;
  2914. char *s;
  2915. if (!EVENT_IS_INTERESTING(EVENT_NS) || !smartlist_len(statuses))
  2916. return 0;
  2917. strs = smartlist_create();
  2918. smartlist_add(strs, tor_strdup("650+NS\r\n"));
  2919. SMARTLIST_FOREACH(statuses, local_routerstatus_t *, rs,
  2920. {
  2921. s = networkstatus_getinfo_helper_single(&rs->status);
  2922. if (!s) continue;
  2923. smartlist_add(strs, s);
  2924. });
  2925. smartlist_add(strs, tor_strdup("\r\n.\r\n"));
  2926. /* XXX020 the above strdup has an extra \r\n in it, resulting in
  2927. * a blank line in the NS output. Can we remove it, or is that
  2928. * bad since the output of networkstatus_getinfo_helper_single()
  2929. * only adds \n, not \r\n? */
  2930. s = smartlist_join_strings(strs, "", 0, NULL);
  2931. SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
  2932. smartlist_free(strs);
  2933. send_control_event_string(EVENT_NS, ALL_NAMES|ALL_FORMATS, s);
  2934. tor_free(s);
  2935. return 0;
  2936. }
  2937. /** Called when a single local_routerstatus_t has changed: Sends an NS event
  2938. * to any countroller that cares. */
  2939. int
  2940. control_event_networkstatus_changed_single(local_routerstatus_t *rs)
  2941. {
  2942. smartlist_t *statuses;
  2943. int r;
  2944. if (!EVENT_IS_INTERESTING(EVENT_NS))
  2945. return 0;
  2946. statuses = smartlist_create();
  2947. smartlist_add(statuses, rs);
  2948. r = control_event_networkstatus_changed(statuses);
  2949. smartlist_free(statuses);
  2950. return r;
  2951. }
  2952. /** Our own router descriptor has changed; tell any controllers that care.
  2953. */
  2954. int
  2955. control_event_my_descriptor_changed(void)
  2956. {
  2957. send_control_event(EVENT_DESCCHANGED, ALL_NAMES, "650 DESCCHANGED\r\n");
  2958. return 0;
  2959. }
  2960. /** Helper: sends a status event where <b>type</b> is one of
  2961. * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
  2962. * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
  2963. * string corresponding to <b>args</b>. */
  2964. static int
  2965. control_event_status(int type, int severity, const char *format, va_list args)
  2966. {
  2967. char format_buf[160];
  2968. const char *status, *sev;
  2969. switch (type) {
  2970. case EVENT_STATUS_GENERAL:
  2971. status = "STATUS_GENERAL";
  2972. break;
  2973. case EVENT_STATUS_CLIENT:
  2974. status = "STATUS_CLIENT";
  2975. break;
  2976. case EVENT_STATUS_SERVER:
  2977. status = "STATUS_SEVER";
  2978. break;
  2979. default:
  2980. log_warn(LD_BUG, "Unrecognized status type %d", type);
  2981. return -1;
  2982. }
  2983. switch (severity) {
  2984. case LOG_NOTICE:
  2985. sev = "NOTICE";
  2986. break;
  2987. case LOG_WARN:
  2988. sev = "WARN";
  2989. break;
  2990. case LOG_ERR:
  2991. sev = "ERR";
  2992. break;
  2993. default:
  2994. log_warn(LD_BUG, "Unrecognized status severity %d", severity);
  2995. return -1;
  2996. }
  2997. if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s %s\r\n",
  2998. status, sev, format)<0) {
  2999. log_warn(LD_BUG, "Format string too long.");
  3000. return -1;
  3001. }
  3002. send_control_event_impl(type, ALL_NAMES|ALL_FORMATS, 0, format_buf, args);
  3003. return 0;
  3004. }
  3005. /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
  3006. * by formatting the arguments using the printf-style <b>format</b>. */
  3007. int
  3008. control_event_general_status(int severity, const char *format, ...)
  3009. {
  3010. va_list ap;
  3011. int r;
  3012. if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
  3013. return 0;
  3014. va_start(ap, format);
  3015. r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
  3016. va_end(ap);
  3017. return r;
  3018. }
  3019. /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
  3020. * by formatting the arguments using the printf-style <b>format</b>. */
  3021. int
  3022. control_event_client_status(int severity, const char *format, ...)
  3023. {
  3024. va_list ap;
  3025. int r;
  3026. if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
  3027. return 0;
  3028. va_start(ap, format);
  3029. r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
  3030. va_end(ap);
  3031. return r;
  3032. }
  3033. /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
  3034. * by formatting the arguments using the printf-style <b>format</b>. */
  3035. int
  3036. control_event_server_status(int severity, const char *format, ...)
  3037. {
  3038. va_list ap;
  3039. int r;
  3040. if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
  3041. return 0;
  3042. va_start(ap, format);
  3043. r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
  3044. va_end(ap);
  3045. return r;
  3046. }
  3047. /** Called when the status of an entry guard with the given <b>nickname</b>
  3048. * and identity <b>digest</b> has changed to <b>status</b>: tells any
  3049. * controllers that care. */
  3050. int
  3051. control_event_guard(const char *nickname, const char *digest,
  3052. const char *status)
  3053. {
  3054. char hbuf[HEX_DIGEST_LEN+1];
  3055. base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
  3056. if (!EVENT_IS_INTERESTING(EVENT_GUARD))
  3057. return 0;
  3058. if (EVENT_IS_INTERESTING1L(EVENT_GUARD)) {
  3059. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  3060. routerinfo_t *ri = router_get_by_digest(digest);
  3061. if (ri) {
  3062. router_get_verbose_nickname(buf, ri);
  3063. } else {
  3064. tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
  3065. }
  3066. send_control_event(EVENT_GUARD, LONG_NAMES,
  3067. "650 GUARD ENTRY %s %s\r\n", buf, status);
  3068. }
  3069. if (EVENT_IS_INTERESTING1S(EVENT_GUARD)) {
  3070. send_control_event(EVENT_GUARD, SHORT_NAMES,
  3071. "650 GUARD ENTRY $%s %s\r\n", hbuf, status);
  3072. }
  3073. return 0;
  3074. }
  3075. /** Choose a random authentication cookie and write it to disk.
  3076. * Anybody who can read the cookie from disk will be considered
  3077. * authorized to use the control connection. */
  3078. int
  3079. init_cookie_authentication(int enabled)
  3080. {
  3081. char fname[512];
  3082. if (!enabled) {
  3083. authentication_cookie_is_set = 0;
  3084. return 0;
  3085. }
  3086. tor_snprintf(fname, sizeof(fname), "%s"PATH_SEPARATOR"control_auth_cookie",
  3087. get_options()->DataDirectory);
  3088. crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  3089. authentication_cookie_is_set = 1;
  3090. if (write_bytes_to_file(fname, authentication_cookie,
  3091. AUTHENTICATION_COOKIE_LEN, 1)) {
  3092. log_warn(LD_FS,"Error writing authentication cookie.");
  3093. return -1;
  3094. }
  3095. return 0;
  3096. }