control.c 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602
  1. /* Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. const char control_c_id[] = "$Id$";
  5. /**
  6. * \file control.c
  7. * \brief Implementation for Tor's control-socket interface.
  8. **/
  9. #include "or.h"
  10. #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN_V0 || \
  11. (s) == CONTROL_CONN_STATE_OPEN_V1)
  12. #define STATE_IS_V0(s) ((s) == CONTROL_CONN_STATE_NEEDAUTH_V0 || \
  13. (s) == CONTROL_CONN_STATE_OPEN_V0)
  14. /*
  15. * See control-spec.txt and control-spec-v0.txt for full details on protocol(s).
  16. */
  17. /* Recognized message type codes. */
  18. #define CONTROL0_CMD_ERROR 0x0000
  19. #define CONTROL0_CMD_DONE 0x0001
  20. #define CONTROL0_CMD_SETCONF 0x0002
  21. #define CONTROL0_CMD_GETCONF 0x0003
  22. #define CONTROL0_CMD_CONFVALUE 0x0004
  23. #define CONTROL0_CMD_SETEVENTS 0x0005
  24. #define CONTROL0_CMD_EVENT 0x0006
  25. #define CONTROL0_CMD_AUTHENTICATE 0x0007
  26. #define CONTROL0_CMD_SAVECONF 0x0008
  27. #define CONTROL0_CMD_SIGNAL 0x0009
  28. #define CONTROL0_CMD_MAPADDRESS 0x000A
  29. #define CONTROL0_CMD_GETINFO 0x000B
  30. #define CONTROL0_CMD_INFOVALUE 0x000C
  31. #define CONTROL0_CMD_EXTENDCIRCUIT 0x000D
  32. #define CONTROL0_CMD_ATTACHSTREAM 0x000E
  33. #define CONTROL0_CMD_POSTDESCRIPTOR 0x000F
  34. #define CONTROL0_CMD_FRAGMENTHEADER 0x0010
  35. #define CONTROL0_CMD_FRAGMENT 0x0011
  36. #define CONTROL0_CMD_REDIRECTSTREAM 0x0012
  37. #define CONTROL0_CMD_CLOSESTREAM 0x0013
  38. #define CONTROL0_CMD_CLOSECIRCUIT 0x0014
  39. #define _CONTROL0_CMD_MAX_RECOGNIZED 0x0014
  40. /* Recognized error codes. */
  41. #define ERR_UNSPECIFIED 0x0000
  42. #define ERR_INTERNAL 0x0001
  43. #define ERR_UNRECOGNIZED_TYPE 0x0002
  44. #define ERR_SYNTAX 0x0003
  45. #define ERR_UNRECOGNIZED_CONFIG_KEY 0x0004
  46. #define ERR_INVALID_CONFIG_VALUE 0x0005
  47. #define ERR_UNRECOGNIZED_EVENT_CODE 0x0006
  48. #define ERR_UNAUTHORIZED 0x0007
  49. #define ERR_REJECTED_AUTHENTICATION 0x0008
  50. #define ERR_RESOURCE_EXHAUSETED 0x0009
  51. #define ERR_NO_STREAM 0x000A
  52. #define ERR_NO_CIRC 0x000B
  53. #define ERR_NO_ROUTER 0x000C
  54. /* Recognized asynchronous event types. */
  55. #define _EVENT_MIN 0x0001
  56. #define EVENT_CIRCUIT_STATUS 0x0001
  57. #define EVENT_STREAM_STATUS 0x0002
  58. #define EVENT_OR_CONN_STATUS 0x0003
  59. #define EVENT_BANDWIDTH_USED 0x0004
  60. #define EVENT_LOG_OBSOLETE 0x0005
  61. #define EVENT_NEW_DESC 0x0006
  62. #define EVENT_DEBUG_MSG 0x0007
  63. #define EVENT_INFO_MSG 0x0008
  64. #define EVENT_NOTICE_MSG 0x0009
  65. #define EVENT_WARN_MSG 0x000A
  66. #define EVENT_ERR_MSG 0x000B
  67. #define LAST_V0_EVENT 0x000B
  68. #define EVENT_ADDRMAP 0x000C
  69. #define _EVENT_MAX 0x000C
  70. /** Array mapping from message type codes to human-readable message
  71. * type names. Used for compatibility with version 0 of the control
  72. * protocol. */
  73. static const char * CONTROL0_COMMANDS[_CONTROL0_CMD_MAX_RECOGNIZED+1] = {
  74. "error",
  75. "done",
  76. "setconf",
  77. "getconf",
  78. "confvalue",
  79. "setevents",
  80. "events",
  81. "authenticate",
  82. "saveconf",
  83. "signal",
  84. "mapaddress",
  85. "getinfo",
  86. "infovalue",
  87. "extendcircuit",
  88. "attachstream",
  89. "postdescriptor",
  90. "fragmentheader",
  91. "fragment",
  92. };
  93. /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
  94. * connection is interested in events of type <b>e</b>. We use this
  95. * so that we can decide to skip generating event messages that nobody
  96. * has interest in without having to walk over the global connection
  97. * list to find out.
  98. **/
  99. static uint32_t global_event_mask0 = 0;
  100. static uint32_t global_event_mask1 = 0;
  101. /** True iff we have disabled log messages from being sent to the controller */
  102. static int disable_log_messages = 0;
  103. /** Macro: true if any control connection is interested in events of type
  104. * <b>e</b>. */
  105. #define EVENT_IS_INTERESTING0(e) (global_event_mask0 & (1<<(e)))
  106. #define EVENT_IS_INTERESTING1(e) (global_event_mask1 & (1<<(e)))
  107. #define EVENT_IS_INTERESTING(e) \
  108. ((global_event_mask0|global_event_mask1) & (1<<(e)))
  109. /** If we're using cookie-type authentication, how long should our cookies be?
  110. */
  111. #define AUTHENTICATION_COOKIE_LEN 32
  112. /** If true, we've set authentication_cookie to a secret code and
  113. * stored it to disk. */
  114. static int authentication_cookie_is_set = 0;
  115. static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
  116. static void connection_printf_to_buf(connection_t *conn, const char *format, ...)
  117. CHECK_PRINTF(2,3);
  118. /*static*/ size_t write_escaped_data(const char *data, size_t len,
  119. int translate_newlines, char **out);
  120. /*static*/ size_t read_escaped_data(const char *data, size_t len,
  121. int translate_newlines, char **out);
  122. static void send_control0_message(connection_t *conn, uint16_t type,
  123. uint32_t len, const char *body);
  124. static void send_control_done(connection_t *conn);
  125. static void send_control_done2(connection_t *conn, const char *msg, size_t len);
  126. static void send_control0_error(connection_t *conn, uint16_t error,
  127. const char *message);
  128. static void send_control0_event(uint16_t event, uint32_t len, const char *body);
  129. static void send_control1_event(uint16_t event, const char *format, ...)
  130. CHECK_PRINTF(2,3);
  131. static int handle_control_setconf(connection_t *conn, uint32_t len,
  132. char *body);
  133. static int handle_control_resetconf(connection_t *conn, uint32_t len,
  134. char *body);
  135. static int handle_control_getconf(connection_t *conn, uint32_t len,
  136. const char *body);
  137. static int handle_control_setevents(connection_t *conn, uint32_t len,
  138. const char *body);
  139. static int handle_control_authenticate(connection_t *conn, uint32_t len,
  140. const char *body);
  141. static int handle_control_saveconf(connection_t *conn, uint32_t len,
  142. const char *body);
  143. static int handle_control_signal(connection_t *conn, uint32_t len,
  144. const char *body);
  145. static int handle_control_mapaddress(connection_t *conn, uint32_t len,
  146. const char *body);
  147. static int handle_control_getinfo(connection_t *conn, uint32_t len,
  148. const char *body);
  149. static int handle_control_extendcircuit(connection_t *conn, uint32_t len,
  150. const char *body);
  151. static int handle_control_attachstream(connection_t *conn, uint32_t len,
  152. const char *body);
  153. static int handle_control_postdescriptor(connection_t *conn, uint32_t len,
  154. const char *body);
  155. static int handle_control_redirectstream(connection_t *conn, uint32_t len,
  156. const char *body);
  157. static int handle_control_closestream(connection_t *conn, uint32_t len,
  158. const char *body);
  159. static int handle_control_closecircuit(connection_t *conn, uint32_t len,
  160. const char *body);
  161. static int write_stream_target_to_buf(connection_t *conn, char *buf, size_t len);
  162. /** Given a possibly invalid message type code <b>cmd</b>, return a
  163. * human-readable string equivalent. */
  164. static INLINE const char *
  165. control_cmd_to_string(uint16_t cmd)
  166. {
  167. return (cmd<=_CONTROL0_CMD_MAX_RECOGNIZED) ? CONTROL0_COMMANDS[cmd] : "Unknown";
  168. }
  169. /** Given a control event code for a message event, return the corresponding
  170. * log severity. */
  171. static INLINE int
  172. event_to_log_severity(int event)
  173. {
  174. switch (event) {
  175. case EVENT_DEBUG_MSG: return LOG_DEBUG;
  176. case EVENT_INFO_MSG: return LOG_INFO;
  177. case EVENT_NOTICE_MSG: return LOG_NOTICE;
  178. case EVENT_WARN_MSG: return LOG_WARN;
  179. case EVENT_ERR_MSG: return LOG_ERR;
  180. default: return -1;
  181. }
  182. }
  183. /** Given a log severity, return the corresponding control event code. */
  184. static INLINE int
  185. log_severity_to_event(int severity)
  186. {
  187. switch (severity) {
  188. case LOG_DEBUG: return EVENT_DEBUG_MSG;
  189. case LOG_INFO: return EVENT_INFO_MSG;
  190. case LOG_NOTICE: return EVENT_NOTICE_MSG;
  191. case LOG_WARN: return EVENT_WARN_MSG;
  192. case LOG_ERR: return EVENT_ERR_MSG;
  193. default: return -1;
  194. }
  195. }
  196. /** Set <b>global_event_maskX</b> (where X is 0 or 1) to the bitwise OR
  197. * of each live control connection's event_mask field. */
  198. void
  199. control_update_global_event_mask(void)
  200. {
  201. connection_t **conns;
  202. int n_conns, i;
  203. global_event_mask0 = 0;
  204. global_event_mask1 = 0;
  205. get_connection_array(&conns, &n_conns);
  206. for (i = 0; i < n_conns; ++i) {
  207. if (conns[i]->type == CONN_TYPE_CONTROL &&
  208. STATE_IS_OPEN(conns[i]->state)) {
  209. if (STATE_IS_V0(conns[i]->state))
  210. global_event_mask0 |= conns[i]->event_mask;
  211. else
  212. global_event_mask1 |= conns[i]->event_mask;
  213. }
  214. }
  215. control_adjust_event_log_severity();
  216. }
  217. /** Adjust the log severities that result in control_event_logmsg being called
  218. * to match the severity of log messages that any controllers are interested
  219. * in. */
  220. void
  221. control_adjust_event_log_severity(void)
  222. {
  223. int i;
  224. int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
  225. for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
  226. if (EVENT_IS_INTERESTING(i)) {
  227. min_log_event = i;
  228. break;
  229. }
  230. }
  231. for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
  232. if (EVENT_IS_INTERESTING(i)) {
  233. max_log_event = i;
  234. break;
  235. }
  236. }
  237. if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE)) {
  238. if (min_log_event > EVENT_NOTICE_MSG)
  239. min_log_event = EVENT_NOTICE_MSG;
  240. if (max_log_event < EVENT_ERR_MSG)
  241. max_log_event = EVENT_ERR_MSG;
  242. }
  243. change_callback_log_severity(event_to_log_severity(min_log_event),
  244. event_to_log_severity(max_log_event),
  245. control_event_logmsg);
  246. }
  247. /** Append a NUL-terminated string <b>s</b> to the end of
  248. * <b>conn</b>-\>outbuf
  249. */
  250. static INLINE void
  251. connection_write_str_to_buf(const char *s, connection_t *conn)
  252. {
  253. size_t len = strlen(s);
  254. connection_write_to_buf(s, len, conn);
  255. }
  256. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  257. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  258. * the contents of <b>data</b> into *<b>out</b>, adding a period
  259. * before any period that that appears at the start of a line, and
  260. * adding a period-CRLF line at the end. If <b>translate_newlines</b>
  261. * is true, replace all LF characters sequences with CRLF. Return the
  262. * number of bytes in *<b>out</b>.
  263. */
  264. /* static */ size_t
  265. write_escaped_data(const char *data, size_t len, int translate_newlines,
  266. char **out)
  267. {
  268. size_t sz_out = len+8;
  269. char *outp;
  270. const char *end;
  271. int i;
  272. int start_of_line;
  273. for (i=0; i<(int)len; ++i) {
  274. if (data[i]== '\n')
  275. sz_out += 2; /* Maybe add a CR; maybe add a dot. */
  276. }
  277. *out = outp = tor_malloc(sz_out+1);
  278. end = data+len;
  279. start_of_line = 1;
  280. while (data < end) {
  281. if (*data == '\n') {
  282. if (translate_newlines)
  283. *outp++ = '\r';
  284. start_of_line = 1;
  285. } else if (*data == '.') {
  286. if (start_of_line) {
  287. start_of_line = 0;
  288. *outp++ = '.';
  289. }
  290. } else {
  291. start_of_line = 0;
  292. }
  293. *outp++ = *data++;
  294. }
  295. if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
  296. *outp++ = '\r';
  297. *outp++ = '\n';
  298. }
  299. *outp++ = '.';
  300. *outp++ = '\r';
  301. *outp++ = '\n';
  302. *outp = '\0'; /* NUL-terminate just in case. */
  303. tor_assert((outp - *out) <= (int)sz_out);
  304. return outp - *out;
  305. }
  306. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  307. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  308. * the contents of <b>data</b> into *<b>out</b>, removing any period
  309. * that appears at the start of a line. If <b>translate_newlines</b>
  310. * is true, replace all CRLF sequences with LF. Return the number of
  311. * bytes in *<b>out</b>. */
  312. /*static*/ size_t
  313. read_escaped_data(const char *data, size_t len, int translate_newlines,
  314. char **out)
  315. {
  316. char *outp;
  317. const char *next;
  318. const char *end;
  319. *out = outp = tor_malloc(len+1);
  320. end = data+len;
  321. while (data < end) {
  322. if (*data == '.')
  323. ++data;
  324. if (translate_newlines)
  325. next = tor_memmem(data, end-data, "\r\n", 2);
  326. else
  327. next = tor_memmem(data, end-data, "\r\n.", 3);
  328. if (next) {
  329. memcpy(outp, data, next-data);
  330. outp += (next-data);
  331. data = next+2;
  332. } else {
  333. memcpy(outp, data, end-data);
  334. outp += (end-data);
  335. *outp = '\0';
  336. return outp - *out;
  337. }
  338. if (translate_newlines) {
  339. *outp++ = '\n';
  340. } else {
  341. *outp++ = '\r';
  342. *outp++ = '\n';
  343. }
  344. }
  345. *outp = '\0';
  346. return outp - *out;
  347. }
  348. /** Given a pointer to a string starting at <b>start</b> containing
  349. * <b>in_len_max</b> characters, decode a string beginning with a single
  350. * quote, containing any number of non-quote characters or characters escaped
  351. * with a backslash, and ending with a final quote. Place the resulting
  352. * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
  353. * store its length in <b>out_len</b>. On success, return a pointer to the
  354. * character immediately following the escaped string. On failure, return
  355. * NULL. */
  356. static const char *
  357. get_escaped_string(const char *start, size_t in_len_max,
  358. char **out, size_t *out_len)
  359. {
  360. const char *cp, *end;
  361. char *outp;
  362. size_t len=0;
  363. if (*start != '\"')
  364. return NULL;
  365. cp = start+1;
  366. end = start+in_len_max;
  367. /* Calculate length. */
  368. while (1) {
  369. if (cp >= end)
  370. return NULL;
  371. else if (*cp == '\\') {
  372. if (++cp == end)
  373. return NULL; /* Can't escape EOS. */
  374. ++cp;
  375. ++len;
  376. } else if (*cp == '\"') {
  377. break;
  378. } else {
  379. ++cp;
  380. ++len;
  381. }
  382. }
  383. end = cp;
  384. outp = *out = tor_malloc(len+1);
  385. *out_len = len;
  386. cp = start+1;
  387. while (cp < end) {
  388. if (*cp == '\\')
  389. ++cp;
  390. *outp++ = *cp++;
  391. }
  392. *outp = '\0';
  393. tor_assert((outp - *out) == (int)*out_len);
  394. return end+1;
  395. }
  396. /** Acts like sprintf, but writes its formatted string to the end of
  397. * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
  398. * but it will always end with a CRLF sequence.
  399. */
  400. static void
  401. connection_printf_to_buf(connection_t *conn, const char *format, ...)
  402. {
  403. va_list ap;
  404. char buf[1024];
  405. int r;
  406. size_t len;
  407. va_start(ap,format);
  408. r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  409. va_end(ap);
  410. len = strlen(buf);
  411. if (memcmp("\r\n\0", buf+len-2, 3)) {
  412. buf[1023] = '\0';
  413. buf[1022] = '\n';
  414. buf[1021] = '\r';
  415. }
  416. connection_write_to_buf(buf, len, conn);
  417. }
  418. /** Send a message of type <b>type</b> containing <b>len</b> bytes
  419. * from <b>body</b> along the control connection <b>conn</b> */
  420. static void
  421. send_control0_message(connection_t *conn, uint16_t type, uint32_t len,
  422. const char *body)
  423. {
  424. char buf[10];
  425. tor_assert(conn);
  426. tor_assert(STATE_IS_V0(conn->state));
  427. tor_assert(len || !body);
  428. tor_assert(type <= _CONTROL0_CMD_MAX_RECOGNIZED);
  429. if (len < 65536) {
  430. set_uint16(buf, htons(len));
  431. set_uint16(buf+2, htons(type));
  432. connection_write_to_buf(buf, 4, conn);
  433. if (len)
  434. connection_write_to_buf(body, len, conn);
  435. } else {
  436. set_uint16(buf, htons(65535));
  437. set_uint16(buf+2, htons(CONTROL0_CMD_FRAGMENTHEADER));
  438. set_uint16(buf+4, htons(type));
  439. set_uint32(buf+6, htonl(len));
  440. connection_write_to_buf(buf, 10, conn);
  441. connection_write_to_buf(body, 65535-6, conn);
  442. len -= (65535-6);
  443. body += (65535-6);
  444. while (len) {
  445. size_t chunklen = (len<65535)?len:65535;
  446. set_uint16(buf, htons((uint16_t)chunklen));
  447. set_uint16(buf+2, htons(CONTROL0_CMD_FRAGMENT));
  448. connection_write_to_buf(buf, 4, conn);
  449. connection_write_to_buf(body, chunklen, conn);
  450. len -= chunklen;
  451. body += chunklen;
  452. }
  453. }
  454. }
  455. /** Send a "DONE" message down the control connection <b>conn</b> */
  456. static void
  457. send_control_done(connection_t *conn)
  458. {
  459. if (STATE_IS_V0(conn->state)) {
  460. send_control0_message(conn, CONTROL0_CMD_DONE, 0, NULL);
  461. } else {
  462. connection_write_str_to_buf("250 OK\r\n", conn);
  463. }
  464. }
  465. /** Send a "DONE" message down the v0 control message <b>conn</b>, with body
  466. * as provided in the <b>len</b> bytes at <b>msg</b>.
  467. */
  468. static void
  469. send_control_done2(connection_t *conn, const char *msg, size_t len)
  470. {
  471. if (len==0)
  472. len = strlen(msg);
  473. send_control0_message(conn, CONTROL0_CMD_DONE, len, msg);
  474. }
  475. /** Send an error message with error code <b>error</b> and body
  476. * <b>message</b> down the connection <b>conn</b> */
  477. static void
  478. send_control0_error(connection_t *conn, uint16_t error, const char *message)
  479. {
  480. char buf[256];
  481. size_t len;
  482. set_uint16(buf, htons(error));
  483. len = strlen(message);
  484. tor_assert(len < (256-2));
  485. memcpy(buf+2, message, len);
  486. send_control0_message(conn, CONTROL0_CMD_ERROR, (uint16_t)(len+2), buf);
  487. }
  488. /** Send an 'event' message of event type <b>event</b>, containing
  489. * <b>len</b> bytes in <b>body</b> to every control connection that
  490. * is interested in it. */
  491. static void
  492. send_control0_event(uint16_t event, uint32_t len, const char *body)
  493. {
  494. connection_t **conns;
  495. int n_conns, i;
  496. size_t buflen;
  497. char *buf;
  498. tor_assert(event >= _EVENT_MIN && event <= LAST_V0_EVENT);
  499. buflen = len + 2;
  500. buf = tor_malloc_zero(buflen);
  501. set_uint16(buf, htons(event));
  502. memcpy(buf+2, body, len);
  503. get_connection_array(&conns, &n_conns);
  504. for (i = 0; i < n_conns; ++i) {
  505. if (conns[i]->type == CONN_TYPE_CONTROL &&
  506. !conns[i]->marked_for_close &&
  507. conns[i]->state == CONTROL_CONN_STATE_OPEN_V0 &&
  508. conns[i]->event_mask & (1<<event)) {
  509. send_control0_message(conns[i], CONTROL0_CMD_EVENT, buflen, buf);
  510. if (event == EVENT_ERR_MSG)
  511. _connection_controller_force_write(conns[i]);
  512. }
  513. }
  514. tor_free(buf);
  515. }
  516. /* Send an event to all v1 controllers that are listening for code
  517. * <b>event</b>. The event's body is created by the printf-style format in
  518. * <b>format</b>, and other arguments as provided. */
  519. static void
  520. send_control1_event(uint16_t event, const char *format, ...)
  521. {
  522. connection_t **conns;
  523. int n_conns, i, r;
  524. char buf[1024]; /* XXXX Length */
  525. va_list ap;
  526. size_t len;
  527. va_start(ap, format);
  528. r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  529. va_end(ap);
  530. len = strlen(buf);
  531. if (memcmp("\r\n\0", buf+len-2, 3)) {
  532. buf[1023] = '\0';
  533. buf[1022] = '\n';
  534. buf[1021] = '\r';
  535. }
  536. tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);
  537. get_connection_array(&conns, &n_conns);
  538. for (i = 0; i < n_conns; ++i) {
  539. if (conns[i]->type == CONN_TYPE_CONTROL &&
  540. !conns[i]->marked_for_close &&
  541. conns[i]->state == CONTROL_CONN_STATE_OPEN_V1 &&
  542. conns[i]->event_mask & (1<<event)) {
  543. connection_write_to_buf(buf, len, conns[i]);
  544. if (event == EVENT_ERR_MSG)
  545. _connection_controller_force_write(conns[i]);
  546. }
  547. }
  548. }
  549. /** Given a text circuit <b>id</b>, return the corresponding circuit. */
  550. static circuit_t *
  551. get_circ(const char *id)
  552. {
  553. unsigned long n_id;
  554. int ok;
  555. n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
  556. if (!ok)
  557. return NULL;
  558. return circuit_get_by_global_id(n_id);
  559. }
  560. /** Given a text stream <b>id</b>, return the corresponding AP connection. */
  561. static connection_t *
  562. get_stream(const char *id)
  563. {
  564. unsigned long n_id;
  565. int ok;
  566. connection_t *conn;
  567. n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
  568. if (!ok)
  569. return NULL;
  570. conn = connection_get_by_global_id(n_id);
  571. if (!conn || conn->type != CONN_TYPE_AP)
  572. return NULL;
  573. return conn;
  574. }
  575. /** Helper for setconf and resetconf. Acts like setconf, except
  576. * it passes <b>use_defaults</b> on to options_trial_assign().
  577. */
  578. static int
  579. control_setconf_helper(connection_t *conn, uint32_t len, char *body,
  580. int use_defaults, int clear_first)
  581. {
  582. int r;
  583. config_line_t *lines=NULL;
  584. char *start = body;
  585. int v0 = STATE_IS_V0(conn->state);
  586. if (!v0) {
  587. char *config = tor_malloc(len+1);
  588. char *outp = config;
  589. while (*body) {
  590. char *eq = body;
  591. while (!TOR_ISSPACE(*eq) && *eq != '=')
  592. ++eq;
  593. memcpy(outp, body, eq-body);
  594. outp += (eq-body);
  595. *outp++ = ' ';
  596. body = eq+1;
  597. if (*eq == '=') {
  598. if (*body != '\"') {
  599. while (!TOR_ISSPACE(*body))
  600. *outp++ = *body++;
  601. } else {
  602. char *val;
  603. size_t val_len;
  604. body = (char*)get_escaped_string(body, (len - (body-start)),
  605. &val, &val_len);
  606. if (!body) {
  607. connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
  608. tor_free(config);
  609. return 0;
  610. }
  611. memcpy(outp, val, val_len);
  612. outp += val_len;
  613. tor_free(val);
  614. }
  615. }
  616. while (TOR_ISSPACE(*body))
  617. ++body;
  618. *outp++ = '\n';
  619. }
  620. *outp = '\0';
  621. if (config_get_lines(config, &lines) < 0) {
  622. log_fn(LOG_WARN,"Controller gave us config lines we can't parse.");
  623. connection_write_str_to_buf("551 Couldn't parse configuration\r\n", conn);
  624. tor_free(config);
  625. return 0;
  626. }
  627. tor_free(config);
  628. } else {
  629. if (config_get_lines(body, &lines) < 0) {
  630. log_fn(LOG_WARN,"Controller gave us config lines we can't parse.");
  631. send_control0_error(conn, ERR_SYNTAX, "Couldn't parse configuration");
  632. return 0;
  633. }
  634. }
  635. if ((r=options_trial_assign(lines, use_defaults, clear_first)) < 0) {
  636. int v0_err;
  637. const char *msg;
  638. log_fn(LOG_WARN,"Controller gave us config lines that didn't validate.");
  639. switch (r) {
  640. case -1:
  641. v0_err = ERR_UNRECOGNIZED_CONFIG_KEY;
  642. msg = "Unrecognized option";
  643. break;
  644. case -2:
  645. v0_err = ERR_INVALID_CONFIG_VALUE;
  646. msg = "Unrecognized option value";
  647. break;
  648. case -3:
  649. v0_err = ERR_INVALID_CONFIG_VALUE;
  650. msg = "Transition not allowed";
  651. break;
  652. case -4:
  653. default:
  654. v0_err = ERR_INVALID_CONFIG_VALUE;
  655. msg = "Unable to set option";
  656. break;
  657. }
  658. if (v0) {
  659. send_control0_error(conn, v0_err, msg);
  660. } else {
  661. connection_printf_to_buf(conn, "552 %s\r\n", msg);
  662. }
  663. config_free_lines(lines);
  664. return 0;
  665. }
  666. config_free_lines(lines);
  667. send_control_done(conn);
  668. return 0;
  669. }
  670. /** Called when we receive a SETCONF message: parse the body and try
  671. * to update our configuration. Reply with a DONE or ERROR message. */
  672. static int
  673. handle_control_setconf(connection_t *conn, uint32_t len, char *body)
  674. {
  675. return control_setconf_helper(conn, len, body, 0, 1);
  676. }
  677. /** Called when we receive a RESETCONF message: parse the body and try
  678. * to update our configuration. Reply with a DONE or ERROR message. */
  679. static int
  680. handle_control_resetconf(connection_t *conn, uint32_t len, char *body)
  681. {
  682. int v0 = STATE_IS_V0(conn->state);
  683. tor_assert(!v0);
  684. return control_setconf_helper(conn, len, body, 1, 1);
  685. }
  686. /** Called when we receive a GETCONF message. Parse the request, and
  687. * reply with a CONFVALUE or an ERROR message */
  688. static int
  689. handle_control_getconf(connection_t *conn, uint32_t body_len, const char *body)
  690. {
  691. smartlist_t *questions = NULL;
  692. smartlist_t *answers = NULL;
  693. smartlist_t *unrecognized = NULL;
  694. char *msg = NULL;
  695. size_t msg_len;
  696. or_options_t *options = get_options();
  697. int v0 = STATE_IS_V0(conn->state);
  698. questions = smartlist_create();
  699. if (v0) {
  700. smartlist_split_string(questions, body, "\n",
  701. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  702. } else {
  703. smartlist_split_string(questions, body, " ",
  704. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  705. }
  706. answers = smartlist_create();
  707. unrecognized = smartlist_create();
  708. SMARTLIST_FOREACH(questions, char *, q,
  709. {
  710. if (!option_is_recognized(q)) {
  711. if (v0) {
  712. send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, q);
  713. goto done;
  714. } else {
  715. smartlist_add(unrecognized, q);
  716. }
  717. } else {
  718. config_line_t *answer = option_get_assignment(options,q);
  719. if (!v0 && !answer) {
  720. const char *name = option_get_canonical_name(q);
  721. size_t alen = strlen(name)+8;
  722. char *astr = tor_malloc(alen);
  723. tor_snprintf(astr, alen, "250-%s\r\n", name);
  724. smartlist_add(answers, astr);
  725. }
  726. while (answer) {
  727. config_line_t *next;
  728. size_t alen = strlen(answer->key)+strlen(answer->value)+8;
  729. char *astr = tor_malloc(alen);
  730. if (v0)
  731. tor_snprintf(astr, alen, "%s %s\n", answer->key, answer->value);
  732. else
  733. tor_snprintf(astr, alen, "250-%s=%s\r\n", answer->key, answer->value);
  734. smartlist_add(answers, astr);
  735. next = answer->next;
  736. tor_free(answer->key);
  737. tor_free(answer->value);
  738. tor_free(answer);
  739. answer = next;
  740. }
  741. }
  742. });
  743. if (v0) {
  744. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  745. send_control0_message(conn, CONTROL0_CMD_CONFVALUE,
  746. (uint16_t)msg_len, msg_len?msg:NULL);
  747. } else {
  748. int i,len;
  749. if ((len = smartlist_len(unrecognized))) {
  750. for (i=0; i < len-1; ++i)
  751. connection_printf_to_buf(conn,
  752. "552-Unrecognized configuration key \"%s\"\r\n",
  753. (char*)smartlist_get(unrecognized, i));
  754. connection_printf_to_buf(conn,
  755. "552 Unrecognized configuration key \"%s\"\r\n",
  756. (char*)smartlist_get(unrecognized, len-1));
  757. } else if ((len = smartlist_len(answers))) {
  758. char *tmp = smartlist_get(answers, len-1);
  759. tor_assert(strlen(tmp)>4);
  760. tmp[3] = ' ';
  761. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  762. connection_write_to_buf(msg, msg_len, conn);
  763. } else {
  764. connection_write_str_to_buf("250 OK\r\n", conn);
  765. }
  766. }
  767. done:
  768. if (answers) SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  769. if (questions) SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  770. smartlist_free(answers);
  771. smartlist_free(questions);
  772. smartlist_free(unrecognized);
  773. tor_free(msg);
  774. return 0;
  775. }
  776. /** Called when we get a SETEVENTS message: update conn->event_mask,
  777. * and reply with DONE or ERROR. */
  778. static int
  779. handle_control_setevents(connection_t *conn, uint32_t len, const char *body)
  780. {
  781. uint16_t event_code;
  782. uint32_t event_mask = 0;
  783. unsigned int extended = 0;
  784. if (STATE_IS_V0(conn->state)) {
  785. if (len % 2) {
  786. send_control0_error(conn, ERR_SYNTAX,
  787. "Odd number of bytes in setevents message");
  788. return 0;
  789. }
  790. for (; len; len -= 2, body += 2) {
  791. event_code = ntohs(get_uint16(body));
  792. if (event_code < _EVENT_MIN || event_code > LAST_V0_EVENT) {
  793. send_control0_error(conn, ERR_UNRECOGNIZED_EVENT_CODE,
  794. "Unrecognized event code");
  795. return 0;
  796. }
  797. event_mask |= (1 << event_code);
  798. }
  799. } else {
  800. smartlist_t *events = smartlist_create();
  801. smartlist_split_string(events, body, " ",
  802. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  803. SMARTLIST_FOREACH(events, const char *, ev,
  804. {
  805. if (!strcasecmp(ev, "EXTENDED")) {
  806. extended = 1;
  807. continue;
  808. } else if (!strcasecmp(ev, "CIRC"))
  809. event_code = EVENT_CIRCUIT_STATUS;
  810. else if (!strcasecmp(ev, "STREAM"))
  811. event_code = EVENT_STREAM_STATUS;
  812. else if (!strcasecmp(ev, "ORCONN"))
  813. event_code = EVENT_OR_CONN_STATUS;
  814. else if (!strcasecmp(ev, "BW"))
  815. event_code = EVENT_BANDWIDTH_USED;
  816. else if (!strcasecmp(ev, "DEBUG"))
  817. event_code = EVENT_DEBUG_MSG;
  818. else if (!strcasecmp(ev, "INFO"))
  819. event_code = EVENT_INFO_MSG;
  820. else if (!strcasecmp(ev, "NOTICE"))
  821. event_code = EVENT_NOTICE_MSG;
  822. else if (!strcasecmp(ev, "WARN"))
  823. event_code = EVENT_WARN_MSG;
  824. else if (!strcasecmp(ev, "ERR"))
  825. event_code = EVENT_ERR_MSG;
  826. else if (!strcasecmp(ev, "NEWDESC"))
  827. event_code = EVENT_NEW_DESC;
  828. else if (!strcasecmp(ev, "ADDRMAP"))
  829. event_code = EVENT_ADDRMAP;
  830. else {
  831. connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
  832. ev);
  833. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  834. smartlist_free(events);
  835. return 0;
  836. }
  837. event_mask |= (1 << event_code);
  838. });
  839. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  840. smartlist_free(events);
  841. }
  842. conn->event_mask = event_mask;
  843. conn->control_events_are_extended = extended;
  844. control_update_global_event_mask();
  845. send_control_done(conn);
  846. return 0;
  847. }
  848. /** Decode the hashed, base64'd password stored in <b>hashed</b>. If
  849. * <b>buf</b> is provided, store the hashed password in the first
  850. * S2K_SPECIFIER_LEN+DIGEST_LEN bytes of <b>buf</b>. Return 0 on
  851. * success, -1 on failure.
  852. */
  853. int
  854. decode_hashed_password(char *buf, const char *hashed)
  855. {
  856. char decoded[64];
  857. if (!strcmpstart(hashed, "16:")) {
  858. if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
  859. || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
  860. return -1;
  861. }
  862. } else {
  863. if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
  864. != S2K_SPECIFIER_LEN+DIGEST_LEN) {
  865. return -1;
  866. }
  867. }
  868. if (buf)
  869. memcpy(buf, decoded, S2K_SPECIFIER_LEN+DIGEST_LEN);
  870. return 0;
  871. }
  872. /** Called when we get an AUTHENTICATE message. Check whether the
  873. * authentication is valid, and if so, update the connection's state to
  874. * OPEN. Reply with DONE or ERROR.
  875. */
  876. static int
  877. handle_control_authenticate(connection_t *conn, uint32_t len, const char *body)
  878. {
  879. or_options_t *options = get_options();
  880. char *password;
  881. size_t password_len;
  882. if (STATE_IS_V0(conn->state)) {
  883. password = (char*)body;
  884. password_len = len;
  885. } else {
  886. if (TOR_ISXDIGIT(body[0])) {
  887. int i = 0;
  888. while (TOR_ISXDIGIT(body[i]))
  889. ++i;
  890. password = tor_malloc(i/2 + 1);
  891. if (base16_decode(password, i/2+1, body, i)<0) {
  892. connection_write_str_to_buf("551 Invalid hexadecimal encoding\r\n", conn);
  893. tor_free(password);
  894. return 0;
  895. }
  896. password_len = i/2;
  897. } else if (TOR_ISSPACE(body[0])) {
  898. password = tor_strdup("");
  899. password_len = 0;
  900. } else {
  901. if (!get_escaped_string(body, len, &password, &password_len)) {
  902. connection_write_str_to_buf("551 Invalid quoted string\r\n", conn);
  903. return 0;
  904. }
  905. }
  906. }
  907. if (options->CookieAuthentication) {
  908. if (len == AUTHENTICATION_COOKIE_LEN &&
  909. !memcmp(authentication_cookie, password, password_len)) {
  910. goto ok;
  911. }
  912. } else if (options->HashedControlPassword) {
  913. char expected[S2K_SPECIFIER_LEN+DIGEST_LEN];
  914. char received[DIGEST_LEN];
  915. if (decode_hashed_password(expected, options->HashedControlPassword)<0) {
  916. log_fn(LOG_WARN,"Couldn't decode HashedControlPassword: invalid base64");
  917. goto err;
  918. }
  919. secret_to_key(received,DIGEST_LEN,password,password_len,expected);
  920. if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
  921. goto ok;
  922. goto err;
  923. } else {
  924. /* if Tor doesn't demand any stronger authentication, then
  925. * the controller can get in with anything. */
  926. goto ok;
  927. }
  928. err:
  929. if (STATE_IS_V0(conn->state))
  930. send_control0_error(conn,ERR_REJECTED_AUTHENTICATION,"Authentication failed");
  931. else {
  932. tor_free(password);
  933. connection_write_str_to_buf("515 Authentication failed\r\n", conn);
  934. }
  935. return 0;
  936. ok:
  937. log_fn(LOG_INFO, "Authenticated control connection (%d)", conn->s);
  938. send_control_done(conn);
  939. if (STATE_IS_V0(conn->state))
  940. conn->state = CONTROL_CONN_STATE_OPEN_V0;
  941. else {
  942. conn->state = CONTROL_CONN_STATE_OPEN_V1;
  943. tor_free(password);
  944. }
  945. return 0;
  946. }
  947. /** Called when we get a SAVECONF command. Try to flush the current options to
  948. * disk, and report success or failure. */
  949. static int
  950. handle_control_saveconf(connection_t *conn, uint32_t len,
  951. const char *body)
  952. {
  953. if (options_save_current()<0) {
  954. if (STATE_IS_V0(conn->state))
  955. send_control0_error(conn, ERR_INTERNAL,
  956. "Unable to write configuration to disk.");
  957. else
  958. connection_write_str_to_buf("551 Unable to write configuration to disk.",
  959. conn);
  960. } else {
  961. send_control_done(conn);
  962. }
  963. return 0;
  964. }
  965. /** Called when we get a SIGNAL command. React to the provided signal, and
  966. * report success or failure. (If the signal results in a shutdown, success
  967. * may not be reported.) */
  968. static int
  969. handle_control_signal(connection_t *conn, uint32_t len,
  970. const char *body)
  971. {
  972. int sig;
  973. if (STATE_IS_V0(conn->state)) {
  974. if (len != 1) {
  975. send_control0_error(conn, ERR_SYNTAX,
  976. "Body of SIGNAL command too long or too short.");
  977. return 0;
  978. } else {
  979. sig = (uint8_t)body[0];
  980. }
  981. } else {
  982. int n = 0;
  983. char *s;
  984. while (body[n] && ! TOR_ISSPACE(body[n]))
  985. ++n;
  986. s = tor_strndup(body, n);
  987. if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
  988. sig = SIGHUP;
  989. else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
  990. sig = SIGINT;
  991. else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
  992. sig = SIGUSR1;
  993. else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
  994. sig = SIGUSR2;
  995. else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
  996. sig = SIGTERM;
  997. else {
  998. connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
  999. body);
  1000. sig = -1;
  1001. }
  1002. tor_free(s);
  1003. if (sig<0)
  1004. return 0;
  1005. }
  1006. if (control_signal_act(sig) < 0) {
  1007. if (STATE_IS_V0(conn->state))
  1008. send_control0_error(conn, ERR_SYNTAX, "Unrecognized signal number.");
  1009. else
  1010. connection_write_str_to_buf("551 Internal error acting on signal\r\n",
  1011. conn);
  1012. } else {
  1013. send_control_done(conn);
  1014. }
  1015. return 0;
  1016. }
  1017. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  1018. * and report success or failrue. */
  1019. static int
  1020. handle_control_mapaddress(connection_t *conn, uint32_t len, const char *body)
  1021. {
  1022. smartlist_t *elts;
  1023. smartlist_t *lines;
  1024. smartlist_t *reply;
  1025. char *r;
  1026. size_t sz;
  1027. int v0 = STATE_IS_V0(conn->state);
  1028. lines = smartlist_create();
  1029. elts = smartlist_create();
  1030. reply = smartlist_create();
  1031. if (v0)
  1032. smartlist_split_string(lines, body, "\n",
  1033. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1034. else
  1035. smartlist_split_string(lines, body, " ",
  1036. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1037. /* XXXX Make errors conformant. */
  1038. SMARTLIST_FOREACH(lines, char *, line,
  1039. {
  1040. tor_strlower(line);
  1041. if (v0)
  1042. smartlist_split_string(elts, line, " ", 0, 2);
  1043. else
  1044. smartlist_split_string(elts, line, "=", 0, 2);
  1045. if (smartlist_len(elts) == 2) {
  1046. const char *from = smartlist_get(elts,0);
  1047. const char *to = smartlist_get(elts,1);
  1048. if (!is_plausible_address(from)) {
  1049. log_fn(LOG_WARN,"Skipping invalid argument '%s' in MapAddress msg",from);
  1050. } else if (!is_plausible_address(to)) {
  1051. log_fn(LOG_WARN,"Skipping invalid argument '%s' in MapAddress msg",to);
  1052. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
  1053. const char *address = addressmap_register_virtual_address(
  1054. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
  1055. tor_strdup(to));
  1056. if (!address) {
  1057. log_fn(LOG_WARN,
  1058. "Unable to allocate address for '%s' in MapAddress msg",
  1059. safe_str(line));
  1060. } else {
  1061. size_t anslen = strlen(address)+strlen(to)+8;
  1062. char *ans = tor_malloc(anslen);
  1063. if (v0)
  1064. tor_snprintf(ans, anslen, "%s %s", address, to);
  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. if (v0)
  1072. smartlist_add(reply, tor_strdup(line));
  1073. else {
  1074. size_t anslen = strlen(line)+8;
  1075. char *ans = tor_malloc(anslen);
  1076. tor_snprintf(ans, anslen, "250-%s", line);
  1077. smartlist_add(reply, ans);
  1078. }
  1079. }
  1080. } else {
  1081. log_fn(LOG_WARN, "Skipping MapAddress line with wrong number of items.");
  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 (v0) {
  1090. r = smartlist_join_strings(reply, "\n", 1, &sz);
  1091. send_control_done2(conn,r,sz);
  1092. } else {
  1093. if (smartlist_len(reply))
  1094. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1095. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1096. connection_write_to_buf(r, sz, conn);
  1097. }
  1098. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1099. smartlist_free(reply);
  1100. tor_free(r);
  1101. return 0;
  1102. }
  1103. /** Return a newly allocated string listing all valid GETINFO fields as
  1104. * required by GETINFO info/names. */
  1105. static char *
  1106. list_getinfo_options(void)
  1107. {
  1108. return tor_strdup(
  1109. "accounting/bytes Number of bytes read/written so far in interval.\n"
  1110. "accounting/bytes-left Number of bytes left to read/write in interval.\n"
  1111. "accounting/enabled Is accounting currently enabled?\n"
  1112. "accounting/hibernating Are we hibernating or awake?\n"
  1113. "accounting/interval-end Time when interval ends.\n"
  1114. "accounting/interval-start Time when interval starts.\n"
  1115. "accounting/interval-wake Time to wake up in this interval.\n"
  1116. "addr-mappings/all All current remapped addresses.\n"
  1117. "addr-mappings/cache Addresses remapped by DNS cache.\n"
  1118. "addr-mappings/configl Addresses remapped from configuration options.\n"
  1119. "addr-mappings/control Addresses remapped by a controller.\n"
  1120. "circuit-status Status of each current circuit.\n"
  1121. "config/names List of configuration options, types, and documentation.\n"
  1122. "desc/id/* Server descriptor by hex ID\n"
  1123. "desc/name/* Server descriptor by nickname.\n"
  1124. "helper-nodes Which nodes will we use as helpers?\n"
  1125. "info/names List of GETINFO options, types, and documentation.\n"
  1126. "network-status List of hex IDs, nicknames, server statuses.\n"
  1127. "orconn-status Status of each current OR connection.\n"
  1128. "stream-status Status of each current application stream.\n"
  1129. "version The current version of Tor.\n");
  1130. }
  1131. /** Lookup the 'getinfo' entry <b>question</b>, and return
  1132. * the answer in <b>*answer</b> (or NULL if key not recognized).
  1133. * Return 0 if success, or -1 if internal error. */
  1134. static int
  1135. handle_getinfo_helper(const char *question, char **answer)
  1136. {
  1137. *answer = NULL; /* unrecognized key by default */
  1138. if (!strcmp(question, "version")) {
  1139. *answer = tor_strdup(VERSION);
  1140. } else if (!strcmp(question, "config-file")) {
  1141. *answer = tor_strdup(get_torrc_fname());
  1142. } else if (!strcmpstart(question, "accounting/")) {
  1143. return accounting_getinfo_helper(question, answer);
  1144. } else if (!strcmpstart(question, "helper-nodes")) {
  1145. return helper_nodes_getinfo_helper(question, answer);
  1146. } else if (!strcmpstart(question, "config/")) {
  1147. return config_getinfo_helper(question, answer);
  1148. } else if (!strcmp(question, "info/names")) {
  1149. *answer = list_getinfo_options();
  1150. } else if (!strcmpstart(question, "desc/id/")) {
  1151. routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
  1152. if (ri && ri->signed_descriptor)
  1153. *answer = tor_strdup(ri->signed_descriptor);
  1154. } else if (!strcmpstart(question, "desc/name/")) {
  1155. routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
  1156. if (ri && ri->signed_descriptor)
  1157. *answer = tor_strdup(ri->signed_descriptor);
  1158. } else if (!strcmpstart(question, "unregistered-servers-")) {
  1159. *answer = dirserver_getinfo_unregistered(question +
  1160. strlen("unregistered-servers-"));
  1161. } else if (!strcmp(question, "network-status")) {
  1162. routerlist_t *routerlist;
  1163. router_get_routerlist(&routerlist);
  1164. if (!routerlist || !routerlist->routers ||
  1165. list_server_status(routerlist->routers, answer) < 0) {
  1166. return -1;
  1167. }
  1168. } else if (!strcmp(question, "circuit-status")) {
  1169. circuit_t *circ;
  1170. smartlist_t *status = smartlist_create();
  1171. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  1172. char *s, *path;
  1173. size_t slen;
  1174. const char *state;
  1175. if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
  1176. continue;
  1177. path = circuit_list_path(circ,0);
  1178. if (circ->state == CIRCUIT_STATE_OPEN)
  1179. state = "BUILT";
  1180. else if (strlen(path))
  1181. state = "EXTENDED";
  1182. else
  1183. state = "LAUNCHED";
  1184. slen = strlen(path)+strlen(state)+20;
  1185. s = tor_malloc(slen+1);
  1186. tor_snprintf(s, slen, "%lu %s %s", (unsigned long)circ->global_identifier,
  1187. state, path);
  1188. smartlist_add(status, s);
  1189. tor_free(path);
  1190. }
  1191. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1192. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1193. smartlist_free(status);
  1194. } else if (!strcmp(question, "stream-status")) {
  1195. connection_t **conns;
  1196. int n_conns, i;
  1197. char buf[256];
  1198. smartlist_t *status = smartlist_create();
  1199. get_connection_array(&conns, &n_conns);
  1200. for (i=0; i < n_conns; ++i) {
  1201. const char *state;
  1202. char *s;
  1203. size_t slen;
  1204. circuit_t *circ;
  1205. if (conns[i]->type != CONN_TYPE_AP ||
  1206. conns[i]->marked_for_close ||
  1207. conns[i]->state == AP_CONN_STATE_SOCKS_WAIT)
  1208. continue;
  1209. switch (conns[i]->state)
  1210. {
  1211. case AP_CONN_STATE_CONTROLLER_WAIT:
  1212. case AP_CONN_STATE_CIRCUIT_WAIT:
  1213. if (conns[i]->socks_request &&
  1214. conns[i]->socks_request->command == SOCKS_COMMAND_RESOLVE)
  1215. state = "NEWRESOLVE";
  1216. else
  1217. state = "NEW";
  1218. break;
  1219. case AP_CONN_STATE_RENDDESC_WAIT:
  1220. case AP_CONN_STATE_CONNECT_WAIT:
  1221. state = "SENTCONNECT"; break;
  1222. case AP_CONN_STATE_RESOLVE_WAIT:
  1223. state = "SENTRESOLVE"; break;
  1224. case AP_CONN_STATE_OPEN:
  1225. state = "SUCCEEDED"; break;
  1226. default:
  1227. log_fn(LOG_WARN, "Asked for stream in unknown state %d",
  1228. conns[i]->state);
  1229. continue;
  1230. }
  1231. circ = circuit_get_by_edge_conn(conns[i]);
  1232. write_stream_target_to_buf(conns[i], buf, sizeof(buf));
  1233. slen = strlen(buf)+strlen(state)+32;
  1234. s = tor_malloc(slen+1);
  1235. tor_snprintf(s, slen, "%lu %s %lu %s",
  1236. (unsigned long) conns[i]->global_identifier,state,
  1237. circ?(unsigned long)circ->global_identifier : 0ul,
  1238. buf);
  1239. smartlist_add(status, s);
  1240. }
  1241. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1242. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1243. smartlist_free(status);
  1244. } else if (!strcmp(question, "orconn-status")) {
  1245. connection_t **conns;
  1246. int n_conns, i;
  1247. smartlist_t *status = smartlist_create();
  1248. get_connection_array(&conns, &n_conns);
  1249. for (i=0; i < n_conns; ++i) {
  1250. const char *state;
  1251. char *s;
  1252. size_t slen;
  1253. if (conns[i]->type != CONN_TYPE_OR || conns[i]->marked_for_close)
  1254. continue;
  1255. if (conns[i]->state == OR_CONN_STATE_OPEN)
  1256. state = "CONNECTED";
  1257. else
  1258. state = "LAUNCHED";
  1259. slen = strlen(conns[i]->nickname)+strlen(state)+2;
  1260. s = tor_malloc(slen+1);
  1261. tor_snprintf(s, slen, "%s %s",conns[i]->nickname,state);
  1262. smartlist_add(status, s);
  1263. }
  1264. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1265. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1266. smartlist_free(status);
  1267. } else if (!strcmpstart(question, "addr-mappings/")) {
  1268. time_t min_e, max_e;
  1269. smartlist_t *mappings;
  1270. if (!strcmp(question, "addr-mappings/all")) {
  1271. min_e = 0; max_e = TIME_MAX;
  1272. } else if (!strcmp(question, "addr-mappings/cache")) {
  1273. min_e = 2; max_e = TIME_MAX;
  1274. } else if (!strcmp(question, "addr-mappings/config")) {
  1275. min_e = 0; max_e = 0;
  1276. } else if (!strcmp(question, "addr-mappings/control")) {
  1277. min_e = 1; max_e = 1;
  1278. } else {
  1279. return 0;
  1280. }
  1281. mappings = smartlist_create();
  1282. addressmap_get_mappings(mappings, min_e, max_e);
  1283. *answer = smartlist_join_strings(mappings, "\n", 0, NULL);
  1284. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  1285. smartlist_free(mappings);
  1286. }
  1287. return 0;
  1288. }
  1289. /** Called when we receive a GETINFO command. Try to fetch all requested
  1290. * information, and reply with information or error message. */
  1291. static int
  1292. handle_control_getinfo(connection_t *conn, uint32_t len, const char *body)
  1293. {
  1294. smartlist_t *questions = NULL;
  1295. smartlist_t *answers = NULL;
  1296. smartlist_t *unrecognized = NULL;
  1297. char *msg = NULL, *ans = NULL;
  1298. size_t msg_len;
  1299. int v0 = STATE_IS_V0(conn->state);
  1300. questions = smartlist_create();
  1301. if (v0)
  1302. smartlist_split_string(questions, body, "\n",
  1303. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1304. else
  1305. smartlist_split_string(questions, body, " ",
  1306. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1307. answers = smartlist_create();
  1308. unrecognized = smartlist_create();
  1309. SMARTLIST_FOREACH(questions, const char *, q,
  1310. {
  1311. if (handle_getinfo_helper(q, &ans) < 0) {
  1312. if (v0)
  1313. send_control0_error(conn, ERR_INTERNAL, body);
  1314. else
  1315. connection_write_str_to_buf("551 Internal error\r\n", conn);
  1316. goto done;
  1317. }
  1318. if (!ans) {
  1319. if (v0) {
  1320. send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
  1321. goto done;
  1322. } else
  1323. smartlist_add(unrecognized, (char*)q);
  1324. } else {
  1325. smartlist_add(answers, tor_strdup(q));
  1326. smartlist_add(answers, ans);
  1327. }
  1328. });
  1329. if (smartlist_len(unrecognized)) {
  1330. int i;
  1331. tor_assert(!v0);
  1332. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  1333. connection_printf_to_buf(conn,
  1334. "552-Unrecognized key \"%s\"\r\n",
  1335. (char*)smartlist_get(unrecognized, i));
  1336. connection_printf_to_buf(conn,
  1337. "552 Unrecognized key \"%s\"\r\n",
  1338. (char*)smartlist_get(unrecognized, i));
  1339. goto done;
  1340. }
  1341. if (v0) {
  1342. msg = smartlist_join_strings2(answers, "\0", 1, 1, &msg_len);
  1343. tor_assert(msg_len > 0); /* it will at least be terminated */
  1344. send_control0_message(conn, CONTROL0_CMD_INFOVALUE,
  1345. msg_len, msg);
  1346. } else if (smartlist_len(answers)) {
  1347. int i;
  1348. for (i = 0; i < smartlist_len(answers); i += 2) {
  1349. char *k = smartlist_get(answers, i);
  1350. char *v = smartlist_get(answers, i+1);
  1351. /*XXXX Not an adequate test! XXXX011 */
  1352. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  1353. connection_printf_to_buf(conn, "250-%s=", k);
  1354. connection_write_str_to_buf(v, conn);
  1355. connection_write_str_to_buf("\r\n", conn);
  1356. } else {
  1357. char *esc = NULL;
  1358. size_t len;
  1359. len = write_escaped_data(v, strlen(v), 1, &esc);
  1360. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  1361. connection_write_to_buf(esc, len, conn);
  1362. tor_free(esc);
  1363. }
  1364. }
  1365. connection_write_str_to_buf("250 OK\r\n", conn);
  1366. }
  1367. done:
  1368. if (answers) SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  1369. if (questions) SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  1370. smartlist_free(answers);
  1371. smartlist_free(questions);
  1372. smartlist_free(unrecognized);
  1373. tor_free(msg);
  1374. return 0;
  1375. }
  1376. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  1377. * circuit, and report success or failure. */
  1378. static int
  1379. handle_control_extendcircuit(connection_t *conn, uint32_t len,
  1380. const char *body)
  1381. {
  1382. smartlist_t *router_nicknames=NULL, *routers=NULL;
  1383. uint32_t circ_id;
  1384. circuit_t *circ = NULL;
  1385. int zero_circ, v0;
  1386. char reply[4];
  1387. v0 = STATE_IS_V0(conn->state);
  1388. router_nicknames = smartlist_create();
  1389. if (v0) {
  1390. if (len<5) {
  1391. send_control0_error(conn, ERR_SYNTAX, "extendcircuit message too short");
  1392. goto done;
  1393. }
  1394. smartlist_split_string(router_nicknames, body+4, ",", 0, 0);
  1395. circ_id = ntohl(get_uint32(body));
  1396. if (!circ_id) {
  1397. /* start a new circuit */
  1398. zero_circ = 1;
  1399. } else {
  1400. circ = circuit_get_by_global_id(circ_id);
  1401. zero_circ = 0;
  1402. if (!circ) {
  1403. send_control0_error(conn, ERR_NO_CIRC,
  1404. "No circuit found with given ID");
  1405. goto done;
  1406. }
  1407. }
  1408. } else { /* v1 */
  1409. smartlist_t *args;
  1410. args = smartlist_create();
  1411. smartlist_split_string(args, body, " ",
  1412. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1413. if (smartlist_len(args)<2)
  1414. connection_printf_to_buf(conn,"512 Missing argument to EXTENDCIRCUIT\r\n");
  1415. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  1416. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  1417. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1418. (char*)smartlist_get(args, 0));
  1419. }
  1420. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  1421. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1422. smartlist_free(args);
  1423. if (!zero_circ && !circ) {
  1424. goto done;
  1425. }
  1426. }
  1427. routers = smartlist_create();
  1428. SMARTLIST_FOREACH(router_nicknames, const char *, n,
  1429. {
  1430. routerinfo_t *r = router_get_by_nickname(n, 1);
  1431. if (!r) {
  1432. if (v0)
  1433. send_control0_error(conn, ERR_NO_ROUTER, n);
  1434. else
  1435. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  1436. goto done;
  1437. }
  1438. smartlist_add(routers, r);
  1439. });
  1440. if (!smartlist_len(routers)) {
  1441. if (v0)
  1442. send_control0_error(conn, ERR_SYNTAX, "No router names provided");
  1443. else
  1444. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  1445. goto done;
  1446. }
  1447. if (zero_circ) {
  1448. /* start a new circuit */
  1449. circ = circuit_init(CIRCUIT_PURPOSE_C_GENERAL, 0, 0, 0);
  1450. }
  1451. /* now circ refers to something that is ready to be extended */
  1452. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  1453. {
  1454. extend_info_t *info = extend_info_from_router(r);
  1455. circuit_append_new_exit(circ, info);
  1456. extend_info_free(info);
  1457. });
  1458. /* now that we've populated the cpath, start extending */
  1459. if (zero_circ) {
  1460. if (circuit_handle_first_hop(circ) < 0) {
  1461. circuit_mark_for_close(circ);
  1462. if (v0)
  1463. send_control0_error(conn, ERR_INTERNAL, "couldn't start circuit");
  1464. else
  1465. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  1466. goto done;
  1467. }
  1468. } else {
  1469. if (circ->state == CIRCUIT_STATE_OPEN) {
  1470. circ->state = CIRCUIT_STATE_BUILDING;
  1471. if (circuit_send_next_onion_skin(circ) < 0) {
  1472. log_fn(LOG_INFO,"send_next_onion_skin failed; circuit marked for closing.");
  1473. circuit_mark_for_close(circ);
  1474. if (v0)
  1475. send_control0_error(conn, ERR_INTERNAL, "couldn't send onion skin");
  1476. else
  1477. connection_write_str_to_buf("551 Couldn't send onion skinr\n", conn);
  1478. goto done;
  1479. }
  1480. }
  1481. }
  1482. if (v0) {
  1483. set_uint32(reply, htonl(circ->global_identifier));
  1484. send_control_done2(conn, reply, sizeof(reply));
  1485. } else {
  1486. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  1487. (unsigned long)circ->global_identifier);
  1488. }
  1489. done:
  1490. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  1491. smartlist_free(router_nicknames);
  1492. if (routers)
  1493. smartlist_free(routers);
  1494. return 0;
  1495. }
  1496. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  1497. * stream, and report success or failure. */
  1498. static int
  1499. handle_control_attachstream(connection_t *conn, uint32_t len,
  1500. const char *body)
  1501. {
  1502. connection_t *ap_conn = NULL;
  1503. circuit_t *circ = NULL;
  1504. int zero_circ;
  1505. if (STATE_IS_V0(conn->state)) {
  1506. uint32_t conn_id;
  1507. uint32_t circ_id;
  1508. if (len < 8) {
  1509. send_control0_error(conn, ERR_SYNTAX, "attachstream message too short");
  1510. return 0;
  1511. }
  1512. conn_id = ntohl(get_uint32(body));
  1513. circ_id = ntohl(get_uint32(body+4));
  1514. zero_circ = circ_id == 0;
  1515. if (!(ap_conn = connection_get_by_global_id(conn_id))) {
  1516. send_control0_error(conn, ERR_NO_STREAM,
  1517. "No connection found with given ID");
  1518. return 0;
  1519. }
  1520. if (circ_id && !(circ = circuit_get_by_global_id(circ_id))) {
  1521. send_control0_error(conn, ERR_NO_CIRC, "No circuit found with given ID");
  1522. return 0;
  1523. }
  1524. } else {
  1525. smartlist_t *args;
  1526. args = smartlist_create();
  1527. smartlist_split_string(args, body, " ",
  1528. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1529. if (smartlist_len(args)<2)
  1530. connection_printf_to_buf(conn,"512 Missing argument to ATTACHSTREAM\r\n");
  1531. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  1532. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  1533. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1534. (char*)smartlist_get(args, 0));
  1535. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  1536. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1537. (char*)smartlist_get(args, 1));
  1538. }
  1539. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1540. smartlist_free(args);
  1541. if (!ap_conn || (!zero_circ && !circ))
  1542. return 0;
  1543. }
  1544. if (ap_conn->state != AP_CONN_STATE_CONTROLLER_WAIT) {
  1545. if (STATE_IS_V0(conn->state)) {
  1546. send_control0_error(conn, ERR_NO_STREAM,
  1547. "Connection is not managed by controller.");
  1548. } else {
  1549. connection_write_str_to_buf(
  1550. "555 Connection is not managed by controller.\r\n",
  1551. conn);
  1552. }
  1553. return 0;
  1554. }
  1555. if (zero_circ) {
  1556. ap_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1557. if (connection_ap_handshake_attach_circuit(ap_conn)<0)
  1558. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_CANT_ATTACH);
  1559. send_control_done(conn);
  1560. return 0;
  1561. }
  1562. if (circ->state != CIRCUIT_STATE_OPEN) {
  1563. if (STATE_IS_V0(conn->state))
  1564. send_control0_error(conn, ERR_INTERNAL, "Refuse to attach stream to non-open circ.");
  1565. else
  1566. connection_write_str_to_buf(
  1567. "551 Can't attach stream to non-open circuit\r\n",
  1568. conn);
  1569. return 0;
  1570. }
  1571. if (connection_ap_handshake_attach_chosen_circuit(ap_conn, circ) != 1) {
  1572. if (STATE_IS_V0(conn->state))
  1573. send_control0_error(conn, ERR_INTERNAL, "Unable to attach stream.");
  1574. else
  1575. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  1576. return 0;
  1577. }
  1578. send_control_done(conn);
  1579. return 0;
  1580. }
  1581. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  1582. * descriptor, and report success or failure. */
  1583. static int
  1584. handle_control_postdescriptor(connection_t *conn, uint32_t len,
  1585. const char *body)
  1586. {
  1587. char *desc;
  1588. int v0 = STATE_IS_V0(conn->state);
  1589. const char *msg=NULL;
  1590. if (v0)
  1591. desc = (char*)body;
  1592. else {
  1593. const char *cp = memchr(body, '\n', len);
  1594. tor_assert(cp);
  1595. read_escaped_data(cp, len-(cp-body), 1, &desc);
  1596. }
  1597. switch (router_load_single_router(desc, &msg)) {
  1598. case -1:
  1599. if (!msg) msg = "Could not parse descriptor";
  1600. if (v0)
  1601. send_control0_error(conn,ERR_SYNTAX,msg);
  1602. else
  1603. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  1604. break;
  1605. case 0:
  1606. if (!msg) msg = "Descriptor not added";
  1607. if (v0)
  1608. send_control_done2(conn,msg,0);
  1609. else
  1610. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  1611. break;
  1612. case 1:
  1613. send_control_done(conn);
  1614. break;
  1615. }
  1616. if (!v0)
  1617. tor_free(desc);
  1618. return 0;
  1619. }
  1620. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  1621. * adderess of the named AP steream, and report success or failure. */
  1622. static int
  1623. handle_control_redirectstream(connection_t *conn, uint32_t len,
  1624. const char *body)
  1625. {
  1626. connection_t *ap_conn = NULL;
  1627. uint32_t conn_id;
  1628. char *new_addr = NULL;
  1629. if (STATE_IS_V0(conn->state)) {
  1630. if (len < 6) {
  1631. send_control0_error(conn, ERR_SYNTAX, "redirectstream message too short");
  1632. return 0;
  1633. }
  1634. conn_id = ntohl(get_uint32(body));
  1635. if (!(ap_conn = connection_get_by_global_id(conn_id))
  1636. || ap_conn->state != CONN_TYPE_AP
  1637. || !ap_conn->socks_request) {
  1638. send_control0_error(conn, ERR_NO_STREAM,
  1639. "No AP connection found with given ID");
  1640. return 0;
  1641. }
  1642. new_addr = tor_strdup(body+4);
  1643. } else {
  1644. smartlist_t *args;
  1645. args = smartlist_create();
  1646. smartlist_split_string(args, body, " ",
  1647. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1648. if (smartlist_len(args)<2)
  1649. connection_printf_to_buf(conn,"512 Missing argument to REDIRECTSTREAM\r\n");
  1650. else if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  1651. || !ap_conn->socks_request) {
  1652. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1653. (char*)smartlist_get(args, 0));
  1654. } else {
  1655. new_addr = tor_strdup(smartlist_get(args, 1));
  1656. }
  1657. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1658. smartlist_free(args);
  1659. if (!new_addr)
  1660. return 0;
  1661. }
  1662. strlcpy(ap_conn->socks_request->address, new_addr,
  1663. sizeof(ap_conn->socks_request->address));
  1664. tor_free(new_addr);
  1665. send_control_done(conn);
  1666. return 0;
  1667. }
  1668. /** Called when we get a CLOSESTREAM command; try to close the named stream
  1669. * and report success or failure. */
  1670. static int
  1671. handle_control_closestream(connection_t *conn, uint32_t len,
  1672. const char *body)
  1673. {
  1674. connection_t *ap_conn=NULL;
  1675. uint8_t reason=0;
  1676. if (STATE_IS_V0(conn->state)) {
  1677. uint32_t conn_id;
  1678. if (len < 6) {
  1679. send_control0_error(conn, ERR_SYNTAX, "closestream message too short");
  1680. return 0;
  1681. }
  1682. conn_id = ntohl(get_uint32(body));
  1683. reason = *(uint8_t*)(body+4);
  1684. if (!(ap_conn = connection_get_by_global_id(conn_id))
  1685. || ap_conn->state != CONN_TYPE_AP
  1686. || !ap_conn->socks_request) {
  1687. send_control0_error(conn, ERR_NO_STREAM,
  1688. "No AP connection found with given ID");
  1689. return 0;
  1690. }
  1691. } else {
  1692. smartlist_t *args;
  1693. int ok;
  1694. args = smartlist_create();
  1695. smartlist_split_string(args, body, " ",
  1696. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1697. if (smartlist_len(args)<2)
  1698. connection_printf_to_buf(conn, "512 Missing argument to CLOSESTREAM\r\n");
  1699. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  1700. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1701. (char*)smartlist_get(args, 0));
  1702. else {
  1703. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  1704. &ok, NULL);
  1705. if (!ok) {
  1706. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  1707. (char*)smartlist_get(args, 1));
  1708. ap_conn = NULL;
  1709. }
  1710. }
  1711. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1712. smartlist_free(args);
  1713. if (!ap_conn)
  1714. return 0;
  1715. }
  1716. connection_mark_unattached_ap(ap_conn, reason);
  1717. send_control_done(conn);
  1718. return 0;
  1719. }
  1720. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  1721. * and report success or failure. */
  1722. static int
  1723. handle_control_closecircuit(connection_t *conn, uint32_t len,
  1724. const char *body)
  1725. {
  1726. circuit_t *circ = NULL;
  1727. int safe = 0;
  1728. if (STATE_IS_V0(conn->state)) {
  1729. uint32_t circ_id;
  1730. if (len < 5) {
  1731. send_control0_error(conn, ERR_SYNTAX, "closecircuit message too short");
  1732. return 0;
  1733. }
  1734. circ_id = ntohl(get_uint32(body));
  1735. safe = (*(uint8_t*)(body+4)) & 1;
  1736. if (!(circ = circuit_get_by_global_id(circ_id))) {
  1737. send_control0_error(conn, ERR_NO_CIRC,
  1738. "No circuit found with given ID");
  1739. return 0;
  1740. }
  1741. } else {
  1742. smartlist_t *args;
  1743. args = smartlist_create();
  1744. smartlist_split_string(args, body, " ",
  1745. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1746. if (smartlist_len(args)<1)
  1747. connection_printf_to_buf(conn, "512 Missing argument to CLOSECIRCUIT\r\n");
  1748. else if (!(circ=get_circ(smartlist_get(args, 0))))
  1749. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1750. (char*)smartlist_get(args, 0));
  1751. else {
  1752. int i;
  1753. for (i=1; i < smartlist_len(args); ++i) {
  1754. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  1755. safe = 1;
  1756. else
  1757. log_fn(LOG_INFO, "Skipping unknown option %s",
  1758. (char*)smartlist_get(args,i));
  1759. }
  1760. }
  1761. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1762. smartlist_free(args);
  1763. if (!circ)
  1764. return 0;
  1765. }
  1766. if (!safe || !circ->p_streams) {
  1767. circuit_mark_for_close(circ);
  1768. }
  1769. send_control_done(conn);
  1770. return 0;
  1771. }
  1772. /** Called when we get a v0 FRAGMENTHEADER or FRAGMENT command; try to append
  1773. * the data to conn->incoming_cmd, setting conn->incoming_(type|len|cur_len)
  1774. * as appropriate. If the command is malformed, drop it and all pending
  1775. * fragments and report failure.
  1776. */
  1777. static int
  1778. handle_control_fragments(connection_t *conn, uint16_t command_type,
  1779. uint32_t body_len, char *body)
  1780. {
  1781. if (command_type == CONTROL0_CMD_FRAGMENTHEADER) {
  1782. if (conn->incoming_cmd) {
  1783. log_fn(LOG_WARN, "Dropping incomplete fragmented command");
  1784. tor_free(conn->incoming_cmd);
  1785. }
  1786. if (body_len < 6) {
  1787. send_control0_error(conn, ERR_SYNTAX, "FRAGMENTHEADER too short.");
  1788. return 0;
  1789. }
  1790. conn->incoming_cmd_type = ntohs(get_uint16(body));
  1791. conn->incoming_cmd_len = ntohl(get_uint32(body+2));
  1792. conn->incoming_cmd_cur_len = 0;
  1793. conn->incoming_cmd = tor_malloc(conn->incoming_cmd_len);
  1794. body += 6;
  1795. body_len -= 6;
  1796. } else if (command_type == CONTROL0_CMD_FRAGMENT) {
  1797. if (!conn->incoming_cmd) {
  1798. send_control0_error(conn, ERR_SYNTAX, "Out-of-place FRAGMENT");
  1799. return 0;
  1800. }
  1801. } else {
  1802. tor_assert(0);
  1803. }
  1804. if (conn->incoming_cmd_cur_len + body_len > conn->incoming_cmd_len) {
  1805. tor_free(conn->incoming_cmd);
  1806. send_control0_error(conn, ERR_SYNTAX,
  1807. "Fragmented data exceeds declared length");
  1808. return 0;
  1809. }
  1810. memcpy(conn->incoming_cmd + conn->incoming_cmd_cur_len,
  1811. body, body_len);
  1812. conn->incoming_cmd_cur_len += body_len;
  1813. return 0;
  1814. }
  1815. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  1816. int
  1817. connection_control_finished_flushing(connection_t *conn)
  1818. {
  1819. tor_assert(conn);
  1820. tor_assert(conn->type == CONN_TYPE_CONTROL);
  1821. connection_stop_writing(conn);
  1822. return 0;
  1823. }
  1824. /** Called when <b>conn</b> has gotten its socket closed. */
  1825. int
  1826. connection_control_reached_eof(connection_t *conn)
  1827. {
  1828. tor_assert(conn);
  1829. tor_assert(conn->type == CONN_TYPE_CONTROL);
  1830. log_fn(LOG_INFO,"Control connection reached EOF. Closing.");
  1831. connection_mark_for_close(conn);
  1832. return 0;
  1833. }
  1834. /** Called when data has arrived on a v1 control connection: Try to fetch
  1835. * commands from conn->inbuf, and execute them.
  1836. */
  1837. static int
  1838. connection_control_process_inbuf_v1(connection_t *conn)
  1839. {
  1840. size_t data_len;
  1841. int cmd_len;
  1842. char *args;
  1843. tor_assert(conn);
  1844. tor_assert(conn->type == CONN_TYPE_CONTROL);
  1845. tor_assert(conn->state == CONTROL_CONN_STATE_OPEN_V1 ||
  1846. conn->state == CONTROL_CONN_STATE_NEEDAUTH_V1);
  1847. if (!conn->incoming_cmd) {
  1848. conn->incoming_cmd = tor_malloc(1024);
  1849. conn->incoming_cmd_len = 1024;
  1850. conn->incoming_cmd_cur_len = 0;
  1851. }
  1852. again:
  1853. while (1) {
  1854. size_t last_idx;
  1855. int r;
  1856. /* First, fetch a line. */
  1857. do {
  1858. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  1859. r = fetch_from_buf_line(conn->inbuf,
  1860. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  1861. &data_len);
  1862. if (r == 0)
  1863. /* Line not all here yet. Wait. */
  1864. return 0;
  1865. else if (r == -1) {
  1866. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  1867. conn->incoming_cmd_len *= 2;
  1868. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  1869. conn->incoming_cmd_len);
  1870. }
  1871. } while (r != 1);
  1872. tor_assert(data_len);
  1873. last_idx = conn->incoming_cmd_cur_len;
  1874. conn->incoming_cmd_cur_len += data_len;
  1875. /* We have appended a line to incoming_cmd. Is the command done? */
  1876. if (last_idx == 0 && *conn->incoming_cmd != '+')
  1877. /* One line command, didn't start with '+'. */
  1878. break;
  1879. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  1880. !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  1881. /* Just appended ".\r\n"; we're done. Remove it. */
  1882. conn->incoming_cmd_cur_len -= 3;
  1883. break;
  1884. }
  1885. /* Otherwise, read another line. */
  1886. }
  1887. data_len = conn->incoming_cmd_cur_len;
  1888. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  1889. * recognize it.
  1890. */
  1891. cmd_len = 0;
  1892. while ((size_t)cmd_len < data_len
  1893. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  1894. ++cmd_len;
  1895. /*
  1896. log_fn(LOG_NOTICE, "READ A COMMAND FROM THE BUFFER: <%s> [%d]",
  1897. conn->incoming_cmd, (int)cmd_len);
  1898. */
  1899. data_len -= cmd_len;
  1900. conn->incoming_cmd[cmd_len]='\0';
  1901. args = conn->incoming_cmd+cmd_len+1;
  1902. while (*args == ' ' || *args == '\t') {
  1903. ++args;
  1904. --data_len;
  1905. }
  1906. /*
  1907. log_fn(LOG_NOTICE, "COMMAND IS: <%s>", conn->incoming_cmd);
  1908. log_fn(LOG_NOTICE, "ARGS ARE: <%s>", args);
  1909. */
  1910. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  1911. connection_write_str_to_buf("250 closing connection\r\n", conn);
  1912. connection_mark_for_close(conn);
  1913. return 0;
  1914. }
  1915. if (conn->state == CONTROL_CONN_STATE_NEEDAUTH_V1 &&
  1916. strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  1917. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  1918. conn->incoming_cmd_cur_len = 0;
  1919. goto again;
  1920. }
  1921. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  1922. if (handle_control_setconf(conn, data_len, args))
  1923. return -1;
  1924. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  1925. if (handle_control_resetconf(conn, data_len, args))
  1926. return -1;
  1927. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  1928. if (handle_control_getconf(conn, data_len, args))
  1929. return -1;
  1930. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  1931. if (handle_control_setevents(conn, data_len, args))
  1932. return -1;
  1933. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  1934. if (handle_control_authenticate(conn, data_len, args))
  1935. return -1;
  1936. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  1937. if (handle_control_saveconf(conn, data_len, args))
  1938. return -1;
  1939. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  1940. if (handle_control_signal(conn, data_len, args))
  1941. return -1;
  1942. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  1943. if (handle_control_mapaddress(conn, data_len, args))
  1944. return -1;
  1945. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  1946. if (handle_control_getinfo(conn, data_len, args))
  1947. return -1;
  1948. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  1949. if (handle_control_extendcircuit(conn, data_len, args))
  1950. return -1;
  1951. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  1952. if (handle_control_attachstream(conn, data_len, args))
  1953. return -1;
  1954. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  1955. if (handle_control_postdescriptor(conn, data_len, args))
  1956. return -1;
  1957. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  1958. if (handle_control_redirectstream(conn, data_len, args))
  1959. return -1;
  1960. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  1961. if (handle_control_closestream(conn, data_len, args))
  1962. return -1;
  1963. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  1964. if (handle_control_closecircuit(conn, data_len, args))
  1965. return -1;
  1966. } else {
  1967. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  1968. conn->incoming_cmd);
  1969. }
  1970. conn->incoming_cmd_cur_len = 0;
  1971. goto again;
  1972. }
  1973. /** Called when data has arrived on a v0 control connection: Try to fetch
  1974. * commands from conn->inbuf, and execute them.
  1975. */
  1976. static int
  1977. connection_control_process_inbuf_v0(connection_t *conn)
  1978. {
  1979. uint32_t body_len;
  1980. uint16_t command_type;
  1981. char *body=NULL;
  1982. again:
  1983. /* Try to suck a control message from the buffer. */
  1984. switch (fetch_from_buf_control0(conn->inbuf, &body_len, &command_type, &body,
  1985. conn->state == CONTROL_CONN_STATE_NEEDAUTH_V0))
  1986. {
  1987. case -2:
  1988. tor_free(body);
  1989. log_fn(LOG_INFO, "Detected v1 control protocol on connection (fd %d)",
  1990. conn->s);
  1991. conn->state = CONTROL_CONN_STATE_NEEDAUTH_V1;
  1992. return connection_control_process_inbuf_v1(conn);
  1993. case -1:
  1994. tor_free(body);
  1995. log_fn(LOG_WARN, "Error in control command. Failing.");
  1996. return -1;
  1997. case 0:
  1998. /* Control command not all here yet. Wait. */
  1999. return 0;
  2000. case 1:
  2001. /* We got a command. Process it. */
  2002. break;
  2003. default:
  2004. tor_assert(0);
  2005. }
  2006. /* We got a command. If we need authentication, only authentication
  2007. * commands will be considered. */
  2008. if (conn->state == CONTROL_CONN_STATE_NEEDAUTH_V0 &&
  2009. command_type != CONTROL0_CMD_AUTHENTICATE) {
  2010. log_fn(LOG_WARN, "Rejecting '%s' command; authentication needed.",
  2011. control_cmd_to_string(command_type));
  2012. send_control0_error(conn, ERR_UNAUTHORIZED, "Authentication required");
  2013. tor_free(body);
  2014. goto again;
  2015. }
  2016. if (command_type == CONTROL0_CMD_FRAGMENTHEADER ||
  2017. command_type == CONTROL0_CMD_FRAGMENT) {
  2018. if (handle_control_fragments(conn, command_type, body_len, body))
  2019. return -1;
  2020. tor_free(body);
  2021. if (conn->incoming_cmd_cur_len != conn->incoming_cmd_len)
  2022. goto again;
  2023. command_type = conn->incoming_cmd_type;
  2024. body_len = conn->incoming_cmd_len;
  2025. body = conn->incoming_cmd;
  2026. conn->incoming_cmd = NULL;
  2027. } else if (conn->incoming_cmd) {
  2028. log_fn(LOG_WARN, "Dropping incomplete fragmented command");
  2029. tor_free(conn->incoming_cmd);
  2030. }
  2031. /* Okay, we're willing to process the command. */
  2032. switch (command_type)
  2033. {
  2034. case CONTROL0_CMD_SETCONF:
  2035. if (handle_control_setconf(conn, body_len, body))
  2036. return -1;
  2037. break;
  2038. case CONTROL0_CMD_GETCONF:
  2039. if (handle_control_getconf(conn, body_len, body))
  2040. return -1;
  2041. break;
  2042. case CONTROL0_CMD_SETEVENTS:
  2043. if (handle_control_setevents(conn, body_len, body))
  2044. return -1;
  2045. break;
  2046. case CONTROL0_CMD_AUTHENTICATE:
  2047. if (handle_control_authenticate(conn, body_len, body))
  2048. return -1;
  2049. break;
  2050. case CONTROL0_CMD_SAVECONF:
  2051. if (handle_control_saveconf(conn, body_len, body))
  2052. return -1;
  2053. break;
  2054. case CONTROL0_CMD_SIGNAL:
  2055. if (handle_control_signal(conn, body_len, body))
  2056. return -1;
  2057. break;
  2058. case CONTROL0_CMD_MAPADDRESS:
  2059. if (handle_control_mapaddress(conn, body_len, body))
  2060. return -1;
  2061. break;
  2062. case CONTROL0_CMD_GETINFO:
  2063. if (handle_control_getinfo(conn, body_len, body))
  2064. return -1;
  2065. break;
  2066. case CONTROL0_CMD_EXTENDCIRCUIT:
  2067. if (handle_control_extendcircuit(conn, body_len, body))
  2068. return -1;
  2069. break;
  2070. case CONTROL0_CMD_ATTACHSTREAM:
  2071. if (handle_control_attachstream(conn, body_len, body))
  2072. return -1;
  2073. break;
  2074. case CONTROL0_CMD_POSTDESCRIPTOR:
  2075. if (handle_control_postdescriptor(conn, body_len, body))
  2076. return -1;
  2077. break;
  2078. case CONTROL0_CMD_REDIRECTSTREAM:
  2079. if (handle_control_redirectstream(conn, body_len, body))
  2080. return -1;
  2081. break;
  2082. case CONTROL0_CMD_CLOSESTREAM:
  2083. if (handle_control_closestream(conn, body_len, body))
  2084. return -1;
  2085. break;
  2086. case CONTROL0_CMD_CLOSECIRCUIT:
  2087. if (handle_control_closecircuit(conn, body_len, body))
  2088. return -1;
  2089. break;
  2090. case CONTROL0_CMD_ERROR:
  2091. case CONTROL0_CMD_DONE:
  2092. case CONTROL0_CMD_CONFVALUE:
  2093. case CONTROL0_CMD_EVENT:
  2094. case CONTROL0_CMD_INFOVALUE:
  2095. log_fn(LOG_WARN, "Received client-only '%s' command; ignoring.",
  2096. control_cmd_to_string(command_type));
  2097. send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
  2098. "Command type only valid from server to tor client");
  2099. break;
  2100. case CONTROL0_CMD_FRAGMENTHEADER:
  2101. case CONTROL0_CMD_FRAGMENT:
  2102. log_fn(LOG_WARN, "Recieved command fragment out of order; ignoring.");
  2103. send_control0_error(conn, ERR_SYNTAX, "Bad fragmentation on command.");
  2104. default:
  2105. log_fn(LOG_WARN, "Received unrecognized command type %d; ignoring.",
  2106. (int)command_type);
  2107. send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
  2108. "Unrecognized command type");
  2109. break;
  2110. }
  2111. tor_free(body);
  2112. goto again; /* There might be more data. */
  2113. }
  2114. /** Called when <b>conn</b> has received more bytes on its inbuf.
  2115. */
  2116. int
  2117. connection_control_process_inbuf(connection_t *conn)
  2118. {
  2119. tor_assert(conn);
  2120. tor_assert(conn->type == CONN_TYPE_CONTROL);
  2121. if (STATE_IS_V0(conn->state))
  2122. return connection_control_process_inbuf_v0(conn);
  2123. else
  2124. return connection_control_process_inbuf_v1(conn);
  2125. }
  2126. /** Something has happened to circuit <b>circ</b>: tell any interested
  2127. * control connections. */
  2128. int
  2129. control_event_circuit_status(circuit_t *circ, circuit_status_event_t tp)
  2130. {
  2131. char *path, *msg;
  2132. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  2133. return 0;
  2134. tor_assert(circ);
  2135. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  2136. path = circuit_list_path(circ,0);
  2137. if (EVENT_IS_INTERESTING0(EVENT_CIRCUIT_STATUS)) {
  2138. size_t path_len = strlen(path);
  2139. msg = tor_malloc(1+4+path_len+1); /* event, circid, path, NUL. */
  2140. msg[0] = (uint8_t) tp;
  2141. set_uint32(msg+1, htonl(circ->global_identifier));
  2142. strlcpy(msg+5,path,path_len+1);
  2143. send_control0_event(EVENT_CIRCUIT_STATUS, (uint32_t)(path_len+6), msg);
  2144. tor_free(msg);
  2145. }
  2146. if (EVENT_IS_INTERESTING1(EVENT_CIRCUIT_STATUS)) {
  2147. const char *status;
  2148. switch (tp)
  2149. {
  2150. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2151. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  2152. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  2153. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  2154. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  2155. default:
  2156. log_fn(LOG_WARN, "Unrecognized status code %d", (int)tp);
  2157. return 0;
  2158. }
  2159. send_control1_event(EVENT_CIRCUIT_STATUS,
  2160. "650 CIRC %lu %s %s\r\n",
  2161. (unsigned long)circ->global_identifier,
  2162. status, path);
  2163. }
  2164. tor_free(path);
  2165. return 0;
  2166. }
  2167. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  2168. * <b>buf</b>, determine the address:port combination requested on
  2169. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  2170. * failure. */
  2171. static int
  2172. write_stream_target_to_buf(connection_t *conn, char *buf, size_t len)
  2173. {
  2174. char buf2[256];
  2175. if (conn->chosen_exit_name)
  2176. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  2177. return -1;
  2178. if (tor_snprintf(buf, len, "%s%s:%d",
  2179. conn->socks_request->address,
  2180. conn->chosen_exit_name ? buf2 : "",
  2181. conn->socks_request->port)<0)
  2182. return -1;
  2183. return 0;
  2184. }
  2185. /** Something has happened to the stream associated with AP connection
  2186. * <b>conn</b>: tell any interested control connections. */
  2187. int
  2188. control_event_stream_status(connection_t *conn, stream_status_event_t tp)
  2189. {
  2190. char *msg;
  2191. size_t len;
  2192. char buf[256];
  2193. tor_assert(conn->type == CONN_TYPE_AP);
  2194. tor_assert(conn->socks_request);
  2195. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  2196. return 0;
  2197. write_stream_target_to_buf(conn, buf, sizeof(buf));
  2198. if (EVENT_IS_INTERESTING0(EVENT_STREAM_STATUS)) {
  2199. len = strlen(buf);
  2200. msg = tor_malloc(5+len+1);
  2201. msg[0] = (uint8_t) tp;
  2202. set_uint32(msg+1, htonl(conn->global_identifier));
  2203. strlcpy(msg+5, buf, len+1);
  2204. send_control0_event(EVENT_STREAM_STATUS, (uint32_t)(5+len+1), msg);
  2205. tor_free(msg);
  2206. }
  2207. if (EVENT_IS_INTERESTING1(EVENT_STREAM_STATUS)) {
  2208. const char *status;
  2209. circuit_t *circ;
  2210. switch (tp)
  2211. {
  2212. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  2213. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  2214. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  2215. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  2216. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  2217. case STREAM_EVENT_NEW: status = "NEW"; break;
  2218. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  2219. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  2220. default:
  2221. log_fn(LOG_WARN, "Unrecognized status code %d", (int)tp);
  2222. return 0;
  2223. }
  2224. circ = circuit_get_by_edge_conn(conn);
  2225. send_control1_event(EVENT_STREAM_STATUS,
  2226. "650 STREAM %lu %s %lu %s\r\n",
  2227. (unsigned long)conn->global_identifier, status,
  2228. circ?(unsigned long)circ->global_identifier : 0ul,
  2229. buf);
  2230. /* XXX need to specify its intended exit, etc? */
  2231. }
  2232. return 0;
  2233. }
  2234. /** Something has happened to the OR connection <b>conn</b>: tell any
  2235. * interested control connections. */
  2236. int
  2237. control_event_or_conn_status(connection_t *conn,or_conn_status_event_t tp)
  2238. {
  2239. char buf[HEX_DIGEST_LEN+3]; /* status, dollar, identity, NUL */
  2240. size_t len;
  2241. tor_assert(conn->type == CONN_TYPE_OR);
  2242. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  2243. return 0;
  2244. if (EVENT_IS_INTERESTING0(EVENT_OR_CONN_STATUS)) {
  2245. buf[0] = (uint8_t)tp;
  2246. strlcpy(buf+1,conn->nickname,sizeof(buf)-1);
  2247. len = strlen(buf+1);
  2248. send_control0_event(EVENT_OR_CONN_STATUS, (uint32_t)(len+1), buf);
  2249. }
  2250. if (EVENT_IS_INTERESTING1(EVENT_OR_CONN_STATUS)) {
  2251. const char *status;
  2252. switch (tp)
  2253. {
  2254. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2255. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  2256. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  2257. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  2258. default:
  2259. log_fn(LOG_WARN, "Unrecognized status code %d", (int)tp);
  2260. return 0;
  2261. }
  2262. send_control1_event(EVENT_OR_CONN_STATUS,
  2263. "650 ORCONN %s %s\r\n",
  2264. conn->nickname, status);
  2265. }
  2266. return 0;
  2267. }
  2268. /** A second or more has elapsed: tell any interested control
  2269. * connections how much bandwidth we used. */
  2270. int
  2271. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  2272. {
  2273. char buf[8];
  2274. if (EVENT_IS_INTERESTING0(EVENT_BANDWIDTH_USED)) {
  2275. set_uint32(buf, htonl(n_read));
  2276. set_uint32(buf+4, htonl(n_written));
  2277. send_control0_event(EVENT_BANDWIDTH_USED, 8, buf);
  2278. }
  2279. if (EVENT_IS_INTERESTING1(EVENT_BANDWIDTH_USED)) {
  2280. send_control1_event(EVENT_BANDWIDTH_USED,
  2281. "650 BW %lu %lu\r\n",
  2282. (unsigned long)n_read,
  2283. (unsigned long)n_written);
  2284. }
  2285. return 0;
  2286. }
  2287. /** Called when we are sending a log message to the controllers: suspend
  2288. * sending further log messages to the controllers until we're done. Used by
  2289. * CONN_LOG_PROTECT. */
  2290. void
  2291. disable_control_logging(void)
  2292. {
  2293. ++disable_log_messages;
  2294. }
  2295. /** We're done sending a log message to the controllers: re-enable controller
  2296. * logging. Used by CONN_LOG_PROTECT. */
  2297. void
  2298. enable_control_logging(void)
  2299. {
  2300. if (--disable_log_messages < 0)
  2301. tor_assert(0);
  2302. }
  2303. /** We got a log message: tell any interested control connections. */
  2304. void
  2305. control_event_logmsg(int severity, const char *msg)
  2306. {
  2307. int oldlog, event;
  2308. if (disable_log_messages)
  2309. return;
  2310. oldlog = EVENT_IS_INTERESTING0(EVENT_LOG_OBSOLETE) &&
  2311. (severity == LOG_NOTICE || severity == LOG_WARN || severity == LOG_ERR);
  2312. event = log_severity_to_event(severity);
  2313. if (event<0 || !EVENT_IS_INTERESTING0(event))
  2314. event = 0;
  2315. if (oldlog || event) {
  2316. size_t len = strlen(msg);
  2317. ++disable_log_messages;
  2318. if (event)
  2319. send_control0_event(event, (uint32_t)(len+1), msg);
  2320. if (oldlog)
  2321. send_control0_event(EVENT_LOG_OBSOLETE, (uint32_t)(len+1), msg);
  2322. --disable_log_messages;
  2323. }
  2324. event = log_severity_to_event(severity);
  2325. if (event >= 0 && EVENT_IS_INTERESTING1(event)) {
  2326. char *b = NULL;
  2327. const char *s;
  2328. if (strchr(msg, '\n')) {
  2329. char *cp;
  2330. b = tor_strdup(msg);
  2331. for (cp = b; *cp; ++cp)
  2332. if (*cp == '\r' || *cp == '\n')
  2333. *cp = ' ';
  2334. }
  2335. switch (severity) {
  2336. case LOG_DEBUG: s = "DEBUG"; break;
  2337. case LOG_INFO: s = "INFO"; break;
  2338. case LOG_NOTICE: s = "NOTICE"; break;
  2339. case LOG_WARN: s = "WARN"; break;
  2340. case LOG_ERR: s = "ERR"; break;
  2341. default: s = "UnknownLogSeverity"; break;
  2342. }
  2343. ++disable_log_messages;
  2344. send_control1_event(event, "650 %s %s\r\n", s, b?b:msg);
  2345. --disable_log_messages;
  2346. tor_free(b);
  2347. }
  2348. }
  2349. /** Called whenever we receive new router descriptors: tell any
  2350. * interested control connections. <b>routers</b> is a list of
  2351. * DIGEST_LEN-byte identity digests.
  2352. */
  2353. int
  2354. control_event_descriptors_changed(smartlist_t *routers)
  2355. {
  2356. size_t len;
  2357. char *msg;
  2358. smartlist_t *identities;
  2359. char buf[HEX_DIGEST_LEN+1];
  2360. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  2361. return 0;
  2362. identities = smartlist_create();
  2363. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  2364. {
  2365. base16_encode(buf,sizeof(buf),r->identity_digest,DIGEST_LEN);
  2366. smartlist_add(identities, tor_strdup(buf));
  2367. });
  2368. if (EVENT_IS_INTERESTING0(EVENT_NEW_DESC)) {
  2369. msg = smartlist_join_strings(identities, ",", 0, &len);
  2370. send_control0_event(EVENT_NEW_DESC, len+1, msg);
  2371. tor_free(msg);
  2372. }
  2373. if (EVENT_IS_INTERESTING1(EVENT_NEW_DESC)) {
  2374. msg = smartlist_join_strings(identities, " ", 0, &len);
  2375. send_control1_event(EVENT_NEW_DESC, "650 NEWDESC %s\r\n", msg);
  2376. tor_free(msg);
  2377. }
  2378. SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
  2379. smartlist_free(identities);
  2380. return 0;
  2381. }
  2382. /** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
  2383. * <b>expires</b> values less than 3 are special; see connection_edge.c. */
  2384. int
  2385. control_event_address_mapped(const char *from, const char *to, time_t expires)
  2386. {
  2387. if (!EVENT_IS_INTERESTING1(EVENT_ADDRMAP))
  2388. return 0;
  2389. if (expires < 3)
  2390. send_control1_event(EVENT_ADDRMAP, "650 ADDRMAP %s %s NEVER\r\n", from, to);
  2391. else {
  2392. char buf[ISO_TIME_LEN+1];
  2393. format_local_iso_time(buf,expires);
  2394. send_control1_event(EVENT_ADDRMAP, "650 ADDRMAP %s %s \"%s\"\r\n",
  2395. from, to, buf);
  2396. }
  2397. return 0;
  2398. }
  2399. /** Choose a random authentication cookie and write it to disk.
  2400. * Anybody who can read the cookie from disk will be considered
  2401. * authorized to use the control connection. */
  2402. int
  2403. init_cookie_authentication(int enabled)
  2404. {
  2405. char fname[512];
  2406. if (!enabled) {
  2407. authentication_cookie_is_set = 0;
  2408. return 0;
  2409. }
  2410. tor_snprintf(fname, sizeof(fname), "%s/control_auth_cookie",
  2411. get_options()->DataDirectory);
  2412. crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  2413. authentication_cookie_is_set = 1;
  2414. if (write_bytes_to_file(fname, authentication_cookie,
  2415. AUTHENTICATION_COOKIE_LEN, 1)) {
  2416. log_fn(LOG_WARN,"Error writing authentication cookie.");
  2417. return -1;
  2418. }
  2419. return 0;
  2420. }