control.c 107 KB

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