control.c 75 KB

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