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