r13732@catbus: nickm | 2007-07-12 12:35:06 -0400
[tor.git] / src / or / control.c
blob6a1006347bb5319e4dad6b1ccea5ae4b0e0b7f1c
1 /* Copyright 2004-2007 Roger Dingledine, Nick Mathewson. */
2 /* See LICENSE for licensing information */
3 /* $Id$ */
4 const char control_c_id[] =
5 "$Id$";
7 /**
8 * \file control.c
9 * \brief Implementation for Tor's control-socket interface.
10 **/
12 #include "or.h"
14 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
15 * finished authentication and is accepting commands. */
16 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN_V0 || \
17 (s) == CONTROL_CONN_STATE_OPEN_V1)
18 /** Yield true iff <b>s</b> is the state of a control_connection_t that is
19 * speaking the V0 protocol.
21 #define STATE_IS_V0(s) ((s) == CONTROL_CONN_STATE_NEEDAUTH_V0 || \
22 (s) == CONTROL_CONN_STATE_OPEN_V0)
25 * See control-spec.txt and control-spec-v0.txt for full details on
26 * protocol(s).
29 /* Recognized version 0 message type codes; do not add new codes to this list.
30 * Version 0 is dead; version 1 doesn't use codes. */
31 #define CONTROL0_CMD_ERROR 0x0000
32 #define CONTROL0_CMD_DONE 0x0001
33 #define CONTROL0_CMD_SETCONF 0x0002
34 #define CONTROL0_CMD_GETCONF 0x0003
35 #define CONTROL0_CMD_CONFVALUE 0x0004
36 #define CONTROL0_CMD_SETEVENTS 0x0005
37 #define CONTROL0_CMD_EVENT 0x0006
38 #define CONTROL0_CMD_AUTHENTICATE 0x0007
39 #define CONTROL0_CMD_SAVECONF 0x0008
40 #define CONTROL0_CMD_SIGNAL 0x0009
41 #define CONTROL0_CMD_MAPADDRESS 0x000A
42 #define CONTROL0_CMD_GETINFO 0x000B
43 #define CONTROL0_CMD_INFOVALUE 0x000C
44 #define CONTROL0_CMD_EXTENDCIRCUIT 0x000D
45 #define CONTROL0_CMD_ATTACHSTREAM 0x000E
46 #define CONTROL0_CMD_POSTDESCRIPTOR 0x000F
47 #define CONTROL0_CMD_FRAGMENTHEADER 0x0010
48 #define CONTROL0_CMD_FRAGMENT 0x0011
49 #define CONTROL0_CMD_REDIRECTSTREAM 0x0012
50 #define CONTROL0_CMD_CLOSESTREAM 0x0013
51 #define CONTROL0_CMD_CLOSECIRCUIT 0x0014
52 #define _CONTROL0_CMD_MAX_RECOGNIZED 0x0014
54 /* Recognized version 0 error codes. Do not expand. */
55 #define ERR_UNSPECIFIED 0x0000
56 #define ERR_INTERNAL 0x0001
57 #define ERR_UNRECOGNIZED_TYPE 0x0002
58 #define ERR_SYNTAX 0x0003
59 #define ERR_UNRECOGNIZED_CONFIG_KEY 0x0004
60 #define ERR_INVALID_CONFIG_VALUE 0x0005
61 #define ERR_UNRECOGNIZED_EVENT_CODE 0x0006
62 #define ERR_UNAUTHORIZED 0x0007
63 #define ERR_REJECTED_AUTHENTICATION 0x0008
64 #define ERR_RESOURCE_EXHAUSTED 0x0009
65 #define ERR_NO_STREAM 0x000A
66 #define ERR_NO_CIRC 0x000B
67 #define ERR_NO_ROUTER 0x000C
69 /* Recognized asynchronous event types. It's okay to expand this list
70 * because it is used both as a list of v0 event types, and as indices
71 * into the bitfield to determine which controllers want which events.
73 #define _EVENT_MIN 0x0001
74 #define EVENT_CIRCUIT_STATUS 0x0001
75 #define EVENT_STREAM_STATUS 0x0002
76 #define EVENT_OR_CONN_STATUS 0x0003
77 #define EVENT_BANDWIDTH_USED 0x0004
78 #define EVENT_LOG_OBSOLETE 0x0005
79 #define EVENT_NEW_DESC 0x0006
80 #define EVENT_DEBUG_MSG 0x0007
81 #define EVENT_INFO_MSG 0x0008
82 #define EVENT_NOTICE_MSG 0x0009
83 #define EVENT_WARN_MSG 0x000A
84 #define EVENT_ERR_MSG 0x000B
85 #define LAST_V0_EVENT 0x000B
86 #define EVENT_ADDRMAP 0x000C
87 #define EVENT_AUTHDIR_NEWDESCS 0x000D
88 #define EVENT_DESCCHANGED 0x000E
89 #define EVENT_NS 0x000F
90 #define EVENT_STATUS_CLIENT 0x0010
91 #define EVENT_STATUS_SERVER 0x0011
92 #define EVENT_STATUS_GENERAL 0x0012
93 #define EVENT_GUARD 0x0013
94 #define EVENT_STREAM_BANDWIDTH_USED 0x0014
95 #define _EVENT_MAX 0x0014
96 /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
98 /** Array mapping from message type codes to human-readable message
99 * type names. Used for compatibility with version 0 of the control
100 * protocol. Do not add new items to this list. */
101 static const char * CONTROL0_COMMANDS[_CONTROL0_CMD_MAX_RECOGNIZED+1] = {
102 "error",
103 "done",
104 "setconf",
105 "getconf",
106 "confvalue",
107 "setevents",
108 "events",
109 "authenticate",
110 "saveconf",
111 "signal",
112 "mapaddress",
113 "getinfo",
114 "infovalue",
115 "extendcircuit",
116 "attachstream",
117 "postdescriptor",
118 "fragmentheader",
119 "fragment",
120 "redirectstream",
121 "closestream",
122 "closecircuit",
125 /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
126 * connection is interested in events of type <b>e</b>. We use this
127 * so that we can decide to skip generating event messages that nobody
128 * has interest in without having to walk over the global connection
129 * list to find out.
131 typedef uint32_t event_mask_t;
132 static event_mask_t global_event_mask0 = 0;
133 static event_mask_t global_event_mask1long = 0;
134 static event_mask_t global_event_mask1short = 0;
136 /** True iff we have disabled log messages from being sent to the controller */
137 static int disable_log_messages = 0;
139 /** Macro: true if any control connection is interested in events of type
140 * <b>e</b>. */
141 #define EVENT_IS_INTERESTING0(e) (global_event_mask0 & (1<<(e)))
142 #define EVENT_IS_INTERESTING1(e) \
143 ((global_event_mask1long|global_event_mask1short) & (1<<(e)))
144 #define EVENT_IS_INTERESTING1L(e) (global_event_mask1long & (1<<(e)))
145 #define EVENT_IS_INTERESTING1S(e) (global_event_mask1short & (1<<(e)))
146 #define EVENT_IS_INTERESTING(e) \
147 ((global_event_mask0|global_event_mask1short|global_event_mask1long) \
148 & (1<<(e)))
150 /** If we're using cookie-type authentication, how long should our cookies be?
152 #define AUTHENTICATION_COOKIE_LEN 32
154 /** If true, we've set authentication_cookie to a secret code and
155 * stored it to disk. */
156 static int authentication_cookie_is_set = 0;
157 static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
159 #define SHORT_NAMES 1
160 #define LONG_NAMES 2
161 #define ALL_NAMES (SHORT_NAMES|LONG_NAMES)
162 #define EXTENDED_FORMAT 4
163 #define NONEXTENDED_FORMAT 8
164 #define ALL_FORMATS (EXTENDED_FORMAT|NONEXTENDED_FORMAT)
165 typedef int event_format_t;
167 static void connection_printf_to_buf(control_connection_t *conn,
168 const char *format, ...)
169 CHECK_PRINTF(2,3);
170 /*static*/ size_t write_escaped_data(const char *data, size_t len,
171 int translate_newlines, char **out);
172 /*static*/ size_t read_escaped_data(const char *data, size_t len,
173 int translate_newlines, char **out);
174 static void send_control0_message(control_connection_t *conn, uint16_t type,
175 uint32_t len, const char *body);
176 static void send_control_done(control_connection_t *conn);
177 static void send_control_done2(control_connection_t *conn, const char *msg,
178 size_t len);
179 static void send_control0_error(control_connection_t *conn, uint16_t error,
180 const char *message);
181 static void send_control0_event(uint16_t event, uint32_t len,
182 const char *body);
183 static void send_control1_event(uint16_t event, event_format_t which,
184 const char *format, ...)
185 CHECK_PRINTF(3,4);
186 static void send_control1_event_extended(uint16_t event, event_format_t which,
187 const char *format, ...)
188 CHECK_PRINTF(3,4);
189 static int handle_control_setconf(control_connection_t *conn, uint32_t len,
190 char *body);
191 static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
192 char *body);
193 static int handle_control_getconf(control_connection_t *conn, uint32_t len,
194 const char *body);
195 static int handle_control_setevents(control_connection_t *conn, uint32_t len,
196 const char *body);
197 static int handle_control_authenticate(control_connection_t *conn,
198 uint32_t len,
199 const char *body);
200 static int handle_control_saveconf(control_connection_t *conn, uint32_t len,
201 const char *body);
202 static int handle_control_signal(control_connection_t *conn, uint32_t len,
203 const char *body);
204 static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
205 const char *body);
206 static char *list_getinfo_options(void);
207 static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
208 const char *body);
209 static int handle_control_extendcircuit(control_connection_t *conn,
210 uint32_t len,
211 const char *body);
212 static int handle_control_setpurpose(control_connection_t *conn,
213 int for_circuits,
214 uint32_t len, const char *body);
215 static int handle_control_attachstream(control_connection_t *conn,
216 uint32_t len,
217 const char *body);
218 static int handle_control_postdescriptor(control_connection_t *conn,
219 uint32_t len,
220 const char *body);
221 static int handle_control_redirectstream(control_connection_t *conn,
222 uint32_t len,
223 const char *body);
224 static int handle_control_closestream(control_connection_t *conn, uint32_t len,
225 const char *body);
226 static int handle_control_closecircuit(control_connection_t *conn,
227 uint32_t len,
228 const char *body);
229 static int handle_control_usefeature(control_connection_t *conn,
230 uint32_t len,
231 const char *body);
232 static int write_stream_target_to_buf(edge_connection_t *conn, char *buf,
233 size_t len);
234 static void orconn_target_get_name(int long_names, char *buf, size_t len,
235 or_connection_t *conn);
237 /** Given a possibly invalid message type code <b>cmd</b>, return a
238 * human-readable string equivalent. */
239 static INLINE const char *
240 control_cmd_to_string(uint16_t cmd)
242 return (cmd<=_CONTROL0_CMD_MAX_RECOGNIZED) ?
243 CONTROL0_COMMANDS[cmd] : "Unknown";
246 /** Given a control event code for a message event, return the corresponding
247 * log severity. */
248 static INLINE int
249 event_to_log_severity(int event)
251 switch (event) {
252 case EVENT_DEBUG_MSG: return LOG_DEBUG;
253 case EVENT_INFO_MSG: return LOG_INFO;
254 case EVENT_NOTICE_MSG: return LOG_NOTICE;
255 case EVENT_WARN_MSG: return LOG_WARN;
256 case EVENT_ERR_MSG: return LOG_ERR;
257 default: return -1;
261 /** Given a log severity, return the corresponding control event code. */
262 static INLINE int
263 log_severity_to_event(int severity)
265 switch (severity) {
266 case LOG_DEBUG: return EVENT_DEBUG_MSG;
267 case LOG_INFO: return EVENT_INFO_MSG;
268 case LOG_NOTICE: return EVENT_NOTICE_MSG;
269 case LOG_WARN: return EVENT_WARN_MSG;
270 case LOG_ERR: return EVENT_ERR_MSG;
271 default: return -1;
275 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
276 * connection's event_mask field. */
277 void
278 control_update_global_event_mask(void)
280 connection_t **conns;
281 int n_conns, i;
282 event_mask_t old_mask, new_mask;
283 old_mask = global_event_mask0;
284 old_mask |= global_event_mask1short;
285 old_mask |= global_event_mask1long;
287 global_event_mask0 = 0;
288 global_event_mask1short = 0;
289 global_event_mask1long = 0;
290 get_connection_array(&conns, &n_conns);
291 for (i = 0; i < n_conns; ++i) {
292 if (conns[i]->type == CONN_TYPE_CONTROL &&
293 STATE_IS_OPEN(conns[i]->state)) {
294 control_connection_t *conn = TO_CONTROL_CONN(conns[i]);
295 if (STATE_IS_V0(conn->_base.state))
296 global_event_mask0 |= conn->event_mask;
297 else if (conn->use_long_names)
298 global_event_mask1long |= conn->event_mask;
299 else
300 global_event_mask1short |= conn->event_mask;
304 new_mask = global_event_mask0;
305 new_mask |= global_event_mask1short;
306 new_mask |= global_event_mask1long;
308 /* Handle the aftermath. Set up the log callback to tell us only what
309 * we want to hear...*/
310 control_adjust_event_log_severity();
312 /* ...then, if we've started logging stream bw, clear the appropriate
313 * fields. */
314 if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
315 (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
316 for (i = 0; i < n_conns; ++i) {
317 if (conns[i]->type == CONN_TYPE_AP) {
318 edge_connection_t *conn = TO_EDGE_CONN(conns[i]);
319 conn->n_written = conn->n_read = 0;
325 /** Adjust the log severities that result in control_event_logmsg being called
326 * to match the severity of log messages that any controllers are interested
327 * in. */
328 void
329 control_adjust_event_log_severity(void)
331 int i;
332 int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
334 for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
335 if (EVENT_IS_INTERESTING(i)) {
336 min_log_event = i;
337 break;
340 for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
341 if (EVENT_IS_INTERESTING(i)) {
342 max_log_event = i;
343 break;
346 if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE) ||
347 EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
348 if (min_log_event > EVENT_NOTICE_MSG)
349 min_log_event = EVENT_NOTICE_MSG;
350 if (max_log_event < EVENT_ERR_MSG)
351 max_log_event = EVENT_ERR_MSG;
353 change_callback_log_severity(event_to_log_severity(min_log_event),
354 event_to_log_severity(max_log_event),
355 control_event_logmsg);
358 /** Append a NUL-terminated string <b>s</b> to the end of
359 * <b>conn</b>-\>outbuf
361 static INLINE void
362 connection_write_str_to_buf(const char *s, control_connection_t *conn)
364 size_t len = strlen(s);
365 connection_write_to_buf(s, len, TO_CONN(conn));
368 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
369 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
370 * the contents of <b>data</b> into *<b>out</b>, adding a period
371 * before any period that that appears at the start of a line, and
372 * adding a period-CRLF line at the end. If <b>translate_newlines</b>
373 * is true, replace all LF characters sequences with CRLF. Return the
374 * number of bytes in *<b>out</b>.
376 /* static */ size_t
377 write_escaped_data(const char *data, size_t len, int translate_newlines,
378 char **out)
380 size_t sz_out = len+8;
381 char *outp;
382 const char *end;
383 int i;
384 int start_of_line;
385 for (i=0; i<(int)len; ++i) {
386 if (data[i]== '\n')
387 sz_out += 2; /* Maybe add a CR; maybe add a dot. */
389 *out = outp = tor_malloc(sz_out+1);
390 end = data+len;
391 start_of_line = 1;
392 while (data < end) {
393 if (*data == '\n') {
394 if (translate_newlines)
395 *outp++ = '\r';
396 start_of_line = 1;
397 } else if (*data == '.') {
398 if (start_of_line) {
399 start_of_line = 0;
400 *outp++ = '.';
402 } else {
403 start_of_line = 0;
405 *outp++ = *data++;
407 if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
408 *outp++ = '\r';
409 *outp++ = '\n';
411 *outp++ = '.';
412 *outp++ = '\r';
413 *outp++ = '\n';
414 *outp = '\0'; /* NUL-terminate just in case. */
415 tor_assert((outp - *out) <= (int)sz_out);
416 return outp - *out;
419 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
420 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
421 * the contents of <b>data</b> into *<b>out</b>, removing any period
422 * that appears at the start of a line. If <b>translate_newlines</b>
423 * is true, replace all CRLF sequences with LF. Return the number of
424 * bytes in *<b>out</b>. */
425 /*static*/ size_t
426 read_escaped_data(const char *data, size_t len, int translate_newlines,
427 char **out)
429 char *outp;
430 const char *next;
431 const char *end;
433 *out = outp = tor_malloc(len+1);
435 end = data+len;
437 while (data < end) {
438 if (*data == '.')
439 ++data;
440 if (translate_newlines)
441 next = tor_memmem(data, end-data, "\r\n", 2);
442 else
443 next = tor_memmem(data, end-data, "\r\n.", 3);
444 if (next) {
445 memcpy(outp, data, next-data);
446 outp += (next-data);
447 data = next+2;
448 } else {
449 memcpy(outp, data, end-data);
450 outp += (end-data);
451 *outp = '\0';
452 return outp - *out;
454 if (translate_newlines) {
455 *outp++ = '\n';
456 } else {
457 *outp++ = '\r';
458 *outp++ = '\n';
462 *outp = '\0';
463 return outp - *out;
466 /** Given a pointer to a string starting at <b>start</b> containing
467 * <b>in_len_max</b> characters, decode a string beginning with a single
468 * quote, containing any number of non-quote characters or characters escaped
469 * with a backslash, and ending with a final quote. Place the resulting
470 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
471 * store its length in <b>out_len</b>. On success, return a pointer to the
472 * character immediately following the escaped string. On failure, return
473 * NULL. */
474 static const char *
475 get_escaped_string(const char *start, size_t in_len_max,
476 char **out, size_t *out_len)
478 const char *cp, *end;
479 char *outp;
480 size_t len=0;
482 if (*start != '\"')
483 return NULL;
485 cp = start+1;
486 end = start+in_len_max;
488 /* Calculate length. */
489 while (1) {
490 if (cp >= end)
491 return NULL;
492 else if (*cp == '\\') {
493 if (++cp == end)
494 return NULL; /* Can't escape EOS. */
495 ++cp;
496 ++len;
497 } else if (*cp == '\"') {
498 break;
499 } else {
500 ++cp;
501 ++len;
504 end = cp;
505 outp = *out = tor_malloc(len+1);
506 *out_len = len;
508 cp = start+1;
509 while (cp < end) {
510 if (*cp == '\\')
511 ++cp;
512 *outp++ = *cp++;
514 *outp = '\0';
515 tor_assert((outp - *out) == (int)*out_len);
517 return end+1;
520 /** Acts like sprintf, but writes its formatted string to the end of
521 * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
522 * but it will always end with a CRLF sequence.
524 * Currently the length of the message is limited to 1024 (including the
525 * ending \n\r\0. */
526 static void
527 connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
529 #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
530 va_list ap;
531 char buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE];
532 int r;
533 size_t len;
534 va_start(ap,format);
535 r = tor_vsnprintf(buf, sizeof(buf), format, ap);
536 va_end(ap);
537 if (r<0) {
538 log_warn(LD_BUG, "Unable to format string for controller.");
539 return;
541 len = strlen(buf);
542 if (memcmp("\r\n\0", buf+len-2, 3)) {
543 buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-1] = '\0';
544 buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-2] = '\n';
545 buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-3] = '\r';
547 connection_write_to_buf(buf, len, TO_CONN(conn));
550 /** Send a message of type <b>type</b> containing <b>len</b> bytes
551 * from <b>body</b> along the control connection <b>conn</b> */
552 static void
553 send_control0_message(control_connection_t *conn, uint16_t type, uint32_t len,
554 const char *body)
556 char buf[10];
557 tor_assert(conn);
558 tor_assert(STATE_IS_V0(conn->_base.state));
559 tor_assert(len || !body);
560 tor_assert(type <= _CONTROL0_CMD_MAX_RECOGNIZED);
561 if (len < 65536) {
562 set_uint16(buf, htons(len));
563 set_uint16(buf+2, htons(type));
564 connection_write_to_buf(buf, 4, TO_CONN(conn));
565 if (len)
566 connection_write_to_buf(body, len, TO_CONN(conn));
567 } else {
568 set_uint16(buf, htons(65535));
569 set_uint16(buf+2, htons(CONTROL0_CMD_FRAGMENTHEADER));
570 set_uint16(buf+4, htons(type));
571 set_uint32(buf+6, htonl(len));
572 connection_write_to_buf(buf, 10, TO_CONN(conn));
573 connection_write_to_buf(body, 65535-6, TO_CONN(conn));
574 len -= (65535-6);
575 body += (65535-6);
576 while (len) {
577 size_t chunklen = (len<65535)?len:65535;
578 set_uint16(buf, htons((uint16_t)chunklen));
579 set_uint16(buf+2, htons(CONTROL0_CMD_FRAGMENT));
580 connection_write_to_buf(buf, 4, TO_CONN(conn));
581 connection_write_to_buf(body, chunklen, TO_CONN(conn));
582 len -= chunklen;
583 body += chunklen;
588 /** Send a "DONE" message down the control connection <b>conn</b> */
589 static void
590 send_control_done(control_connection_t *conn)
592 if (STATE_IS_V0(conn->_base.state)) {
593 send_control0_message(conn, CONTROL0_CMD_DONE, 0, NULL);
594 } else {
595 connection_write_str_to_buf("250 OK\r\n", conn);
599 /** Send a "DONE" message down the v0 control message <b>conn</b>, with body
600 * as provided in the <b>len</b> bytes at <b>msg</b>.
602 static void
603 send_control_done2(control_connection_t *conn, const char *msg, size_t len)
605 if (len==0)
606 len = strlen(msg);
607 send_control0_message(conn, CONTROL0_CMD_DONE, len, msg);
610 /** Send an error message with error code <b>error</b> and body
611 * <b>message</b> down the connection <b>conn</b> */
612 static void
613 send_control0_error(control_connection_t *conn, uint16_t error,
614 const char *message)
616 char buf[256];
617 size_t len;
618 set_uint16(buf, htons(error));
619 len = strlen(message);
620 tor_assert(len < (256-2));
621 memcpy(buf+2, message, len);
622 send_control0_message(conn, CONTROL0_CMD_ERROR, (uint16_t)(len+2), buf);
625 /** Send an 'event' message of event type <b>event</b>, containing
626 * <b>len</b> bytes in <b>body</b> to every control connection that
627 * is interested in it. */
628 static void
629 send_control0_event(uint16_t event, uint32_t len, const char *body)
631 connection_t **conns;
632 int n_conns, i;
633 size_t buflen;
634 char *buf;
636 tor_assert(event >= _EVENT_MIN && event <= LAST_V0_EVENT);
638 buflen = len + 2;
639 buf = tor_malloc_zero(buflen);
640 set_uint16(buf, htons(event));
641 memcpy(buf+2, body, len);
643 get_connection_array(&conns, &n_conns);
644 for (i = 0; i < n_conns; ++i) {
645 if (conns[i]->type == CONN_TYPE_CONTROL &&
646 !conns[i]->marked_for_close &&
647 conns[i]->state == CONTROL_CONN_STATE_OPEN_V0) {
648 control_connection_t *control_conn = TO_CONTROL_CONN(conns[i]);
649 if (control_conn->event_mask & (1<<event)) {
650 send_control0_message(control_conn, CONTROL0_CMD_EVENT, buflen, buf);
651 if (event == EVENT_ERR_MSG)
652 connection_handle_write(TO_CONN(control_conn), 1);
657 tor_free(buf);
660 /* Send an event to all v1 controllers that are listening for code
661 * <b>event</b>. The event's body is given by <b>msg</b>.
663 * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
664 * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
665 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
666 * to contollers that <em>have</em> enabled VERBOSE_NAMES.
668 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
669 * respect to the EXTENDED_EVENTS feature. */
670 static void
671 send_control1_event_string(uint16_t event, event_format_t which,
672 const char *msg)
674 connection_t **conns;
675 int n_conns, i;
677 tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);
679 get_connection_array(&conns, &n_conns);
680 for (i = 0; i < n_conns; ++i) {
681 if (conns[i]->type == CONN_TYPE_CONTROL &&
682 !conns[i]->marked_for_close &&
683 conns[i]->state == CONTROL_CONN_STATE_OPEN_V1) {
684 control_connection_t *control_conn = TO_CONTROL_CONN(conns[i]);
685 if (control_conn->use_long_names) {
686 if (!(which & LONG_NAMES))
687 continue;
688 } else {
689 if (!(which & SHORT_NAMES))
690 continue;
692 if (control_conn->use_extended_events) {
693 if (!(which & EXTENDED_FORMAT))
694 continue;
695 } else {
696 if (!(which & NONEXTENDED_FORMAT))
697 continue;
699 if (control_conn->event_mask & (1<<event)) {
700 int is_err = 0;
701 connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
702 if (event == EVENT_ERR_MSG)
703 is_err = 1;
704 else if (event == EVENT_STATUS_GENERAL)
705 is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
706 else if (event == EVENT_STATUS_CLIENT)
707 is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
708 else if (event == EVENT_STATUS_SERVER)
709 is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
710 if (is_err)
711 connection_handle_write(TO_CONN(control_conn), 1);
717 /** Helper for send_control1_event and send_control1_event_extended:
718 * Send an event to all v1 controllers that are listening for code
719 * <b>event</b>. The event's body is created by the printf-style format in
720 * <b>format</b>, and other arguments as provided.
722 * If <b>extended</b> is true, and the format contains a single '@' character,
723 * it will be replaced with a space and all text after that character will be
724 * sent only to controllers that have enabled extended events.
726 * Currently the length of the message is limited to 1024 (including the
727 * ending \n\r\0). */
728 static void
729 send_control1_event_impl(uint16_t event, event_format_t which, int extended,
730 const char *format, va_list ap)
732 /* This is just a little longer than the longest allowed log message */
733 #define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
734 int r;
735 char buf[SEND_CONTROL1_EVENT_BUFFERSIZE];
736 size_t len;
737 char *cp;
739 r = tor_vsnprintf(buf, sizeof(buf), format, ap);
740 if (r<0) {
741 log_warn(LD_BUG, "Unable to format event for controller.");
742 return;
745 len = strlen(buf);
746 if (memcmp("\r\n\0", buf+len-2, 3)) {
747 /* if it is not properly terminated, do it now */
748 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-1] = '\0';
749 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-2] = '\n';
750 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-3] = '\r';
753 if (extended && (cp = strchr(buf, '@'))) {
754 which &= ~ALL_FORMATS;
755 *cp = ' ';
756 send_control1_event_string(event, which|EXTENDED_FORMAT, buf);
757 memcpy(cp, "\r\n\0", 3);
758 send_control1_event_string(event, which|NONEXTENDED_FORMAT, buf);
759 } else {
760 send_control1_event_string(event, which|ALL_FORMATS, buf);
764 /* Send an event to all v1 controllers that are listening for code
765 * <b>event</b>. The event's body is created by the printf-style format in
766 * <b>format</b>, and other arguments as provided.
768 * Currently the length of the message is limited to 1024 (including the
769 * ending \n\r\0. */
770 static void
771 send_control1_event(uint16_t event, event_format_t which,
772 const char *format, ...)
774 va_list ap;
775 va_start(ap, format);
776 send_control1_event_impl(event, which, 0, format, ap);
777 va_end(ap);
780 /* Send an event to all v1 controllers that are listening for code
781 * <b>event</b>. The event's body is created by the printf-style format in
782 * <b>format</b>, and other arguments as provided.
784 * If the format contains a single '@' character, it will be replaced with a
785 * space and all text after that character will be sent only to controllers
786 * that have enabled extended events.
788 * Currently the length of the message is limited to 1024 (including the
789 * ending \n\r\0. */
790 static void
791 send_control1_event_extended(uint16_t event, event_format_t which,
792 const char *format, ...)
794 va_list ap;
795 va_start(ap, format);
796 send_control1_event_impl(event, which, 1, format, ap);
797 va_end(ap);
800 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
801 static origin_circuit_t *
802 get_circ(const char *id)
804 unsigned long n_id;
805 int ok;
806 n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
807 if (!ok)
808 return NULL;
809 return circuit_get_by_global_id(n_id);
812 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
813 static edge_connection_t *
814 get_stream(const char *id)
816 unsigned long n_id;
817 int ok;
818 edge_connection_t *conn;
819 n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
820 if (!ok)
821 return NULL;
822 conn = connection_get_by_global_id(n_id);
823 if (!conn || conn->_base.type != CONN_TYPE_AP)
824 return NULL;
825 return conn;
828 /** Helper for setconf and resetconf. Acts like setconf, except
829 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
830 * contents of body.
832 static int
833 control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
834 int use_defaults, int clear_first)
836 int r;
837 config_line_t *lines=NULL;
838 char *start = body;
839 char *errstring = NULL;
840 int v0 = STATE_IS_V0(conn->_base.state);
842 if (!v0) {
843 char *config;
844 smartlist_t *entries = smartlist_create();
845 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
846 * separated by space. break it into a list of configuration entries. */
847 while (*body) {
848 char *eq = body;
849 char *key;
850 char *entry;
851 while (!TOR_ISSPACE(*eq) && *eq != '=')
852 ++eq;
853 key = tor_strndup(body, eq-body);
854 body = eq+1;
855 if (*eq == '=') {
856 char *val;
857 size_t val_len;
858 size_t ent_len;
859 if (*body != '\"') {
860 char *val_start = body;
861 while (!TOR_ISSPACE(*body))
862 body++;
863 val = tor_strndup(val_start, body-val_start);
864 val_len = strlen(val);
865 } else {
866 body = (char*)get_escaped_string(body, (len - (body-start)),
867 &val, &val_len);
868 if (!body) {
869 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
870 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
871 smartlist_free(entries);
872 return 0;
875 ent_len = strlen(key)+val_len+3;
876 entry = tor_malloc(ent_len+1);
877 tor_snprintf(entry, ent_len, "%s %s", key, val);
878 tor_free(key);
879 tor_free(val);
880 } else {
881 entry = key;
883 smartlist_add(entries, entry);
884 while (TOR_ISSPACE(*body))
885 ++body;
888 smartlist_add(entries, tor_strdup(""));
889 config = smartlist_join_strings(entries, "\n", 0, NULL);
890 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
891 smartlist_free(entries);
893 if (config_get_lines(config, &lines) < 0) {
894 log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
895 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
896 conn);
897 tor_free(config);
898 return 0;
900 tor_free(config);
901 } else {
902 if (config_get_lines(body, &lines) < 0) {
903 log_warn(LD_CONTROL,
904 "V0 controller gave us config lines we can't parse.");
905 send_control0_error(conn, ERR_SYNTAX, "Couldn't parse configuration");
906 return 0;
910 if ((r=options_trial_assign(lines, use_defaults,
911 clear_first, &errstring)) < 0) {
912 int v0_err;
913 const char *msg;
914 log_warn(LD_CONTROL,
915 "Controller gave us config lines that didn't validate: %s.",
916 errstring);
917 switch (r) {
918 case -1:
919 v0_err = ERR_UNRECOGNIZED_CONFIG_KEY;
920 msg = "552 Unrecognized option";
921 break;
922 case -2:
923 v0_err = ERR_INVALID_CONFIG_VALUE;
924 msg = "513 Unacceptable option value";
925 break;
926 case -3:
927 v0_err = ERR_INVALID_CONFIG_VALUE;
928 msg = "553 Transition not allowed";
929 break;
930 case -4:
931 default:
932 v0_err = ERR_INVALID_CONFIG_VALUE;
933 msg = "553 Unable to set option";
934 break;
936 if (v0) {
937 send_control0_error(conn, v0_err, msg);
938 } else {
939 connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
941 config_free_lines(lines);
942 tor_free(errstring);
943 return 0;
945 config_free_lines(lines);
946 send_control_done(conn);
947 return 0;
950 /** Called when we receive a SETCONF message: parse the body and try
951 * to update our configuration. Reply with a DONE or ERROR message.
952 * Modifies the contents of body.*/
953 static int
954 handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
956 return control_setconf_helper(conn, len, body, 0, 1);
959 /** Called when we receive a RESETCONF message: parse the body and try
960 * to update our configuration. Reply with a DONE or ERROR message.
961 * Modifies the contents of body. */
962 static int
963 handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
965 int v0 = STATE_IS_V0(conn->_base.state);
966 tor_assert(!v0);
967 return control_setconf_helper(conn, len, body, 1, 1);
970 /** Called when we receive a GETCONF message. Parse the request, and
971 * reply with a CONFVALUE or an ERROR message */
972 static int
973 handle_control_getconf(control_connection_t *conn, uint32_t body_len,
974 const char *body)
976 smartlist_t *questions = NULL;
977 smartlist_t *answers = NULL;
978 smartlist_t *unrecognized = NULL;
979 char *msg = NULL;
980 size_t msg_len;
981 or_options_t *options = get_options();
982 int v0 = STATE_IS_V0(conn->_base.state);
984 questions = smartlist_create();
985 (void) body_len; /* body is nul-terminated; so we can ignore len. */
986 if (v0) {
987 smartlist_split_string(questions, body, "\n",
988 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
989 } else {
990 smartlist_split_string(questions, body, " ",
991 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
993 answers = smartlist_create();
994 unrecognized = smartlist_create();
995 SMARTLIST_FOREACH(questions, char *, q,
997 if (!option_is_recognized(q)) {
998 if (v0) {
999 send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, q);
1000 goto done;
1001 } else {
1002 smartlist_add(unrecognized, q);
1004 } else {
1005 config_line_t *answer = option_get_assignment(options,q);
1006 if (!v0 && !answer) {
1007 const char *name = option_get_canonical_name(q);
1008 size_t alen = strlen(name)+8;
1009 char *astr = tor_malloc(alen);
1010 tor_snprintf(astr, alen, "250-%s\r\n", name);
1011 smartlist_add(answers, astr);
1014 while (answer) {
1015 config_line_t *next;
1016 size_t alen = strlen(answer->key)+strlen(answer->value)+8;
1017 char *astr = tor_malloc(alen);
1018 if (v0)
1019 tor_snprintf(astr, alen, "%s %s\n", answer->key, answer->value);
1020 else
1021 tor_snprintf(astr, alen, "250-%s=%s\r\n",
1022 answer->key, answer->value);
1023 smartlist_add(answers, astr);
1025 next = answer->next;
1026 tor_free(answer->key);
1027 tor_free(answer->value);
1028 tor_free(answer);
1029 answer = next;
1034 if (v0) {
1035 msg = smartlist_join_strings(answers, "", 0, &msg_len);
1036 send_control0_message(conn, CONTROL0_CMD_CONFVALUE,
1037 (uint16_t)msg_len, msg_len?msg:NULL);
1038 } else {
1039 int i,len;
1040 if ((len = smartlist_len(unrecognized))) {
1041 for (i=0; i < len-1; ++i)
1042 connection_printf_to_buf(conn,
1043 "552-Unrecognized configuration key \"%s\"\r\n",
1044 (char*)smartlist_get(unrecognized, i));
1045 connection_printf_to_buf(conn,
1046 "552 Unrecognized configuration key \"%s\"\r\n",
1047 (char*)smartlist_get(unrecognized, len-1));
1048 } else if ((len = smartlist_len(answers))) {
1049 char *tmp = smartlist_get(answers, len-1);
1050 tor_assert(strlen(tmp)>4);
1051 tmp[3] = ' ';
1052 msg = smartlist_join_strings(answers, "", 0, &msg_len);
1053 connection_write_to_buf(msg, msg_len, TO_CONN(conn));
1054 } else {
1055 connection_write_str_to_buf("250 OK\r\n", conn);
1059 done:
1060 if (answers) {
1061 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
1062 smartlist_free(answers);
1064 if (questions) {
1065 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
1066 smartlist_free(questions);
1068 smartlist_free(unrecognized);
1069 tor_free(msg);
1071 return 0;
1074 /** Called when we get a SETEVENTS message: update conn->event_mask,
1075 * and reply with DONE or ERROR. */
1076 static int
1077 handle_control_setevents(control_connection_t *conn, uint32_t len,
1078 const char *body)
1080 uint16_t event_code;
1081 uint32_t event_mask = 0;
1082 unsigned int extended = 0;
1084 if (STATE_IS_V0(conn->_base.state)) {
1085 if (len % 2) {
1086 send_control0_error(conn, ERR_SYNTAX,
1087 "Odd number of bytes in setevents message");
1088 return 0;
1091 for (; len; len -= 2, body += 2) {
1092 event_code = ntohs(get_uint16(body));
1093 if (event_code < _EVENT_MIN || event_code > LAST_V0_EVENT) {
1094 send_control0_error(conn, ERR_UNRECOGNIZED_EVENT_CODE,
1095 "Unrecognized event code");
1096 return 0;
1098 event_mask |= (1 << event_code);
1100 } else {
1101 smartlist_t *events = smartlist_create();
1102 smartlist_split_string(events, body, " ",
1103 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1104 SMARTLIST_FOREACH(events, const char *, ev,
1106 if (!strcasecmp(ev, "EXTENDED")) {
1107 extended = 1;
1108 continue;
1109 } else if (!strcasecmp(ev, "CIRC"))
1110 event_code = EVENT_CIRCUIT_STATUS;
1111 else if (!strcasecmp(ev, "STREAM"))
1112 event_code = EVENT_STREAM_STATUS;
1113 else if (!strcasecmp(ev, "ORCONN"))
1114 event_code = EVENT_OR_CONN_STATUS;
1115 else if (!strcasecmp(ev, "BW"))
1116 event_code = EVENT_BANDWIDTH_USED;
1117 else if (!strcasecmp(ev, "DEBUG"))
1118 event_code = EVENT_DEBUG_MSG;
1119 else if (!strcasecmp(ev, "INFO"))
1120 event_code = EVENT_INFO_MSG;
1121 else if (!strcasecmp(ev, "NOTICE"))
1122 event_code = EVENT_NOTICE_MSG;
1123 else if (!strcasecmp(ev, "WARN"))
1124 event_code = EVENT_WARN_MSG;
1125 else if (!strcasecmp(ev, "ERR"))
1126 event_code = EVENT_ERR_MSG;
1127 else if (!strcasecmp(ev, "NEWDESC"))
1128 event_code = EVENT_NEW_DESC;
1129 else if (!strcasecmp(ev, "ADDRMAP"))
1130 event_code = EVENT_ADDRMAP;
1131 else if (!strcasecmp(ev, "AUTHDIR_NEWDESCS"))
1132 event_code = EVENT_AUTHDIR_NEWDESCS;
1133 else if (!strcasecmp(ev, "DESCCHANGED"))
1134 event_code = EVENT_DESCCHANGED;
1135 else if (!strcasecmp(ev, "NS"))
1136 event_code = EVENT_NS;
1137 else if (!strcasecmp(ev, "STATUS_GENERAL"))
1138 event_code = EVENT_STATUS_GENERAL;
1139 else if (!strcasecmp(ev, "STATUS_CLIENT"))
1140 event_code = EVENT_STATUS_CLIENT;
1141 else if (!strcasecmp(ev, "STATUS_SERVER"))
1142 event_code = EVENT_STATUS_SERVER;
1143 else if (!strcasecmp(ev, "GUARD"))
1144 event_code = EVENT_GUARD;
1145 else if (!strcasecmp(ev, "GUARDS")) {
1146 /* XXX tolerate buggy spec in 0.1.2.5-alpha through 0.1.2.10-rc */
1147 event_code = EVENT_GUARD;
1148 } else if (!strcasecmp(ev, "STREAM_BW"))
1149 event_code = EVENT_STREAM_BANDWIDTH_USED;
1150 else {
1151 connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
1152 ev);
1153 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
1154 smartlist_free(events);
1155 return 0;
1157 event_mask |= (1 << event_code);
1159 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
1160 smartlist_free(events);
1162 conn->event_mask = event_mask;
1163 if (extended)
1164 conn->use_extended_events = 1;
1166 control_update_global_event_mask();
1167 send_control_done(conn);
1168 return 0;
1171 /** Decode the hashed, base64'd password stored in <b>hashed</b>. If
1172 * <b>buf</b> is provided, store the hashed password in the first
1173 * S2K_SPECIFIER_LEN+DIGEST_LEN bytes of <b>buf</b>. Return 0 on
1174 * success, -1 on failure.
1177 decode_hashed_password(char *buf, const char *hashed)
1179 char decoded[64];
1180 if (!strcmpstart(hashed, "16:")) {
1181 if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
1182 || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
1183 return -1;
1185 } else {
1186 if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
1187 != S2K_SPECIFIER_LEN+DIGEST_LEN) {
1188 return -1;
1191 if (buf)
1192 memcpy(buf, decoded, S2K_SPECIFIER_LEN+DIGEST_LEN);
1193 return 0;
1196 /** Called when we get an AUTHENTICATE message. Check whether the
1197 * authentication is valid, and if so, update the connection's state to
1198 * OPEN. Reply with DONE or ERROR.
1200 static int
1201 handle_control_authenticate(control_connection_t *conn, uint32_t len,
1202 const char *body)
1204 int used_quoted_string = 0;
1205 or_options_t *options = get_options();
1206 const char *errstr = NULL;
1207 char *password;
1208 size_t password_len;
1209 if (STATE_IS_V0(conn->_base.state)) {
1210 password = (char*)body;
1211 password_len = len;
1212 } else {
1213 if (TOR_ISXDIGIT(body[0])) {
1214 int i = 0;
1215 while (TOR_ISXDIGIT(body[i]))
1216 ++i;
1217 password = tor_malloc(i/2 + 1);
1218 if (base16_decode(password, i/2+1, body, i)<0) {
1219 connection_write_str_to_buf(
1220 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1221 "password? If so, the standard requires that you put it in "
1222 "double quotes.\r\n", conn);
1223 tor_free(password);
1224 return 0;
1226 password_len = i/2;
1227 } else if (TOR_ISSPACE(body[0])) {
1228 password = tor_strdup("");
1229 password_len = 0;
1230 } else {
1231 if (!get_escaped_string(body, len, &password, &password_len)) {
1232 connection_write_str_to_buf("551 Invalid quoted string. You need "
1233 "to put the password in double quotes.\r\n", conn);
1234 return 0;
1236 used_quoted_string = 1;
1239 if (options->CookieAuthentication && authentication_cookie_is_set) {
1240 if (password_len != AUTHENTICATION_COOKIE_LEN) {
1241 log_warn(LD_CONTROL, "Got authentication cookie with wrong length (%d)",
1242 (int)password_len);
1243 errstr = "Wrong length on authentication cookie.";
1244 goto err;
1245 } else if (memcmp(authentication_cookie, password, password_len)) {
1246 log_warn(LD_CONTROL, "Got mismatched authentication cookie");
1247 errstr = "Authentication cookie did not match expected value.";
1248 goto err;
1249 } else {
1250 goto ok;
1252 } else if (options->HashedControlPassword) {
1253 char expected[S2K_SPECIFIER_LEN+DIGEST_LEN];
1254 char received[DIGEST_LEN];
1255 if (decode_hashed_password(expected, options->HashedControlPassword)<0) {
1256 log_warn(LD_CONTROL,
1257 "Couldn't decode HashedControlPassword: invalid base16");
1258 errstr = "Couldn't decode HashedControlPassword value in configuration.";
1259 goto err;
1261 secret_to_key(received,DIGEST_LEN,password,password_len,expected);
1262 if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
1263 goto ok;
1265 if (used_quoted_string)
1266 errstr = "Password did not match HashedControlPassword value from "
1267 "configuration";
1268 else
1269 errstr = "Password did not match HashedControlPassword value from "
1270 "configuration. Maybe you tried a plain text password? "
1271 "If so, the standard requires that you put it in double quotes.";
1272 goto err;
1273 } else {
1274 /* if Tor doesn't demand any stronger authentication, then
1275 * the controller can get in with anything. */
1276 goto ok;
1279 err:
1280 if (STATE_IS_V0(conn->_base.state))
1281 send_control0_error(conn,ERR_REJECTED_AUTHENTICATION,
1282 "Authentication failed");
1283 else {
1284 tor_free(password);
1285 if (!errstr)
1286 errstr = "Unknown reason.";
1287 connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n",
1288 errstr);
1290 return 0;
1292 log_info(LD_CONTROL, "Authenticated control connection (%d)", conn->_base.s);
1293 send_control_done(conn);
1294 if (STATE_IS_V0(conn->_base.state))
1295 conn->_base.state = CONTROL_CONN_STATE_OPEN_V0;
1296 else {
1297 conn->_base.state = CONTROL_CONN_STATE_OPEN_V1;
1298 tor_free(password);
1300 return 0;
1303 /** Called when we get a SAVECONF command. Try to flush the current options to
1304 * disk, and report success or failure. */
1305 static int
1306 handle_control_saveconf(control_connection_t *conn, uint32_t len,
1307 const char *body)
1309 (void) len;
1310 (void) body;
1311 if (options_save_current()<0) {
1312 if (STATE_IS_V0(conn->_base.state))
1313 send_control0_error(conn, ERR_INTERNAL,
1314 "Unable to write configuration to disk.");
1315 else
1316 connection_write_str_to_buf(
1317 "551 Unable to write configuration to disk.\r\n", conn);
1318 } else {
1319 send_control_done(conn);
1321 return 0;
1324 /** Called when we get a SIGNAL command. React to the provided signal, and
1325 * report success or failure. (If the signal results in a shutdown, success
1326 * may not be reported.) */
1327 static int
1328 handle_control_signal(control_connection_t *conn, uint32_t len,
1329 const char *body)
1331 int sig;
1332 if (STATE_IS_V0(conn->_base.state)) {
1333 if (len != 1) {
1334 send_control0_error(conn, ERR_SYNTAX,
1335 "Body of SIGNAL command too long or too short.");
1336 return 0;
1337 } else {
1338 sig = (uint8_t)body[0];
1339 switch (sig)
1341 case 1: sig = SIGHUP; break;
1342 case 2: sig = SIGINT; break;
1343 case 10: sig = SIGUSR1; break;
1344 case 12: sig = SIGUSR2; break;
1345 case 15: sig = SIGTERM; break;
1346 case SIGNEWNYM: break;
1347 default:
1348 send_control0_error(conn, ERR_SYNTAX, "Unrecognized signal number.");
1349 return 0;
1352 } else {
1353 int n = 0;
1354 char *s;
1355 while (body[n] && ! TOR_ISSPACE(body[n]))
1356 ++n;
1357 s = tor_strndup(body, n);
1358 if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
1359 sig = SIGHUP;
1360 else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
1361 sig = SIGINT;
1362 else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
1363 sig = SIGUSR1;
1364 else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
1365 sig = SIGUSR2;
1366 else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
1367 sig = SIGTERM;
1368 else if (!strcasecmp(s, "NEWNYM"))
1369 sig = SIGNEWNYM;
1370 else if (!strcasecmp(s, "CLEARDNSCACHE"))
1371 sig = SIGCLEARDNSCACHE;
1372 else {
1373 connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
1375 sig = -1;
1377 tor_free(s);
1378 if (sig<0)
1379 return 0;
1382 /* Send DONE first, in case the signal makes us shut down. */
1383 send_control_done(conn);
1384 control_signal_act(sig);
1385 return 0;
1388 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1389 * and report success or failrue. */
1390 static int
1391 handle_control_mapaddress(control_connection_t *conn, uint32_t len,
1392 const char *body)
1394 smartlist_t *elts;
1395 smartlist_t *lines;
1396 smartlist_t *reply;
1397 char *r;
1398 size_t sz;
1399 int v0 = STATE_IS_V0(conn->_base.state);
1400 (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
1402 lines = smartlist_create();
1403 elts = smartlist_create();
1404 reply = smartlist_create();
1405 if (v0)
1406 smartlist_split_string(lines, body, "\n",
1407 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1408 else
1409 smartlist_split_string(lines, body, " ",
1410 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1411 SMARTLIST_FOREACH(lines, char *, line,
1413 tor_strlower(line);
1414 if (v0)
1415 smartlist_split_string(elts, line, " ", 0, 2);
1416 else
1417 smartlist_split_string(elts, line, "=", 0, 2);
1418 if (smartlist_len(elts) == 2) {
1419 const char *from = smartlist_get(elts,0);
1420 const char *to = smartlist_get(elts,1);
1421 size_t anslen = strlen(line)+512;
1422 char *ans = tor_malloc(anslen);
1423 if (address_is_invalid_destination(to, 1)) {
1424 if (!v0) {
1425 tor_snprintf(ans, anslen,
1426 "512-syntax error: invalid address '%s'", to);
1427 smartlist_add(reply, ans);
1428 } else
1429 tor_free(ans); /* don't respond if v0 */
1430 log_warn(LD_CONTROL,
1431 "Skipping invalid argument '%s' in MapAddress msg", to);
1432 } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
1433 const char *address = addressmap_register_virtual_address(
1434 !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
1435 tor_strdup(to));
1436 if (!address) {
1437 if (!v0) {
1438 tor_snprintf(ans, anslen,
1439 "451-resource exhausted: skipping '%s'", line);
1440 smartlist_add(reply, ans);
1441 } else
1442 tor_free(ans); /* don't respond if v0 */
1443 log_warn(LD_CONTROL,
1444 "Unable to allocate address for '%s' in MapAddress msg",
1445 safe_str(line));
1446 } else {
1447 if (v0)
1448 tor_snprintf(ans, anslen, "%s %s", address, to);
1449 else
1450 tor_snprintf(ans, anslen, "250-%s=%s", address, to);
1451 smartlist_add(reply, ans);
1453 } else {
1454 addressmap_register(from, tor_strdup(to), 1);
1455 if (v0)
1456 tor_snprintf(ans, anslen, "%s", line);
1457 else
1458 tor_snprintf(ans, anslen, "250-%s", line);
1459 smartlist_add(reply, ans);
1461 } else {
1462 if (!v0) {
1463 size_t anslen = strlen(line)+256;
1464 char *ans = tor_malloc(anslen);
1465 tor_snprintf(ans, anslen, "512-syntax error: mapping '%s' is "
1466 "not of expected form 'foo=bar'.", line);
1467 smartlist_add(reply, ans);
1469 log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
1470 "number of items.", safe_str(line));
1472 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
1473 smartlist_clear(elts);
1475 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1476 smartlist_free(lines);
1477 smartlist_free(elts);
1479 if (v0) {
1480 r = smartlist_join_strings(reply, "\n", 1, &sz);
1481 send_control_done2(conn,r,sz);
1482 tor_free(r);
1483 } else {
1484 if (smartlist_len(reply)) {
1485 ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
1486 r = smartlist_join_strings(reply, "\r\n", 1, &sz);
1487 connection_write_to_buf(r, sz, TO_CONN(conn));
1488 tor_free(r);
1489 } else {
1490 const char *response =
1491 "512 syntax error: not enough arguments to mapaddress.\r\n";
1492 connection_write_to_buf(response, strlen(response), TO_CONN(conn));
1496 SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
1497 smartlist_free(reply);
1498 return 0;
1501 /** Implementation helper for GETINFO: knows the answers for various
1502 * trivial-to-implement questions. */
1503 static int
1504 getinfo_helper_misc(control_connection_t *conn, const char *question,
1505 char **answer)
1507 (void) conn;
1508 if (!strcmp(question, "version")) {
1509 *answer = tor_strdup(VERSION);
1510 } else if (!strcmp(question, "config-file")) {
1511 *answer = tor_strdup(get_torrc_fname());
1512 } else if (!strcmp(question, "info/names")) {
1513 *answer = list_getinfo_options();
1514 } else if (!strcmp(question, "events/names")) {
1515 *answer = tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
1516 "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
1517 "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
1518 "GUARD STREAM_BW");
1519 } else if (!strcmp(question, "features/names")) {
1520 *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1521 } else if (!strcmp(question, "address")) {
1522 uint32_t addr;
1523 if (router_pick_published_address(get_options(), &addr) < 0)
1524 return -1;
1525 *answer = tor_dup_addr(addr);
1526 } else if (!strcmp(question, "dir-usage")) {
1527 *answer = directory_dump_request_log();
1528 } else if (!strcmp(question, "fingerprint")) {
1529 routerinfo_t *me = router_get_my_routerinfo();
1530 if (!me) {
1531 *answer = tor_strdup("");
1532 } else {
1533 *answer = tor_malloc(HEX_DIGEST_LEN+1);
1534 base16_encode(*answer, HEX_DIGEST_LEN+1, me->cache_info.identity_digest,
1535 DIGEST_LEN);
1538 return 0;
1541 /** Implementation helper for GETINFO: knows the answers for questions about
1542 * directory information. */
1543 static int
1544 getinfo_helper_dir(control_connection_t *control_conn,
1545 const char *question, char **answer)
1547 if (!strcmpstart(question, "desc/id/")) {
1548 routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
1549 if (ri) {
1550 const char *body = signed_descriptor_get_body(&ri->cache_info);
1551 if (body)
1552 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1554 } else if (!strcmpstart(question, "desc/name/")) {
1555 routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
1556 if (ri) {
1557 const char *body = signed_descriptor_get_body(&ri->cache_info);
1558 if (body)
1559 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1561 } else if (!strcmp(question, "desc/all-recent")) {
1562 routerlist_t *routerlist = router_get_routerlist();
1563 smartlist_t *sl = smartlist_create();
1564 if (routerlist && routerlist->routers) {
1565 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
1567 const char *body = signed_descriptor_get_body(&ri->cache_info);
1568 if (body)
1569 smartlist_add(sl,
1570 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1573 *answer = smartlist_join_strings(sl, "", 0, NULL);
1574 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1575 smartlist_free(sl);
1576 } else if (!strcmpstart(question, "dir/server/")) {
1577 size_t answer_len = 0, url_len = strlen(question)+2;
1578 char *url = tor_malloc(url_len);
1579 smartlist_t *descs = smartlist_create();
1580 const char *msg;
1581 int res;
1582 char *cp;
1583 tor_snprintf(url, url_len, "/tor/%s", question+4);
1584 res = dirserv_get_routerdescs(descs, url, &msg);
1585 if (res) {
1586 log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
1587 return -1;
1589 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1590 answer_len += sd->signed_descriptor_len);
1591 cp = *answer = tor_malloc(answer_len+1);
1592 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1594 memcpy(cp, signed_descriptor_get_body(sd),
1595 sd->signed_descriptor_len);
1596 cp += sd->signed_descriptor_len;
1598 *cp = '\0';
1599 tor_free(url);
1600 smartlist_free(descs);
1601 } else if (!strcmpstart(question, "dir/status/")) {
1602 if (get_options()->DirPort) {
1603 size_t len=0;
1604 char *cp;
1605 smartlist_t *status_list = smartlist_create();
1606 dirserv_get_networkstatus_v2(status_list,
1607 question+strlen("dir/status/"));
1608 SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
1609 cp = *answer = tor_malloc(len+1);
1610 SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
1611 memcpy(cp, d->dir, d->dir_len);
1612 cp += d->dir_len;
1614 *cp = '\0';
1615 smartlist_free(status_list);
1616 } else {
1617 smartlist_t *fp_list = smartlist_create();
1618 smartlist_t *status_list = smartlist_create();
1619 size_t fn_len = strlen(get_options()->DataDirectory)+HEX_DIGEST_LEN+32;
1620 char *fn = tor_malloc(fn_len+1);
1621 char hex_id[HEX_DIGEST_LEN+1];
1622 dirserv_get_networkstatus_v2_fingerprints(
1623 fp_list, question+strlen("dir/status/"));
1624 SMARTLIST_FOREACH(fp_list, const char *, fp, {
1625 char *s;
1626 base16_encode(hex_id, sizeof(hex_id), fp, DIGEST_LEN);
1627 tor_snprintf(fn, fn_len, "%s/cached-status/%s",
1628 get_options()->DataDirectory, hex_id);
1629 s = read_file_to_str(fn, 0, NULL);
1630 if (s)
1631 smartlist_add(status_list, s);
1633 SMARTLIST_FOREACH(fp_list, char *, fp, tor_free(fp));
1634 smartlist_free(fp_list);
1635 *answer = smartlist_join_strings(status_list, "", 0, NULL);
1636 SMARTLIST_FOREACH(status_list, char *, s, tor_free(s));
1637 smartlist_free(status_list);
1639 } else if (!strcmp(question, "network-status")) {
1640 routerlist_t *routerlist = router_get_routerlist();
1641 int verbose = control_conn->use_long_names;
1642 if (!routerlist || !routerlist->routers ||
1643 list_server_status(routerlist->routers, answer, verbose ? 2 : 1) < 0) {
1644 return -1;
1647 return 0;
1650 /** Implementation helper for GETINFO: knows how to generate summaries of the
1651 * current states of things we send events about. */
1652 static int
1653 getinfo_helper_events(control_connection_t *control_conn,
1654 const char *question, char **answer)
1656 if (!strcmp(question, "circuit-status")) {
1657 circuit_t *circ;
1658 smartlist_t *status = smartlist_create();
1659 for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
1660 char *s, *path;
1661 size_t slen;
1662 const char *state;
1663 if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
1664 continue;
1665 if (control_conn->use_long_names)
1666 path = circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ));
1667 else
1668 path = circuit_list_path(TO_ORIGIN_CIRCUIT(circ),0);
1669 if (circ->state == CIRCUIT_STATE_OPEN)
1670 state = "BUILT";
1671 else if (strlen(path))
1672 state = "EXTENDED";
1673 else
1674 state = "LAUNCHED";
1676 slen = strlen(path)+strlen(state)+20;
1677 s = tor_malloc(slen+1);
1678 tor_snprintf(s, slen, "%lu %s %s",
1679 (unsigned long)TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1680 state, path);
1681 smartlist_add(status, s);
1682 tor_free(path);
1684 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1685 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1686 smartlist_free(status);
1687 } else if (!strcmp(question, "stream-status")) {
1688 connection_t **conns;
1689 int n_conns, i;
1690 char buf[256];
1691 smartlist_t *status = smartlist_create();
1692 get_connection_array(&conns, &n_conns);
1693 for (i=0; i < n_conns; ++i) {
1694 const char *state;
1695 edge_connection_t *conn;
1696 char *s;
1697 size_t slen;
1698 circuit_t *circ;
1699 origin_circuit_t *origin_circ = NULL;
1700 if (conns[i]->type != CONN_TYPE_AP ||
1701 conns[i]->marked_for_close ||
1702 conns[i]->state == AP_CONN_STATE_SOCKS_WAIT ||
1703 conns[i]->state == AP_CONN_STATE_NATD_WAIT)
1704 continue;
1705 conn = TO_EDGE_CONN(conns[i]);
1706 switch (conn->_base.state)
1708 case AP_CONN_STATE_CONTROLLER_WAIT:
1709 case AP_CONN_STATE_CIRCUIT_WAIT:
1710 if (conn->socks_request &&
1711 SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
1712 state = "NEWRESOLVE";
1713 else
1714 state = "NEW";
1715 break;
1716 case AP_CONN_STATE_RENDDESC_WAIT:
1717 case AP_CONN_STATE_CONNECT_WAIT:
1718 state = "SENTCONNECT"; break;
1719 case AP_CONN_STATE_RESOLVE_WAIT:
1720 state = "SENTRESOLVE"; break;
1721 case AP_CONN_STATE_OPEN:
1722 state = "SUCCEEDED"; break;
1723 default:
1724 log_warn(LD_BUG, "Asked for stream in unknown state %d",
1725 conn->_base.state);
1726 continue;
1728 circ = circuit_get_by_edge_conn(conn);
1729 if (circ && CIRCUIT_IS_ORIGIN(circ))
1730 origin_circ = TO_ORIGIN_CIRCUIT(circ);
1731 write_stream_target_to_buf(conn, buf, sizeof(buf));
1732 slen = strlen(buf)+strlen(state)+32;
1733 s = tor_malloc(slen+1);
1734 tor_snprintf(s, slen, "%lu %s %lu %s",
1735 (unsigned long) conn->global_identifier,state,
1736 origin_circ?
1737 (unsigned long)origin_circ->global_identifier : 0ul,
1738 buf);
1739 smartlist_add(status, s);
1741 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1742 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1743 smartlist_free(status);
1744 } else if (!strcmp(question, "orconn-status")) {
1745 connection_t **conns;
1746 int n_conns, i;
1747 smartlist_t *status = smartlist_create();
1748 get_connection_array(&conns, &n_conns);
1749 for (i=0; i < n_conns; ++i) {
1750 const char *state;
1751 char *s;
1752 char name[128];
1753 size_t slen;
1754 or_connection_t *conn;
1755 if (conns[i]->type != CONN_TYPE_OR || conns[i]->marked_for_close)
1756 continue;
1757 conn = TO_OR_CONN(conns[i]);
1758 if (conn->_base.state == OR_CONN_STATE_OPEN)
1759 state = "CONNECTED";
1760 else if (conn->nickname)
1761 state = "LAUNCHED";
1762 else
1763 state = "NEW";
1764 orconn_target_get_name(control_conn->use_long_names, name, sizeof(name),
1765 conn);
1766 slen = strlen(name)+strlen(state)+2;
1767 s = tor_malloc(slen+1);
1768 tor_snprintf(s, slen, "%s %s", name, state);
1769 smartlist_add(status, s);
1771 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1772 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1773 smartlist_free(status);
1774 } else if (!strcmpstart(question, "addr-mappings/")) {
1775 time_t min_e, max_e;
1776 smartlist_t *mappings;
1777 if (!strcmp(question, "addr-mappings/all")) {
1778 min_e = 0; max_e = TIME_MAX;
1779 } else if (!strcmp(question, "addr-mappings/cache")) {
1780 min_e = 2; max_e = TIME_MAX;
1781 } else if (!strcmp(question, "addr-mappings/config")) {
1782 min_e = 0; max_e = 0;
1783 } else if (!strcmp(question, "addr-mappings/control")) {
1784 min_e = 1; max_e = 1;
1785 } else {
1786 return 0;
1788 mappings = smartlist_create();
1789 addressmap_get_mappings(mappings, min_e, max_e);
1790 *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
1791 SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
1792 smartlist_free(mappings);
1794 return 0;
1797 /** Callback function for GETINFO: on a given control connection, try to
1798 * answer the question <b>q</b> and store the newly-allocated answer in
1799 * *<b>a</b>. If there's no answer, or an error occurs, just don't set
1800 * <b>a</b>. Return 0.
1802 typedef int (*getinfo_helper_t)(control_connection_t *,
1803 const char *q, char **a);
1805 /** A single item for the GETINFO question-to-answer-function table. */
1806 typedef struct getinfo_item_t {
1807 const char *varname; /**< The value (or prefix) of the question. */
1808 getinfo_helper_t fn; /**< The function that knows the answer: NULL if
1809 * this entry is documentation-only. */
1810 const char *desc; /**< Description of the variable. */
1811 int is_prefix; /** Must varname match exactly, or must it be a prefix? */
1812 } getinfo_item_t;
1814 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
1815 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
1816 #define DOC(name, desc) { name, NULL, desc, 0 }
1818 /** Table mapping questions accepted by GETINFO to the functions that know how
1819 * to answer them. */
1820 static const getinfo_item_t getinfo_items[] = {
1821 ITEM("version", misc, "The current version of Tor."),
1822 ITEM("config-file", misc, "Current location of the \"torrc\" file."),
1823 ITEM("accounting/bytes", accounting,
1824 "Number of bytes read/written so far in the accounting interval."),
1825 ITEM("accounting/bytes-left", accounting,
1826 "Number of bytes left to write/read so far in the accounting interval."),
1827 ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
1828 ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
1829 ITEM("accounting/interval-start", accounting,
1830 "Time when the accounting period starts."),
1831 ITEM("accounting/interval-end", accounting,
1832 "Time when the accounting period ends."),
1833 ITEM("accounting/interval-wake", accounting,
1834 "Time to wake up in this accounting period."),
1835 ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
1836 ITEM("entry-guards", entry_guards,
1837 "Which nodes are we using as entry guards?"),
1838 ITEM("fingerprint", misc, NULL),
1839 PREFIX("config/", config, "Current configuration values."),
1840 DOC("config/names",
1841 "List of configuration options, types, and documentation."),
1842 ITEM("info/names", misc,
1843 "List of GETINFO options, types, and documentation."),
1844 ITEM("events/names", misc,
1845 "Events that the controller can ask for with SETEVENTS."),
1846 ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
1847 PREFIX("desc/id/", dir, "Router descriptors by ID."),
1848 PREFIX("desc/name/", dir, "Router descriptors by nickname."),
1849 ITEM("desc/all-recent", dir,
1850 "All non-expired, non-superseded router descriptors."),
1851 ITEM("ns/all", networkstatus,
1852 "Brief summary of router status (v2 directory format)"),
1853 PREFIX("ns/id/", networkstatus,
1854 "Brief summary of router status by ID (v2 directory format)."),
1855 PREFIX("ns/name/", networkstatus,
1856 "Brief summary of router status by nickname (v2 directory format)."),
1858 PREFIX("unregisterd-servers-", dirserv_unregistered, NULL),
1859 ITEM("network-status", dir,
1860 "Brief summary of router status (v1 directory format)"),
1861 ITEM("circuit-status", events, "List of current circuits originating here."),
1862 ITEM("stream-status", events,"List of current streams."),
1863 ITEM("orconn-status", events, "A list of current OR connections."),
1864 PREFIX("addr-mappings/", events, NULL),
1865 DOC("addr-mappings/all", "Current address mappings."),
1866 DOC("addr-mappings/cache", "Current cached DNS replies."),
1867 DOC("addr-mappings/config", "Current address mappings from configuration."),
1868 DOC("addr-mappings/control", "Current address mappings from controller."),
1870 ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
1871 ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
1872 PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
1873 PREFIX("dir/status/", dir,"Networkstatus docs as retrieved from a DirPort."),
1874 PREFIX("exit-policy/default", policies,
1875 "The default value appended to the configured exit policy."),
1877 { NULL, NULL, NULL, 0 }
1880 /** Allocate and return a list of recognized GETINFO options. */
1881 static char *
1882 list_getinfo_options(void)
1884 int i;
1885 char buf[300];
1886 smartlist_t *lines = smartlist_create();
1887 char *ans;
1888 for (i = 0; getinfo_items[i].varname; ++i) {
1889 if (!getinfo_items[i].desc)
1890 continue;
1892 tor_snprintf(buf, sizeof(buf), "%s%s -- %s\n",
1893 getinfo_items[i].varname,
1894 getinfo_items[i].is_prefix ? "*" : "",
1895 getinfo_items[i].desc);
1896 smartlist_add(lines, tor_strdup(buf));
1898 smartlist_sort_strings(lines);
1900 ans = smartlist_join_strings(lines, "", 0, NULL);
1901 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1902 smartlist_free(lines);
1904 return ans;
1907 /** Lookup the 'getinfo' entry <b>question</b>, and return
1908 * the answer in <b>*answer</b> (or NULL if key not recognized).
1909 * Return 0 if success or unrecognized, or -1 if recognized but
1910 * internal error. */
1911 static int
1912 handle_getinfo_helper(control_connection_t *control_conn,
1913 const char *question, char **answer)
1915 int i;
1916 *answer = NULL; /* unrecognized key by default */
1918 for (i = 0; getinfo_items[i].varname; ++i) {
1919 int match;
1920 if (getinfo_items[i].is_prefix)
1921 match = !strcmpstart(question, getinfo_items[i].varname);
1922 else
1923 match = !strcmp(question, getinfo_items[i].varname);
1924 if (match) {
1925 tor_assert(getinfo_items[i].fn);
1926 return getinfo_items[i].fn(control_conn, question, answer);
1930 return 0; /* unrecognized */
1933 /** Called when we receive a GETINFO command. Try to fetch all requested
1934 * information, and reply with information or error message. */
1935 static int
1936 handle_control_getinfo(control_connection_t *conn, uint32_t len,
1937 const char *body)
1939 smartlist_t *questions = NULL;
1940 smartlist_t *answers = NULL;
1941 smartlist_t *unrecognized = NULL;
1942 char *msg = NULL, *ans = NULL;
1943 size_t msg_len;
1944 int v0 = STATE_IS_V0(conn->_base.state);
1945 (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
1947 questions = smartlist_create();
1948 if (v0)
1949 smartlist_split_string(questions, body, "\n",
1950 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1951 else
1952 smartlist_split_string(questions, body, " ",
1953 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1954 answers = smartlist_create();
1955 unrecognized = smartlist_create();
1956 SMARTLIST_FOREACH(questions, const char *, q,
1958 if (handle_getinfo_helper(conn, q, &ans) < 0) {
1959 if (v0)
1960 send_control0_error(conn, ERR_INTERNAL, body);
1961 else
1962 connection_write_str_to_buf("551 Internal error\r\n", conn);
1963 goto done;
1965 if (!ans) {
1966 if (v0) {
1967 send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
1968 goto done;
1969 } else
1970 smartlist_add(unrecognized, (char*)q);
1971 } else {
1972 smartlist_add(answers, tor_strdup(q));
1973 smartlist_add(answers, ans);
1976 if (smartlist_len(unrecognized)) {
1977 int i;
1978 tor_assert(!v0);
1979 for (i=0; i < smartlist_len(unrecognized)-1; ++i)
1980 connection_printf_to_buf(conn,
1981 "552-Unrecognized key \"%s\"\r\n",
1982 (char*)smartlist_get(unrecognized, i));
1983 connection_printf_to_buf(conn,
1984 "552 Unrecognized key \"%s\"\r\n",
1985 (char*)smartlist_get(unrecognized, i));
1986 goto done;
1989 if (v0) {
1990 msg = smartlist_join_strings2(answers, "\0", 1, 1, &msg_len);
1991 tor_assert(msg_len > 0); /* it will at least be terminated */
1992 send_control0_message(conn, CONTROL0_CMD_INFOVALUE,
1993 msg_len, msg);
1994 } else {
1995 int i;
1996 for (i = 0; i < smartlist_len(answers); i += 2) {
1997 char *k = smartlist_get(answers, i);
1998 char *v = smartlist_get(answers, i+1);
1999 if (!strchr(v, '\n') && !strchr(v, '\r')) {
2000 connection_printf_to_buf(conn, "250-%s=", k);
2001 connection_write_str_to_buf(v, conn);
2002 connection_write_str_to_buf("\r\n", conn);
2003 } else {
2004 char *esc = NULL;
2005 size_t len;
2006 len = write_escaped_data(v, strlen(v), 1, &esc);
2007 connection_printf_to_buf(conn, "250+%s=\r\n", k);
2008 connection_write_to_buf(esc, len, TO_CONN(conn));
2009 tor_free(esc);
2012 connection_write_str_to_buf("250 OK\r\n", conn);
2015 done:
2016 if (answers) {
2017 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
2018 smartlist_free(answers);
2020 if (questions) {
2021 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
2022 smartlist_free(questions);
2024 smartlist_free(unrecognized);
2025 tor_free(msg);
2027 return 0;
2030 /** If *<b>string</b> contains a recognized purpose (for
2031 * circuits if <b>for_circuits</b> is 1, else for routers),
2032 * possibly prefaced with the string "purpose=", then assign it
2033 * and return 0. Otherwise return -1.
2035 * If it's prefaced with "purpose=", then set *<b>string</b> to
2036 * the remainder of the string. */
2037 static int
2038 get_purpose(char **string, int for_circuits, uint8_t *purpose)
2040 if (!strcmpstart(*string, "purpose="))
2041 *string += strlen("purpose=");
2043 if (!strcmp(*string, "general"))
2044 *purpose = for_circuits ? CIRCUIT_PURPOSE_C_GENERAL :
2045 ROUTER_PURPOSE_GENERAL;
2046 else if (!strcmp(*string, "controller"))
2047 *purpose = for_circuits ? CIRCUIT_PURPOSE_CONTROLLER :
2048 ROUTER_PURPOSE_CONTROLLER;
2049 else { /* not a recognized purpose */
2050 return -1;
2052 return 0;
2055 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
2056 * circuit, and report success or failure. */
2057 static int
2058 handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
2059 const char *body)
2061 smartlist_t *router_nicknames=NULL, *routers=NULL;
2062 uint32_t circ_id;
2063 origin_circuit_t *circ = NULL;
2064 int zero_circ, v0;
2065 char reply[4];
2066 uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
2068 v0 = STATE_IS_V0(conn->_base.state);
2069 router_nicknames = smartlist_create();
2071 if (v0) {
2072 if (len<5) {
2073 send_control0_error(conn, ERR_SYNTAX, "extendcircuit message too short");
2074 goto done;
2076 smartlist_split_string(router_nicknames, body+4, ",", 0, 0);
2077 circ_id = ntohl(get_uint32(body));
2078 if (!circ_id) {
2079 /* start a new circuit */
2080 zero_circ = 1;
2081 } else {
2082 circ = circuit_get_by_global_id(circ_id);
2083 zero_circ = 0;
2084 if (!circ) {
2085 send_control0_error(conn, ERR_NO_CIRC,
2086 "No circuit found with given ID");
2087 goto done;
2090 } else { /* v1 */
2091 smartlist_t *args;
2092 args = smartlist_create();
2093 smartlist_split_string(args, body, " ",
2094 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2095 if (smartlist_len(args)<2) {
2096 connection_printf_to_buf(conn,
2097 "512 Missing argument to EXTENDCIRCUIT\r\n");
2098 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2099 smartlist_free(args);
2100 goto done;
2103 zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
2104 if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
2105 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2106 (char*)smartlist_get(args, 0));
2108 smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
2110 if (zero_circ && smartlist_len(args)>2) {
2111 char *purp = smartlist_get(args,2);
2112 if (get_purpose(&purp, 1, &intended_purpose) < 0) {
2113 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
2114 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2115 smartlist_free(args);
2116 goto done;
2119 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2120 smartlist_free(args);
2121 if (!zero_circ && !circ) {
2122 goto done;
2126 routers = smartlist_create();
2127 SMARTLIST_FOREACH(router_nicknames, const char *, n,
2129 routerinfo_t *r = router_get_by_nickname(n, 1);
2130 if (!r) {
2131 if (v0)
2132 send_control0_error(conn, ERR_NO_ROUTER, n);
2133 else
2134 connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
2135 goto done;
2137 smartlist_add(routers, r);
2139 if (!smartlist_len(routers)) {
2140 if (v0)
2141 send_control0_error(conn, ERR_SYNTAX, "No router names provided");
2142 else
2143 connection_write_str_to_buf("512 No router names provided\r\n", conn);
2144 goto done;
2147 if (zero_circ) {
2148 /* start a new circuit */
2149 circ = origin_circuit_init(intended_purpose, 0, 0, 0, 0);
2152 /* now circ refers to something that is ready to be extended */
2153 SMARTLIST_FOREACH(routers, routerinfo_t *, r,
2155 extend_info_t *info = extend_info_from_router(r);
2156 circuit_append_new_exit(circ, info);
2157 extend_info_free(info);
2160 /* now that we've populated the cpath, start extending */
2161 if (zero_circ) {
2162 int err_reason = 0;
2163 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
2164 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2165 if (v0)
2166 send_control0_error(conn, ERR_INTERNAL, "couldn't start circuit");
2167 else
2168 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
2169 goto done;
2171 } else {
2172 if (circ->_base.state == CIRCUIT_STATE_OPEN) {
2173 int err_reason = 0;
2174 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
2175 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
2176 log_info(LD_CONTROL,
2177 "send_next_onion_skin failed; circuit marked for closing.");
2178 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2179 if (v0)
2180 send_control0_error(conn, ERR_INTERNAL, "couldn't send onion skin");
2181 else
2182 connection_write_str_to_buf("551 Couldn't send onion skinr\n", conn);
2183 goto done;
2188 if (v0) {
2189 set_uint32(reply, htonl(circ->global_identifier));
2190 send_control_done2(conn, reply, sizeof(reply));
2191 } else {
2192 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
2193 (unsigned long)circ->global_identifier);
2195 if (zero_circ) /* send a 'launched' event, for completeness */
2196 control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
2197 done:
2198 SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
2199 smartlist_free(router_nicknames);
2200 if (routers)
2201 smartlist_free(routers);
2202 return 0;
2205 /** Called when we get a SETCIRCUITPURPOSE (if <b>for_circuits</b>
2206 * is 1) or SETROUTERPURPOSE message. If we can find
2207 * the circuit/router and it's a valid purpose, change it. */
2208 static int
2209 handle_control_setpurpose(control_connection_t *conn, int for_circuits,
2210 uint32_t len, const char *body)
2212 origin_circuit_t *circ = NULL;
2213 routerinfo_t *ri = NULL;
2214 uint8_t new_purpose;
2215 smartlist_t *args = smartlist_create();
2216 (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
2217 smartlist_split_string(args, body, " ",
2218 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2219 if (smartlist_len(args)<2) {
2220 connection_printf_to_buf(conn,
2221 "512 Missing argument to SET%sPURPOSE\r\n",
2222 for_circuits ? "CIRCUIT" : "ROUTER");
2223 goto done;
2226 if (for_circuits) {
2227 if (!(circ = get_circ(smartlist_get(args,0)))) {
2228 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2229 (char*)smartlist_get(args, 0));
2230 goto done;
2232 } else {
2233 if (!(ri = router_get_by_nickname(smartlist_get(args,0), 0))) {
2234 connection_printf_to_buf(conn, "552 Unknown router \"%s\"\r\n",
2235 (char*)smartlist_get(args, 0));
2236 goto done;
2241 char *purp = smartlist_get(args,1);
2242 if (get_purpose(&purp, for_circuits, &new_purpose) < 0) {
2243 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
2244 goto done;
2248 if (for_circuits)
2249 circ->_base.purpose = new_purpose;
2250 else
2251 ri->purpose = new_purpose;
2252 connection_write_str_to_buf("250 OK\r\n", conn);
2254 done:
2255 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2256 smartlist_free(args);
2257 return 0;
2260 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
2261 * stream, and report success or failure. */
2262 static int
2263 handle_control_attachstream(control_connection_t *conn, uint32_t len,
2264 const char *body)
2266 edge_connection_t *ap_conn = NULL;
2267 origin_circuit_t *circ = NULL;
2268 int zero_circ;
2270 if (STATE_IS_V0(conn->_base.state)) {
2271 uint32_t conn_id;
2272 uint32_t circ_id;
2273 if (len < 8) {
2274 send_control0_error(conn, ERR_SYNTAX, "attachstream message too short");
2275 return 0;
2278 conn_id = ntohl(get_uint32(body));
2279 circ_id = ntohl(get_uint32(body+4));
2280 zero_circ = circ_id == 0;
2282 if (!(ap_conn = connection_get_by_global_id(conn_id))) {
2283 send_control0_error(conn, ERR_NO_STREAM,
2284 "No connection found with given ID");
2285 return 0;
2287 if (circ_id && !(circ = circuit_get_by_global_id(circ_id))) {
2288 send_control0_error(conn, ERR_NO_CIRC, "No circuit found with given ID");
2289 return 0;
2291 } else {
2292 smartlist_t *args;
2293 args = smartlist_create();
2294 smartlist_split_string(args, body, " ",
2295 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2296 if (smartlist_len(args)<2) {
2297 connection_printf_to_buf(conn,
2298 "512 Missing argument to ATTACHSTREAM\r\n");
2299 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2300 smartlist_free(args);
2301 return 0;
2304 zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
2306 if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
2307 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2308 (char*)smartlist_get(args, 0));
2309 } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
2310 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2311 (char*)smartlist_get(args, 1));
2313 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2314 smartlist_free(args);
2315 if (!ap_conn || (!zero_circ && !circ))
2316 return 0;
2319 if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT &&
2320 ap_conn->_base.state != AP_CONN_STATE_CONNECT_WAIT &&
2321 ap_conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
2322 if (STATE_IS_V0(conn->_base.state)) {
2323 send_control0_error(conn, ERR_NO_STREAM,
2324 "Connection is not managed by controller.");
2325 } else {
2326 connection_write_str_to_buf(
2327 "555 Connection is not managed by controller.\r\n",
2328 conn);
2330 return 0;
2333 /* Do we need to detach it first? */
2334 if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT) {
2335 circuit_t *tmpcirc = circuit_get_by_edge_conn(ap_conn);
2336 connection_edge_end(ap_conn, END_STREAM_REASON_TIMEOUT,
2337 ap_conn->cpath_layer);
2338 /* Un-mark it as ending, since we're going to reuse it. */
2339 ap_conn->_base.edge_has_sent_end = 0;
2340 ap_conn->end_reason = 0;
2341 if (tmpcirc)
2342 circuit_detach_stream(tmpcirc,ap_conn);
2343 ap_conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
2346 if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
2347 if (STATE_IS_V0(conn->_base.state))
2348 send_control0_error(conn, ERR_INTERNAL,
2349 "Refuse to attach stream to non-open, origin circ.");
2350 else
2351 connection_write_str_to_buf(
2352 "551 Can't attach stream to non-open, origin circuit\r\n",
2353 conn);
2354 return 0;
2356 if (circ && circuit_get_cpath_len(circ) < 2) {
2357 if (STATE_IS_V0(conn->_base.state))
2358 send_control0_error(conn, ERR_INTERNAL,
2359 "Refuse to attach stream to one-hop circuit.");
2360 else
2361 connection_write_str_to_buf(
2362 "551 Can't attach stream to one-hop circuit.\r\n",
2363 conn);
2364 return 0;
2366 if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ) < 0) {
2367 if (STATE_IS_V0(conn->_base.state))
2368 send_control0_error(conn, ERR_INTERNAL, "Unable to attach stream.");
2369 else
2370 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
2371 return 0;
2373 send_control_done(conn);
2374 return 0;
2377 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
2378 * descriptor, and report success or failure. */
2379 static int
2380 handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
2381 const char *body)
2383 char *desc;
2384 int v0 = STATE_IS_V0(conn->_base.state);
2385 const char *msg=NULL;
2386 uint8_t purpose = ROUTER_PURPOSE_GENERAL;
2388 if (v0)
2389 desc = (char*)body;
2390 else {
2391 char *cp = memchr(body, '\n', len);
2392 smartlist_t *args = smartlist_create();
2393 tor_assert(cp);
2394 *cp++ = '\0';
2395 smartlist_split_string(args, body, " ",
2396 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2397 if (smartlist_len(args)) {
2398 char *purp = smartlist_get(args,0);
2399 if (get_purpose(&purp, 0, &purpose) < 0) {
2400 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
2401 purp);
2402 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2403 smartlist_free(args);
2404 return 0;
2407 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2408 smartlist_free(args);
2409 read_escaped_data(cp, len-(cp-body), 1, &desc);
2412 switch (router_load_single_router(desc, purpose, &msg)) {
2413 case -1:
2414 if (!msg) msg = "Could not parse descriptor";
2415 if (v0)
2416 send_control0_error(conn,ERR_SYNTAX,msg);
2417 else
2418 connection_printf_to_buf(conn, "554 %s\r\n", msg);
2419 break;
2420 case 0:
2421 if (!msg) msg = "Descriptor not added";
2422 if (v0)
2423 send_control_done2(conn,msg,0);
2424 else
2425 connection_printf_to_buf(conn, "251 %s\r\n",msg);
2426 break;
2427 case 1:
2428 send_control_done(conn);
2429 break;
2432 if (!v0)
2433 tor_free(desc);
2434 return 0;
2437 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
2438 * address of the named AP stream, and report success or failure. */
2439 static int
2440 handle_control_redirectstream(control_connection_t *conn, uint32_t len,
2441 const char *body)
2443 edge_connection_t *ap_conn = NULL;
2444 uint32_t conn_id;
2445 char *new_addr = NULL;
2446 uint16_t new_port = 0;
2447 if (STATE_IS_V0(conn->_base.state)) {
2448 if (len < 6) {
2449 send_control0_error(conn, ERR_SYNTAX,
2450 "redirectstream message too short");
2451 return 0;
2453 conn_id = ntohl(get_uint32(body));
2455 if (!(ap_conn = connection_get_by_global_id(conn_id))
2456 || ap_conn->_base.state != CONN_TYPE_AP
2457 || ap_conn->socks_request) {
2458 send_control0_error(conn, ERR_NO_STREAM,
2459 "No AP connection found with given ID");
2460 return 0;
2462 new_addr = tor_strdup(body+4);
2463 } else {
2464 smartlist_t *args;
2465 args = smartlist_create();
2466 smartlist_split_string(args, body, " ",
2467 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2468 if (smartlist_len(args) < 2)
2469 connection_printf_to_buf(conn,
2470 "512 Missing argument to REDIRECTSTREAM\r\n");
2471 else if (!(ap_conn = get_stream(smartlist_get(args, 0)))
2472 || !ap_conn->socks_request) {
2473 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2474 (char*)smartlist_get(args, 0));
2475 } else {
2476 int ok;
2477 if (smartlist_len(args) > 2) { /* they included a port too */
2478 new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
2479 10, 1, 65535, &ok, NULL);
2481 if (!ok) {
2482 connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
2483 (char*)smartlist_get(args, 2));
2484 } else {
2485 new_addr = tor_strdup(smartlist_get(args, 1));
2489 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2490 smartlist_free(args);
2491 if (!new_addr)
2492 return 0;
2495 strlcpy(ap_conn->socks_request->address, new_addr,
2496 sizeof(ap_conn->socks_request->address));
2497 if (new_port)
2498 ap_conn->socks_request->port = new_port;
2499 tor_free(new_addr);
2500 send_control_done(conn);
2501 return 0;
2504 /** Called when we get a CLOSESTREAM command; try to close the named stream
2505 * and report success or failure. */
2506 static int
2507 handle_control_closestream(control_connection_t *conn, uint32_t len,
2508 const char *body)
2510 edge_connection_t *ap_conn=NULL;
2511 uint8_t reason=0;
2513 if (STATE_IS_V0(conn->_base.state)) {
2514 uint32_t conn_id;
2515 if (len < 6) {
2516 send_control0_error(conn, ERR_SYNTAX, "closestream message too short");
2517 return 0;
2520 conn_id = ntohl(get_uint32(body));
2521 reason = *(uint8_t*)(body+4);
2523 if (!(ap_conn = connection_get_by_global_id(conn_id))
2524 || ap_conn->_base.state != CONN_TYPE_AP
2525 || ap_conn->socks_request) {
2526 send_control0_error(conn, ERR_NO_STREAM,
2527 "No AP connection found with given ID");
2528 return 0;
2530 } else {
2531 smartlist_t *args;
2532 int ok;
2533 args = smartlist_create();
2534 smartlist_split_string(args, body, " ",
2535 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2536 if (smartlist_len(args)<2)
2537 connection_printf_to_buf(conn,
2538 "512 Missing argument to CLOSESTREAM\r\n");
2539 else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
2540 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2541 (char*)smartlist_get(args, 0));
2542 else {
2543 reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
2544 &ok, NULL);
2545 if (!ok) {
2546 connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
2547 (char*)smartlist_get(args, 1));
2548 ap_conn = NULL;
2551 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2552 smartlist_free(args);
2553 if (!ap_conn)
2554 return 0;
2557 connection_mark_unattached_ap(ap_conn, reason);
2558 send_control_done(conn);
2559 return 0;
2562 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
2563 * and report success or failure. */
2564 static int
2565 handle_control_closecircuit(control_connection_t *conn, uint32_t len,
2566 const char *body)
2568 origin_circuit_t *circ = NULL;
2569 int safe = 0;
2571 if (STATE_IS_V0(conn->_base.state)) {
2572 uint32_t circ_id;
2573 if (len < 5) {
2574 send_control0_error(conn, ERR_SYNTAX, "closecircuit message too short");
2575 return 0;
2577 circ_id = ntohl(get_uint32(body));
2578 safe = (*(uint8_t*)(body+4)) & 1;
2580 if (!(circ = circuit_get_by_global_id(circ_id))) {
2581 send_control0_error(conn, ERR_NO_CIRC,
2582 "No circuit found with given ID");
2583 return 0;
2585 } else {
2586 smartlist_t *args;
2587 args = smartlist_create();
2588 smartlist_split_string(args, body, " ",
2589 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2590 if (smartlist_len(args)<1)
2591 connection_printf_to_buf(conn,
2592 "512 Missing argument to CLOSECIRCUIT\r\n");
2593 else if (!(circ=get_circ(smartlist_get(args, 0))))
2594 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2595 (char*)smartlist_get(args, 0));
2596 else {
2597 int i;
2598 for (i=1; i < smartlist_len(args); ++i) {
2599 if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
2600 safe = 1;
2601 else
2602 log_info(LD_CONTROL, "Skipping unknown option %s",
2603 (char*)smartlist_get(args,i));
2606 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2607 smartlist_free(args);
2608 if (!circ)
2609 return 0;
2612 if (!safe || !circ->p_streams) {
2613 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
2616 send_control_done(conn);
2617 return 0;
2620 /** Called when we get a USEFEATURE command: parse the feature list, and
2621 * set up the control_connection's options properly. */
2622 static int
2623 handle_control_usefeature(control_connection_t *conn,
2624 uint32_t len,
2625 const char *body)
2627 smartlist_t *args;
2628 int verbose_names = 0, extended_events = 0;
2629 int bad = 0;
2630 (void) len; /* body is nul-terminated; it's safe to ignore the length */
2631 tor_assert(! STATE_IS_V0(conn->_base.state));
2632 args = smartlist_create();
2633 smartlist_split_string(args, body, " ",
2634 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2635 SMARTLIST_FOREACH(args, const char *, arg, {
2636 if (!strcasecmp(arg, "VERBOSE_NAMES"))
2637 verbose_names = 1;
2638 else if (!strcasecmp(arg, "EXTENDED_EVENTS")) /* <- documented */
2639 extended_events = 1;
2640 else if (!strcasecmp(arg, "EXTENDED_FORMAT")) {
2641 /* remove this in 0.1.2.4; EXTENDED_FORMAT only ever worked for a
2642 * little while during 0.1.2.2-alpha-dev. */
2643 log_warn(LD_GENERAL,
2644 "EXTENDED_FORMAT is deprecated; use EXTENDED_EVENTS "
2645 "instead.");
2646 extended_events = 1;
2647 } else {
2648 connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
2649 arg);
2650 bad = 1;
2651 break;
2655 if (!bad) {
2656 if (verbose_names) {
2657 conn->use_long_names = 1;
2658 control_update_global_event_mask();
2660 if (extended_events)
2661 conn->use_extended_events = 1;
2662 send_control_done(conn);
2665 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2666 smartlist_free(args);
2667 return 0;
2670 /** Called when we get a v0 FRAGMENTHEADER or FRAGMENT command; try to append
2671 * the data to conn->incoming_cmd, setting conn->incoming_(type|len|cur_len)
2672 * as appropriate. If the command is malformed, drop it and all pending
2673 * fragments and report failure.
2675 static int
2676 handle_control_fragments(control_connection_t *conn, uint16_t command_type,
2677 uint32_t body_len, const char *body)
2679 if (command_type == CONTROL0_CMD_FRAGMENTHEADER) {
2680 if (conn->incoming_cmd) {
2681 log_warn(LD_CONTROL, "Dropping incomplete fragmented command; new "
2682 "fragmented command was begun.");
2683 tor_free(conn->incoming_cmd);
2685 if (body_len < 6) {
2686 send_control0_error(conn, ERR_SYNTAX, "FRAGMENTHEADER too short.");
2687 return 0;
2689 conn->incoming_cmd_type = ntohs(get_uint16(body));
2690 conn->incoming_cmd_len = ntohl(get_uint32(body+2));
2691 conn->incoming_cmd_cur_len = 0;
2692 conn->incoming_cmd = tor_malloc(conn->incoming_cmd_len);
2693 body += 6;
2694 body_len -= 6;
2695 } else if (command_type == CONTROL0_CMD_FRAGMENT) {
2696 if (!conn->incoming_cmd) {
2697 send_control0_error(conn, ERR_SYNTAX, "Out-of-place FRAGMENT");
2698 return 0;
2700 } else {
2701 tor_assert(0);
2704 if (conn->incoming_cmd_cur_len + body_len > conn->incoming_cmd_len) {
2705 tor_free(conn->incoming_cmd);
2706 send_control0_error(conn, ERR_SYNTAX,
2707 "Fragmented data exceeds declared length");
2708 return 0;
2710 memcpy(conn->incoming_cmd + conn->incoming_cmd_cur_len,
2711 body, body_len);
2712 conn->incoming_cmd_cur_len += body_len;
2713 return 0;
2716 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
2718 connection_control_finished_flushing(control_connection_t *conn)
2720 tor_assert(conn);
2722 connection_stop_writing(TO_CONN(conn));
2723 return 0;
2726 /** Called when <b>conn</b> has gotten its socket closed. */
2728 connection_control_reached_eof(control_connection_t *conn)
2730 tor_assert(conn);
2732 log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
2733 connection_mark_for_close(TO_CONN(conn));
2734 return 0;
2737 /** Called when data has arrived on a v1 control connection: Try to fetch
2738 * commands from conn->inbuf, and execute them.
2740 static int
2741 connection_control_process_inbuf_v1(control_connection_t *conn)
2743 size_t data_len;
2744 int cmd_len;
2745 char *args;
2747 tor_assert(conn);
2748 tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN_V1 ||
2749 conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V1);
2751 if (!conn->incoming_cmd) {
2752 conn->incoming_cmd = tor_malloc(1024);
2753 conn->incoming_cmd_len = 1024;
2754 conn->incoming_cmd_cur_len = 0;
2757 again:
2758 while (1) {
2759 size_t last_idx;
2760 int r;
2761 /* First, fetch a line. */
2762 do {
2763 data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
2764 r = fetch_from_buf_line(conn->_base.inbuf,
2765 conn->incoming_cmd+conn->incoming_cmd_cur_len,
2766 &data_len);
2767 if (r == 0)
2768 /* Line not all here yet. Wait. */
2769 return 0;
2770 else if (r == -1) {
2771 while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
2772 conn->incoming_cmd_len *= 2;
2773 conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
2774 conn->incoming_cmd_len);
2776 } while (r != 1);
2778 tor_assert(data_len);
2780 last_idx = conn->incoming_cmd_cur_len;
2781 conn->incoming_cmd_cur_len += data_len;
2783 /* We have appended a line to incoming_cmd. Is the command done? */
2784 if (last_idx == 0 && *conn->incoming_cmd != '+')
2785 /* One line command, didn't start with '+'. */
2786 break;
2787 if (last_idx+3 == conn->incoming_cmd_cur_len &&
2788 !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
2789 /* Just appended ".\r\n"; we're done. Remove it. */
2790 conn->incoming_cmd_cur_len -= 3;
2791 break;
2793 /* Otherwise, read another line. */
2795 data_len = conn->incoming_cmd_cur_len;
2796 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
2797 * recognize it.
2799 cmd_len = 0;
2800 while ((size_t)cmd_len < data_len
2801 && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
2802 ++cmd_len;
2804 data_len -= cmd_len;
2805 conn->incoming_cmd[cmd_len]='\0';
2806 args = conn->incoming_cmd+cmd_len+1;
2807 while (*args == ' ' || *args == '\t') {
2808 ++args;
2809 --data_len;
2812 if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
2813 connection_write_str_to_buf("250 closing connection\r\n", conn);
2814 connection_mark_for_close(TO_CONN(conn));
2815 return 0;
2818 if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V1 &&
2819 strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
2820 connection_write_str_to_buf("514 Authentication required.\r\n", conn);
2821 conn->incoming_cmd_cur_len = 0;
2822 goto again;
2825 if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
2826 if (handle_control_setconf(conn, data_len, args))
2827 return -1;
2828 } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
2829 if (handle_control_resetconf(conn, data_len, args))
2830 return -1;
2831 } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
2832 if (handle_control_getconf(conn, data_len, args))
2833 return -1;
2834 } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
2835 if (handle_control_setevents(conn, data_len, args))
2836 return -1;
2837 } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
2838 if (handle_control_authenticate(conn, data_len, args))
2839 return -1;
2840 } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
2841 if (handle_control_saveconf(conn, data_len, args))
2842 return -1;
2843 } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
2844 if (handle_control_signal(conn, data_len, args))
2845 return -1;
2846 } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
2847 if (handle_control_mapaddress(conn, data_len, args))
2848 return -1;
2849 } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
2850 if (handle_control_getinfo(conn, data_len, args))
2851 return -1;
2852 } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
2853 if (handle_control_extendcircuit(conn, data_len, args))
2854 return -1;
2855 } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
2856 if (handle_control_setpurpose(conn, 1, data_len, args))
2857 return -1;
2858 } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
2859 if (handle_control_setpurpose(conn, 0, data_len, args))
2860 return -1;
2861 } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
2862 if (handle_control_attachstream(conn, data_len, args))
2863 return -1;
2864 } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
2865 if (handle_control_postdescriptor(conn, data_len, args))
2866 return -1;
2867 } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
2868 if (handle_control_redirectstream(conn, data_len, args))
2869 return -1;
2870 } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
2871 if (handle_control_closestream(conn, data_len, args))
2872 return -1;
2873 } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
2874 if (handle_control_closecircuit(conn, data_len, args))
2875 return -1;
2876 } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
2877 if (handle_control_usefeature(conn, data_len, args))
2878 return -1;
2879 } else {
2880 connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
2881 conn->incoming_cmd);
2884 conn->incoming_cmd_cur_len = 0;
2885 goto again;
2888 /** Called when data has arrived on a v0 control connection: Try to fetch
2889 * commands from conn->inbuf, and execute them.
2891 static int
2892 connection_control_process_inbuf_v0(control_connection_t *conn)
2894 uint32_t body_len;
2895 uint16_t command_type;
2896 char *body=NULL;
2897 static int have_warned_about_v0_protocol = 0;
2899 again:
2900 /* Try to suck a control message from the buffer. */
2901 switch (fetch_from_buf_control0(conn->_base.inbuf, &body_len, &command_type,
2902 &body,
2903 conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V0))
2905 case -2:
2906 tor_free(body);
2907 log_info(LD_CONTROL,
2908 "Detected v1 control protocol on connection (fd %d)",
2909 conn->_base.s);
2910 conn->_base.state = CONTROL_CONN_STATE_NEEDAUTH_V1;
2911 return connection_control_process_inbuf_v1(conn);
2912 case -1:
2913 tor_free(body);
2914 log_warn(LD_CONTROL, "Error in control command. Failing.");
2915 return -1;
2916 case 0:
2917 /* Control command not all here yet. Wait. */
2918 return 0;
2919 case 1:
2920 /* We got a command. Process it. */
2921 break;
2922 default:
2923 tor_assert(0);
2926 if (!have_warned_about_v0_protocol) {
2927 log_warn(LD_CONTROL, "An application has connected to us using the "
2928 "version 0 control prototol, which has been deprecated since "
2929 "Tor 0.1.1.1-alpha. This protocol will not be supported by "
2930 "future versions of Tor; please use the v1 control protocol "
2931 "instead.");
2932 have_warned_about_v0_protocol = 1;
2935 /* We got a command. If we need authentication, only authentication
2936 * commands will be considered. */
2937 if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V0 &&
2938 command_type != CONTROL0_CMD_AUTHENTICATE) {
2939 log_info(LD_CONTROL, "Rejecting '%s' command; authentication needed.",
2940 control_cmd_to_string(command_type));
2941 send_control0_error(conn, ERR_UNAUTHORIZED, "Authentication required");
2942 tor_free(body);
2943 goto again;
2946 if (command_type == CONTROL0_CMD_FRAGMENTHEADER ||
2947 command_type == CONTROL0_CMD_FRAGMENT) {
2948 if (handle_control_fragments(conn, command_type, body_len, body))
2949 return -1;
2950 tor_free(body);
2951 if (conn->incoming_cmd_cur_len != conn->incoming_cmd_len)
2952 goto again;
2954 command_type = conn->incoming_cmd_type;
2955 body_len = conn->incoming_cmd_len;
2956 body = conn->incoming_cmd;
2957 conn->incoming_cmd = NULL;
2958 } else if (conn->incoming_cmd) {
2959 log_warn(LD_CONTROL, "Dropping incomplete fragmented command");
2960 tor_free(conn->incoming_cmd);
2963 /* Okay, we're willing to process the command. */
2964 switch (command_type)
2966 case CONTROL0_CMD_SETCONF:
2967 if (handle_control_setconf(conn, body_len, body))
2968 return -1;
2969 break;
2970 case CONTROL0_CMD_GETCONF:
2971 if (handle_control_getconf(conn, body_len, body))
2972 return -1;
2973 break;
2974 case CONTROL0_CMD_SETEVENTS:
2975 if (handle_control_setevents(conn, body_len, body))
2976 return -1;
2977 break;
2978 case CONTROL0_CMD_AUTHENTICATE:
2979 if (handle_control_authenticate(conn, body_len, body))
2980 return -1;
2981 break;
2982 case CONTROL0_CMD_SAVECONF:
2983 if (handle_control_saveconf(conn, body_len, body))
2984 return -1;
2985 break;
2986 case CONTROL0_CMD_SIGNAL:
2987 if (handle_control_signal(conn, body_len, body))
2988 return -1;
2989 break;
2990 case CONTROL0_CMD_MAPADDRESS:
2991 if (handle_control_mapaddress(conn, body_len, body))
2992 return -1;
2993 break;
2994 case CONTROL0_CMD_GETINFO:
2995 if (handle_control_getinfo(conn, body_len, body))
2996 return -1;
2997 break;
2998 case CONTROL0_CMD_EXTENDCIRCUIT:
2999 if (handle_control_extendcircuit(conn, body_len, body))
3000 return -1;
3001 break;
3002 case CONTROL0_CMD_ATTACHSTREAM:
3003 if (handle_control_attachstream(conn, body_len, body))
3004 return -1;
3005 break;
3006 case CONTROL0_CMD_POSTDESCRIPTOR:
3007 if (handle_control_postdescriptor(conn, body_len, body))
3008 return -1;
3009 break;
3010 case CONTROL0_CMD_REDIRECTSTREAM:
3011 if (handle_control_redirectstream(conn, body_len, body))
3012 return -1;
3013 break;
3014 case CONTROL0_CMD_CLOSESTREAM:
3015 if (handle_control_closestream(conn, body_len, body))
3016 return -1;
3017 break;
3018 case CONTROL0_CMD_CLOSECIRCUIT:
3019 if (handle_control_closecircuit(conn, body_len, body))
3020 return -1;
3021 break;
3022 case CONTROL0_CMD_ERROR:
3023 case CONTROL0_CMD_DONE:
3024 case CONTROL0_CMD_CONFVALUE:
3025 case CONTROL0_CMD_EVENT:
3026 case CONTROL0_CMD_INFOVALUE:
3027 log_warn(LD_CONTROL, "Received client-only '%s' command; ignoring.",
3028 control_cmd_to_string(command_type));
3029 send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
3030 "Command type only valid from server to tor client");
3031 break;
3032 case CONTROL0_CMD_FRAGMENTHEADER:
3033 case CONTROL0_CMD_FRAGMENT:
3034 log_warn(LD_CONTROL,
3035 "Recieved command fragment out of order; ignoring.");
3036 send_control0_error(conn, ERR_SYNTAX, "Bad fragmentation on command.");
3037 default:
3038 log_warn(LD_CONTROL, "Received unrecognized command type %d; ignoring.",
3039 (int)command_type);
3040 send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
3041 "Unrecognized command type");
3042 break;
3044 tor_free(body);
3045 goto again; /* There might be more data. */
3048 /** Called when <b>conn</b> has received more bytes on its inbuf.
3051 connection_control_process_inbuf(control_connection_t *conn)
3053 tor_assert(conn);
3055 if (STATE_IS_V0(conn->_base.state))
3056 return connection_control_process_inbuf_v0(conn);
3057 else
3058 return connection_control_process_inbuf_v1(conn);
3061 /** Convert a numeric reason for destroying a circuit into a string for a
3062 * CIRCUIT event. */
3063 static const char *
3064 circuit_end_reason_to_string(int reason)
3066 if (reason >= 0 && reason & END_CIRC_REASON_FLAG_REMOTE)
3067 reason &= ~END_CIRC_REASON_FLAG_REMOTE;
3068 switch (reason) {
3069 case END_CIRC_AT_ORIGIN:
3070 /* This shouldn't get passed here; it's a catch-all reason. */
3071 return "ORIGIN";
3072 case END_CIRC_REASON_NONE:
3073 /* This shouldn't get passed here; it's a catch-all reason. */
3074 return "NONE";
3075 case END_CIRC_REASON_TORPROTOCOL:
3076 return "TORPROTOCOL";
3077 case END_CIRC_REASON_INTERNAL:
3078 return "INTERNAL";
3079 case END_CIRC_REASON_REQUESTED:
3080 return "REQUESTED";
3081 case END_CIRC_REASON_HIBERNATING:
3082 return "HIBERNATING";
3083 case END_CIRC_REASON_RESOURCELIMIT:
3084 return "RESOURCELIMIT";
3085 case END_CIRC_REASON_CONNECTFAILED:
3086 return "CONNECTFAILED";
3087 case END_CIRC_REASON_OR_IDENTITY:
3088 return "OR_IDENTITY";
3089 case END_CIRC_REASON_OR_CONN_CLOSED:
3090 return "OR_CONN_CLOSED";
3091 case END_CIRC_REASON_FINISHED:
3092 return "FINISHED";
3093 case END_CIRC_REASON_TIMEOUT:
3094 return "TIMEOUT";
3095 case END_CIRC_REASON_DESTROYED:
3096 return "DESTROYED";
3097 case END_CIRC_REASON_NOPATH:
3098 return "NOPATH";
3099 case END_CIRC_REASON_NOSUCHSERVICE:
3100 return "NOSUCHSERVICE";
3101 default:
3102 log_warn(LD_BUG, "Unrecognized reason code %d", (int)reason);
3103 return NULL;
3107 /** Something has happened to circuit <b>circ</b>: tell any interested
3108 * control connections. */
3110 control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
3111 int reason_code)
3113 char *path=NULL, *msg;
3114 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
3115 return 0;
3116 tor_assert(circ);
3118 if (EVENT_IS_INTERESTING0(EVENT_CIRCUIT_STATUS) ||
3119 EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS))
3120 path = circuit_list_path(circ,0);
3121 if (EVENT_IS_INTERESTING0(EVENT_CIRCUIT_STATUS)) {
3122 size_t path_len = strlen(path);
3123 msg = tor_malloc(1+4+path_len+1); /* event, circid, path, NUL. */
3124 msg[0] = (uint8_t) tp;
3125 set_uint32(msg+1, htonl(circ->global_identifier));
3126 strlcpy(msg+5,path,path_len+1);
3128 send_control0_event(EVENT_CIRCUIT_STATUS, (uint32_t)(path_len+6), msg);
3129 tor_free(msg);
3131 if (EVENT_IS_INTERESTING1(EVENT_CIRCUIT_STATUS)) {
3132 const char *status;
3133 char reason_buf[64];
3134 int providing_reason=0;
3135 switch (tp)
3137 case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
3138 case CIRC_EVENT_BUILT: status = "BUILT"; break;
3139 case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
3140 case CIRC_EVENT_FAILED: status = "FAILED"; break;
3141 case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
3142 default:
3143 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3144 return 0;
3147 if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
3148 const char *reason_str = circuit_end_reason_to_string(reason_code);
3149 char *reason = NULL;
3150 providing_reason=1;
3151 if (!reason_str) {
3152 reason = tor_malloc(16);
3153 tor_snprintf(reason, 16, "UNKNOWN_%d", reason_code);
3154 reason_str = reason;
3156 if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
3157 tor_snprintf(reason_buf, sizeof(reason_buf),
3158 "REASON=DESTROYED REMOTE_REASON=%s", reason_str);
3159 } else {
3160 tor_snprintf(reason_buf, sizeof(reason_buf),
3161 "REASON=%s", reason_str);
3163 tor_free(reason);
3166 if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS)) {
3167 const char *sp = strlen(path) ? " " : "";
3168 if (providing_reason)
3169 send_control1_event_extended(EVENT_CIRCUIT_STATUS, SHORT_NAMES,
3170 "650 CIRC %lu %s%s%s@%s\r\n",
3171 (unsigned long)circ->global_identifier,
3172 status, sp, path, reason_buf);
3173 else
3174 send_control1_event_extended(EVENT_CIRCUIT_STATUS, SHORT_NAMES,
3175 "650 CIRC %lu %s%s%s\r\n",
3176 (unsigned long)circ->global_identifier,
3177 status, sp, path);
3179 if (EVENT_IS_INTERESTING1L(EVENT_CIRCUIT_STATUS)) {
3180 char *vpath = circuit_list_path_for_controller(circ);
3181 const char *sp = strlen(vpath) ? " " : "";
3182 if (providing_reason)
3183 send_control1_event_extended(EVENT_CIRCUIT_STATUS, LONG_NAMES,
3184 "650 CIRC %lu %s%s%s@%s\r\n",
3185 (unsigned long)circ->global_identifier,
3186 status, sp, vpath, reason_buf);
3187 else
3188 send_control1_event_extended(EVENT_CIRCUIT_STATUS, LONG_NAMES,
3189 "650 CIRC %lu %s%s%s\r\n",
3190 (unsigned long)circ->global_identifier,
3191 status, sp, vpath);
3192 tor_free(vpath);
3195 tor_free(path);
3197 return 0;
3200 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
3201 * <b>buf</b>, determine the address:port combination requested on
3202 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
3203 * failure. */
3204 static int
3205 write_stream_target_to_buf(edge_connection_t *conn, char *buf, size_t len)
3207 char buf2[256];
3208 if (conn->chosen_exit_name)
3209 if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
3210 return -1;
3211 if (tor_snprintf(buf, len, "%s%s%s:%d",
3212 conn->socks_request->address,
3213 conn->chosen_exit_name ? buf2 : "",
3214 !conn->chosen_exit_name &&
3215 connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
3216 conn->socks_request->port)<0)
3217 return -1;
3218 return 0;
3221 /** Convert the reason for ending a stream <b>reason</b> into the format used
3222 * in STREAM events. Return NULL if the reason is unrecognized. */
3223 static const char *
3224 stream_end_reason_to_string(int reason)
3226 reason &= END_STREAM_REASON_MASK;
3227 switch (reason) {
3228 case END_STREAM_REASON_MISC: return "MISC";
3229 case END_STREAM_REASON_RESOLVEFAILED: return "RESOLVEFAILED";
3230 case END_STREAM_REASON_CONNECTREFUSED: return "CONNECTREFUSED";
3231 case END_STREAM_REASON_EXITPOLICY: return "EXITPOLICY";
3232 case END_STREAM_REASON_DESTROY: return "DESTROY";
3233 case END_STREAM_REASON_DONE: return "DONE";
3234 case END_STREAM_REASON_TIMEOUT: return "TIMEOUT";
3235 case END_STREAM_REASON_HIBERNATING: return "HIBERNATING";
3236 case END_STREAM_REASON_INTERNAL: return "INTERNAL";
3237 case END_STREAM_REASON_RESOURCELIMIT: return "RESOURCELIMIT";
3238 case END_STREAM_REASON_CONNRESET: return "CONNRESET";
3239 case END_STREAM_REASON_TORPROTOCOL: return "TORPROTOCOL";
3240 case END_STREAM_REASON_NOTDIRECTORY: return "NOTDIRECTORY";
3242 case END_STREAM_REASON_CANT_ATTACH: return "CANT_ATTACH";
3243 case END_STREAM_REASON_NET_UNREACHABLE: return "NET_UNREACHABLE";
3244 case END_STREAM_REASON_SOCKSPROTOCOL: return "SOCKS_PROTOCOL";
3246 default: return NULL;
3250 /** Something has happened to the stream associated with AP connection
3251 * <b>conn</b>: tell any interested control connections. */
3253 control_event_stream_status(edge_connection_t *conn, stream_status_event_t tp,
3254 int reason_code)
3256 char *msg;
3257 size_t len;
3258 char buf[256];
3259 tor_assert(conn->socks_request);
3261 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
3262 return 0;
3264 if (tp == STREAM_EVENT_CLOSED &&
3265 (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
3266 return 0;
3268 write_stream_target_to_buf(conn, buf, sizeof(buf));
3269 if (EVENT_IS_INTERESTING0(EVENT_STREAM_STATUS)) {
3270 len = strlen(buf);
3271 msg = tor_malloc(5+len+1);
3272 msg[0] = (uint8_t) tp;
3273 set_uint32(msg+1, htonl(conn->global_identifier));
3274 strlcpy(msg+5, buf, len+1);
3276 send_control0_event(EVENT_STREAM_STATUS, (uint32_t)(5+len+1), msg);
3277 tor_free(msg);
3279 if (EVENT_IS_INTERESTING1(EVENT_STREAM_STATUS)) {
3280 char reason_buf[64];
3281 const char *status;
3282 circuit_t *circ;
3283 origin_circuit_t *origin_circ = NULL;
3284 reason_buf[0] = '\0';
3285 switch (tp)
3287 case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
3288 case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
3289 case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
3290 case STREAM_EVENT_FAILED: status = "FAILED"; break;
3291 case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
3292 case STREAM_EVENT_NEW: status = "NEW"; break;
3293 case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
3294 case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
3295 case STREAM_EVENT_REMAP: status = "REMAP"; break;
3296 default:
3297 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3298 return 0;
3300 if (reason_code && (tp == STREAM_EVENT_FAILED ||
3301 tp == STREAM_EVENT_CLOSED ||
3302 tp == STREAM_EVENT_FAILED_RETRIABLE)) {
3303 const char *reason_str = stream_end_reason_to_string(reason_code);
3304 char *r = NULL;
3305 if (!reason_str) {
3306 r = tor_malloc(16);
3307 tor_snprintf(r, 16, "UNKNOWN_%d", reason_code);
3308 reason_str = r;
3310 if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
3311 tor_snprintf(reason_buf, sizeof(reason_buf),
3312 "REASON=END REMOTE_REASON=%s", reason_str);
3313 else
3314 tor_snprintf(reason_buf, sizeof(reason_buf),
3315 "REASON=%s", reason_str);
3316 tor_free(r);
3317 } else if (reason_code && tp == STREAM_EVENT_REMAP) {
3318 switch (reason_code) {
3319 case REMAP_STREAM_SOURCE_CACHE:
3320 strlcpy(reason_buf, "SOURCE=CACHE", sizeof(reason_buf));
3321 break;
3322 case REMAP_STREAM_SOURCE_EXIT:
3323 strlcpy(reason_buf, "SOURCE=EXIT", sizeof(reason_buf));
3324 break;
3325 default:
3326 tor_snprintf(reason_buf, sizeof(reason_buf), "REASON=UNKNOWN_%d",
3327 reason_code);
3328 break;
3331 circ = circuit_get_by_edge_conn(conn);
3332 if (circ && CIRCUIT_IS_ORIGIN(circ))
3333 origin_circ = TO_ORIGIN_CIRCUIT(circ);
3334 send_control1_event_extended(EVENT_STREAM_STATUS, ALL_NAMES,
3335 "650 STREAM %lu %s %lu %s@%s\r\n",
3336 (unsigned long)conn->global_identifier, status,
3337 origin_circ?
3338 (unsigned long)origin_circ->global_identifier : 0ul,
3339 buf, reason_buf);
3340 /* XXX need to specify its intended exit, etc? */
3342 return 0;
3345 /** Figure out the best name for the target router of an OR connection
3346 * <b>conn</b>, and write it into the <b>len</b>-character buffer
3347 * <b>name</b>. Use verbose names if <b>long_names</b> is set. */
3348 static void
3349 orconn_target_get_name(int long_names,
3350 char *name, size_t len, or_connection_t *conn)
3352 if (! long_names) {
3353 if (conn->nickname)
3354 strlcpy(name, conn->nickname, len);
3355 else
3356 tor_snprintf(name, len, "%s:%d",
3357 conn->_base.address, conn->_base.port);
3358 } else {
3359 routerinfo_t *ri = router_get_by_digest(conn->identity_digest);
3360 if (ri) {
3361 tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
3362 router_get_verbose_nickname(name, ri);
3363 } else if (! tor_digest_is_zero(conn->identity_digest)) {
3364 name[0] = '$';
3365 base16_encode(name+1, len-1, conn->identity_digest,
3366 DIGEST_LEN);
3367 } else {
3368 tor_snprintf(name, len, "%s:%d",
3369 conn->_base.address, conn->_base.port);
3374 /** Convert a TOR_TLS_* error code into an END_OR_CONN_* reason. */
3376 control_tls_error_to_reason(int e)
3378 switch (e) {
3379 case TOR_TLS_ERROR_IO:
3380 return END_OR_CONN_REASON_TLS_IO_ERROR;
3381 case TOR_TLS_ERROR_CONNREFUSED:
3382 return END_OR_CONN_REASON_TCP_REFUSED;
3383 case TOR_TLS_ERROR_CONNRESET:
3384 return END_OR_CONN_REASON_TLS_CONNRESET;
3385 case TOR_TLS_ERROR_NO_ROUTE:
3386 return END_OR_CONN_REASON_TLS_NO_ROUTE;
3387 case TOR_TLS_ERROR_TIMEOUT:
3388 return END_OR_CONN_REASON_TLS_TIMEOUT;
3389 case TOR_TLS_WANTREAD:
3390 case TOR_TLS_WANTWRITE:
3391 case TOR_TLS_CLOSE:
3392 case TOR_TLS_DONE:
3393 return END_OR_CONN_REASON_DONE;
3394 default:
3395 return END_OR_CONN_REASON_TLS_MISC;
3399 /** Convert the reason for ending an OR connection <b>r</b> into the format
3400 * used in ORCONN events. Return NULL if the reason is unrecognized. */
3401 static const char *
3402 or_conn_end_reason_to_string(int r)
3404 switch (r) {
3405 case END_OR_CONN_REASON_DONE:
3406 return "REASON=DONE";
3407 case END_OR_CONN_REASON_TCP_REFUSED:
3408 return "REASON=CONNECTREFUSED";
3409 case END_OR_CONN_REASON_OR_IDENTITY:
3410 return "REASON=IDENTITY";
3411 case END_OR_CONN_REASON_TLS_CONNRESET:
3412 return "REASON=CONNECTRESET";
3413 case END_OR_CONN_REASON_TLS_TIMEOUT:
3414 return "REASON=TIMEOUT";
3415 case END_OR_CONN_REASON_TLS_NO_ROUTE:
3416 return "REASON=NOROUTE";
3417 case END_OR_CONN_REASON_TLS_IO_ERROR:
3418 return "REASON=IOERROR";
3419 case END_OR_CONN_REASON_TLS_MISC:
3420 return "REASON=MISC";
3421 case 0:
3422 return "";
3423 default:
3424 log_warn(LD_BUG, "Unrecognized or_conn reason code %d", r);
3425 return "REASON=BOGUS";
3429 /** Called when the status of an OR connection <b>conn</b> changes: tell any
3430 * interested control connections. <b>tp</b> is the new status for the
3431 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
3432 * may be the reason why.
3435 control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
3436 int reason)
3438 char buf[HEX_DIGEST_LEN+3]; /* status, dollar, identity, NUL */
3439 size_t len;
3440 int ncircs = 0;
3442 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
3443 return 0;
3445 if (EVENT_IS_INTERESTING0(EVENT_OR_CONN_STATUS)) {
3446 buf[0] = (uint8_t)tp;
3447 strlcpy(buf+1,conn->nickname ? conn->nickname : "",sizeof(buf)-1);
3448 len = strlen(buf+1);
3449 send_control0_event(EVENT_OR_CONN_STATUS, (uint32_t)(len+1), buf);
3451 if (EVENT_IS_INTERESTING1(EVENT_OR_CONN_STATUS)) {
3452 const char *status;
3453 char name[128];
3454 char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
3455 switch (tp)
3457 case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
3458 case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
3459 case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
3460 case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
3461 case OR_CONN_EVENT_NEW: status = "NEW"; break;
3462 default:
3463 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3464 return 0;
3466 ncircs = circuit_count_pending_on_or_conn(conn);
3467 ncircs += conn->n_circuits;
3468 if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
3469 tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
3470 reason ? " " : "", ncircs);
3473 if (EVENT_IS_INTERESTING1S(EVENT_OR_CONN_STATUS)) {
3474 orconn_target_get_name(0, name, sizeof(name), conn);
3475 send_control1_event_extended(EVENT_OR_CONN_STATUS, SHORT_NAMES,
3476 "650 ORCONN %s %s@%s%s\r\n",
3477 name, status,
3478 or_conn_end_reason_to_string(reason), ncircs_buf);
3480 if (EVENT_IS_INTERESTING1L(EVENT_OR_CONN_STATUS)) {
3481 orconn_target_get_name(1, name, sizeof(name), conn);
3482 send_control1_event_extended(EVENT_OR_CONN_STATUS, LONG_NAMES,
3483 "650 ORCONN %s %s@%s%s\r\n",
3484 name, status,
3485 or_conn_end_reason_to_string(reason), ncircs_buf);
3488 return 0;
3491 /** A second or more has elapsed: tell any interested control
3492 * connections how much bandwidth streams have used. */
3494 control_event_stream_bandwidth_used(void)
3496 connection_t **carray;
3497 edge_connection_t *conn;
3498 int n, i;
3500 if (EVENT_IS_INTERESTING1(EVENT_STREAM_BANDWIDTH_USED)) {
3502 get_connection_array(&carray, &n);
3504 for (i = 0; i < n; ++i) {
3505 if (carray[i]->type != CONN_TYPE_AP)
3506 continue;
3507 conn = TO_EDGE_CONN(carray[i]);
3508 if (!conn->n_read && !conn->n_written)
3509 continue;
3511 send_control1_event(EVENT_STREAM_BANDWIDTH_USED, ALL_NAMES,
3512 "650 STREAM_BW %lu %lu %lu\r\n",
3513 (unsigned long)conn->global_identifier,
3514 (unsigned long)conn->n_read,
3515 (unsigned long)conn->n_written);
3517 conn->n_written = conn->n_read = 0;
3521 return 0;
3524 /** A second or more has elapsed: tell any interested control
3525 * connections how much bandwidth we used. */
3527 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
3529 char buf[8];
3531 if (EVENT_IS_INTERESTING0(EVENT_BANDWIDTH_USED)) {
3532 set_uint32(buf, htonl(n_read));
3533 set_uint32(buf+4, htonl(n_written));
3534 send_control0_event(EVENT_BANDWIDTH_USED, 8, buf);
3536 if (EVENT_IS_INTERESTING1(EVENT_BANDWIDTH_USED)) {
3537 send_control1_event(EVENT_BANDWIDTH_USED, ALL_NAMES,
3538 "650 BW %lu %lu\r\n",
3539 (unsigned long)n_read,
3540 (unsigned long)n_written);
3543 return 0;
3546 /** Called when we are sending a log message to the controllers: suspend
3547 * sending further log messages to the controllers until we're done. Used by
3548 * CONN_LOG_PROTECT. */
3549 void
3550 disable_control_logging(void)
3552 ++disable_log_messages;
3555 /** We're done sending a log message to the controllers: re-enable controller
3556 * logging. Used by CONN_LOG_PROTECT. */
3557 void
3558 enable_control_logging(void)
3560 if (--disable_log_messages < 0)
3561 tor_assert(0);
3564 /** We got a log message: tell any interested control connections. */
3565 void
3566 control_event_logmsg(int severity, uint32_t domain, const char *msg)
3568 int oldlog, event;
3570 if (disable_log_messages)
3571 return;
3573 if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
3574 severity <= LOG_NOTICE) {
3575 char *esc = esc_for_log(msg);
3576 ++disable_log_messages;
3577 control_event_general_status(severity, "BUG REASON=\"%s\"", esc);
3578 --disable_log_messages;
3579 tor_free(esc);
3582 oldlog = EVENT_IS_INTERESTING0(EVENT_LOG_OBSOLETE) &&
3583 (severity == LOG_NOTICE || severity == LOG_WARN || severity == LOG_ERR);
3584 event = log_severity_to_event(severity);
3586 if (event<0 || !EVENT_IS_INTERESTING0(event))
3587 event = 0;
3589 if (oldlog || event) {
3590 size_t len = strlen(msg);
3591 ++disable_log_messages;
3592 if (event)
3593 send_control0_event(event, (uint32_t)(len+1), msg);
3594 if (oldlog)
3595 send_control0_event(EVENT_LOG_OBSOLETE, (uint32_t)(len+1), msg);
3596 --disable_log_messages;
3599 event = log_severity_to_event(severity);
3600 if (event >= 0 && EVENT_IS_INTERESTING1(event)) {
3601 char *b = NULL;
3602 const char *s;
3603 if (strchr(msg, '\n')) {
3604 char *cp;
3605 b = tor_strdup(msg);
3606 for (cp = b; *cp; ++cp)
3607 if (*cp == '\r' || *cp == '\n')
3608 *cp = ' ';
3610 switch (severity) {
3611 case LOG_DEBUG: s = "DEBUG"; break;
3612 case LOG_INFO: s = "INFO"; break;
3613 case LOG_NOTICE: s = "NOTICE"; break;
3614 case LOG_WARN: s = "WARN"; break;
3615 case LOG_ERR: s = "ERR"; break;
3616 default: s = "UnknownLogSeverity"; break;
3618 ++disable_log_messages;
3619 send_control1_event(event, ALL_NAMES, "650 %s %s\r\n", s, b?b:msg);
3620 --disable_log_messages;
3621 tor_free(b);
3625 /** Called whenever we receive new router descriptors: tell any
3626 * interested control connections. <b>routers</b> is a list of
3627 * DIGEST_LEN-byte identity digests.
3630 control_event_descriptors_changed(smartlist_t *routers)
3632 size_t len;
3633 char *msg;
3634 smartlist_t *identities = NULL;
3635 char buf[HEX_DIGEST_LEN+1];
3637 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
3638 return 0;
3639 if (EVENT_IS_INTERESTING0(EVENT_NEW_DESC) ||
3640 EVENT_IS_INTERESTING1S(EVENT_NEW_DESC)) {
3641 identities = smartlist_create();
3642 SMARTLIST_FOREACH(routers, routerinfo_t *, r,
3644 base16_encode(buf,sizeof(buf),r->cache_info.identity_digest,DIGEST_LEN);
3645 smartlist_add(identities, tor_strdup(buf));
3648 if (EVENT_IS_INTERESTING0(EVENT_NEW_DESC)) {
3649 msg = smartlist_join_strings(identities, ",", 0, &len);
3650 send_control0_event(EVENT_NEW_DESC, len+1, msg);
3651 tor_free(msg);
3653 if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC)) {
3654 char *ids = smartlist_join_strings(identities, " ", 0, &len);
3655 size_t len = strlen(ids)+32;
3656 msg = tor_malloc(len);
3657 tor_snprintf(msg, len, "650 NEWDESC %s\r\n", ids);
3658 send_control1_event_string(EVENT_NEW_DESC, SHORT_NAMES|ALL_FORMATS, msg);
3659 tor_free(ids);
3660 tor_free(msg);
3662 if (EVENT_IS_INTERESTING1L(EVENT_NEW_DESC)) {
3663 smartlist_t *names = smartlist_create();
3664 char *ids;
3665 size_t len;
3666 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
3667 char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
3668 router_get_verbose_nickname(b, ri);
3669 smartlist_add(names, b);
3671 ids = smartlist_join_strings(names, " ", 0, &len);
3672 len = strlen(ids)+32;
3673 msg = tor_malloc(len);
3674 tor_snprintf(msg, len, "650 NEWDESC %s\r\n", ids);
3675 send_control1_event_string(EVENT_NEW_DESC, LONG_NAMES|ALL_FORMATS, msg);
3676 tor_free(ids);
3677 tor_free(msg);
3678 SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
3679 smartlist_free(names);
3681 if (identities) {
3682 SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
3683 smartlist_free(identities);
3685 return 0;
3688 /** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
3689 * <b>expires</b> values less than 3 are special; see connection_edge.c. */
3691 control_event_address_mapped(const char *from, const char *to, time_t expires)
3693 if (!EVENT_IS_INTERESTING1(EVENT_ADDRMAP))
3694 return 0;
3696 if (expires < 3)
3697 send_control1_event(EVENT_ADDRMAP, ALL_NAMES,
3698 "650 ADDRMAP %s %s NEVER\r\n", from, to);
3699 else {
3700 char buf[ISO_TIME_LEN+1];
3701 format_local_iso_time(buf,expires);
3702 send_control1_event(EVENT_ADDRMAP, ALL_NAMES,
3703 "650 ADDRMAP %s %s \"%s\"\r\n",
3704 from, to, buf);
3707 return 0;
3710 /** The authoritative dirserver has received a new descriptor that
3711 * has passed basic syntax checks and is properly self-signed.
3713 * Notify any interested party of the new descriptor and what has
3714 * been done with it, and also optionally give an explanation/reason. */
3716 control_event_or_authdir_new_descriptor(const char *action,
3717 const char *descriptor,
3718 const char *msg)
3720 char firstline[1024];
3721 char *buf;
3722 int totallen;
3723 char *esc = NULL;
3724 size_t esclen;
3726 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
3727 return 0;
3729 tor_snprintf(firstline, sizeof(firstline),
3730 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
3731 action,
3732 msg ? msg : "");
3734 /* Escape the server descriptor properly */
3735 esclen = write_escaped_data(descriptor, strlen(descriptor), 1, &esc);
3737 totallen = strlen(firstline) + esclen + 1;
3738 buf = tor_malloc(totallen);
3739 strlcpy(buf, firstline, totallen);
3740 strlcpy(buf+strlen(firstline), esc, totallen);
3741 send_control1_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_NAMES|ALL_FORMATS,
3742 buf);
3744 tor_free(esc);
3745 tor_free(buf);
3747 return 0;
3750 /** Called when the local_routerstatus_ts <b>statuses</b> have changed: sends
3751 * an NS event to any controller that cares. */
3753 control_event_networkstatus_changed(smartlist_t *statuses)
3755 smartlist_t *strs;
3756 char *s;
3757 if (!EVENT_IS_INTERESTING(EVENT_NS) || !smartlist_len(statuses))
3758 return 0;
3760 strs = smartlist_create();
3761 smartlist_add(strs, tor_strdup("650+NS\r\n"));
3762 SMARTLIST_FOREACH(statuses, local_routerstatus_t *, rs,
3764 s = networkstatus_getinfo_helper_single(&rs->status);
3765 if (!s) continue;
3766 smartlist_add(strs, s);
3768 smartlist_add(strs, tor_strdup("\r\n.\r\n"));
3770 s = smartlist_join_strings(strs, "", 0, NULL);
3771 SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
3772 smartlist_free(strs);
3773 send_control1_event_string(EVENT_NS, ALL_NAMES|ALL_FORMATS, s);
3774 tor_free(s);
3775 return 0;
3778 /** Called when a single local_routerstatus_t has changed: Sends an NS event
3779 * to any countroller that cares. */
3781 control_event_networkstatus_changed_single(local_routerstatus_t *rs)
3783 smartlist_t *statuses;
3784 int r;
3786 if (!EVENT_IS_INTERESTING(EVENT_NS))
3787 return 0;
3789 statuses = smartlist_create();
3790 smartlist_add(statuses, rs);
3791 r = control_event_networkstatus_changed(statuses);
3792 smartlist_free(statuses);
3793 return r;
3796 /** Our own router descriptor has changed; tell any controllers that care.
3799 control_event_my_descriptor_changed(void)
3801 send_control1_event(EVENT_DESCCHANGED, ALL_NAMES, "650 DESCCHANGED\r\n");
3802 return 0;
3805 /** Helper: sends a status event where <b>type</b> is one of
3806 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
3807 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
3808 * string corresponding to <b>args</b>. */
3809 static int
3810 control_event_status(int type, int severity, const char *format, va_list args)
3812 char format_buf[160];
3813 const char *status, *sev;
3815 switch (type) {
3816 case EVENT_STATUS_GENERAL:
3817 status = "STATUS_GENERAL";
3818 break;
3819 case EVENT_STATUS_CLIENT:
3820 status = "STATUS_CLIENT";
3821 break;
3822 case EVENT_STATUS_SERVER:
3823 status = "STATUS_SEVER";
3824 break;
3825 default:
3826 log_warn(LD_BUG, "Unrecognized status type %d", type);
3827 return -1;
3829 switch (severity) {
3830 case LOG_NOTICE:
3831 sev = "NOTICE";
3832 break;
3833 case LOG_WARN:
3834 sev = "WARN";
3835 break;
3836 case LOG_ERR:
3837 sev = "ERR";
3838 break;
3839 default:
3840 log_warn(LD_BUG, "Unrecognized status severity %d", severity);
3841 return -1;
3843 if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s %s\r\n",
3844 status, sev, format)<0) {
3845 log_warn(LD_BUG, "Format string too long.");
3846 return -1;
3849 send_control1_event_impl(type, ALL_NAMES|ALL_FORMATS, 0, format_buf, args);
3850 return 0;
3853 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
3854 * by formatting the arguments using the printf-style <b>format</b>. */
3856 control_event_general_status(int severity, const char *format, ...)
3858 va_list ap;
3859 int r;
3860 if (!EVENT_IS_INTERESTING1(EVENT_STATUS_GENERAL))
3861 return 0;
3863 va_start(ap, format);
3864 r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
3865 va_end(ap);
3866 return r;
3869 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
3870 * by formatting the arguments using the printf-style <b>format</b>. */
3872 control_event_client_status(int severity, const char *format, ...)
3874 va_list ap;
3875 int r;
3876 if (!EVENT_IS_INTERESTING1(EVENT_STATUS_CLIENT))
3877 return 0;
3879 va_start(ap, format);
3880 r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
3881 va_end(ap);
3882 return r;
3885 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
3886 * by formatting the arguments using the printf-style <b>format</b>. */
3888 control_event_server_status(int severity, const char *format, ...)
3890 va_list ap;
3891 int r;
3892 if (!EVENT_IS_INTERESTING1(EVENT_STATUS_SERVER))
3893 return 0;
3895 va_start(ap, format);
3896 r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
3897 va_end(ap);
3898 return r;
3901 /** Called when the status of an entry guard with the given <b>nickname</b>
3902 * and identity <b>digest</b> has changed to <b>status</b>: tells any
3903 * controllers that care. */
3905 control_event_guard(const char *nickname, const char *digest,
3906 const char *status)
3908 char hbuf[HEX_DIGEST_LEN+1];
3909 base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
3910 if (!EVENT_IS_INTERESTING1(EVENT_GUARD))
3911 return 0;
3913 if (EVENT_IS_INTERESTING1L(EVENT_GUARD)) {
3914 char buf[MAX_VERBOSE_NICKNAME_LEN+1];
3915 routerinfo_t *ri = router_get_by_digest(digest);
3916 if (ri) {
3917 router_get_verbose_nickname(buf, ri);
3918 } else {
3919 tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
3921 send_control1_event(EVENT_GUARD, LONG_NAMES,
3922 "650 GUARD ENTRY %s %s\r\n", buf, status);
3924 if (EVENT_IS_INTERESTING1S(EVENT_GUARD)) {
3925 send_control1_event(EVENT_GUARD, SHORT_NAMES,
3926 "650 GUARD ENTRY $%s %s\r\n", hbuf, status);
3928 return 0;
3931 /** Choose a random authentication cookie and write it to disk.
3932 * Anybody who can read the cookie from disk will be considered
3933 * authorized to use the control connection. */
3935 init_cookie_authentication(int enabled)
3937 char fname[512];
3939 if (!enabled) {
3940 authentication_cookie_is_set = 0;
3941 return 0;
3944 tor_snprintf(fname, sizeof(fname), "%s/control_auth_cookie",
3945 get_options()->DataDirectory);
3946 crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
3947 authentication_cookie_is_set = 1;
3948 if (write_bytes_to_file(fname, authentication_cookie,
3949 AUTHENTICATION_COOKIE_LEN, 1)) {
3950 log_warn(LD_FS,"Error writing authentication cookie.");
3951 return -1;
3954 return 0;