send the newconsensus event if the controller has asked for newconsensus
[tor/rransom.git] / src / or / control.c
blob5600bdcfd91cdf5a8cff84a5afd3c532101d144f
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2008, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file control.c
7 * \brief Implementation for Tor's control-socket interface.
8 * See doc/spec/control-spec.txt for full details on protocol.
9 **/
11 #define CONTROL_PRIVATE
13 #include "or.h"
15 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
16 * finished authentication and is accepting commands. */
17 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
19 /* Recognized asynchronous event types. It's okay to expand this list
20 * because it is used both as a list of v0 event types, and as indices
21 * into the bitfield to determine which controllers want which events.
23 #define _EVENT_MIN 0x0001
24 #define EVENT_CIRCUIT_STATUS 0x0001
25 #define EVENT_STREAM_STATUS 0x0002
26 #define EVENT_OR_CONN_STATUS 0x0003
27 #define EVENT_BANDWIDTH_USED 0x0004
28 #define EVENT_LOG_OBSOLETE 0x0005 /* Can reclaim this. */
29 #define EVENT_NEW_DESC 0x0006
30 #define EVENT_DEBUG_MSG 0x0007
31 #define EVENT_INFO_MSG 0x0008
32 #define EVENT_NOTICE_MSG 0x0009
33 #define EVENT_WARN_MSG 0x000A
34 #define EVENT_ERR_MSG 0x000B
35 #define EVENT_ADDRMAP 0x000C
36 // #define EVENT_AUTHDIR_NEWDESCS 0x000D
37 #define EVENT_DESCCHANGED 0x000E
38 // #define EVENT_NS 0x000F
39 #define EVENT_STATUS_CLIENT 0x0010
40 #define EVENT_STATUS_SERVER 0x0011
41 #define EVENT_STATUS_GENERAL 0x0012
42 #define EVENT_GUARD 0x0013
43 #define EVENT_STREAM_BANDWIDTH_USED 0x0014
44 #define EVENT_CLIENTS_SEEN 0x0015
45 #define EVENT_NEWCONSENSUS 0x0016
46 #define _EVENT_MAX 0x0016
47 /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
49 /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
50 * connection is interested in events of type <b>e</b>. We use this
51 * so that we can decide to skip generating event messages that nobody
52 * has interest in without having to walk over the global connection
53 * list to find out.
54 **/
55 typedef uint32_t event_mask_t;
57 /** An event mask of all the events that controller with the LONG_NAMES option
58 * set is interested in receiving. */
59 static event_mask_t global_event_mask1long = 0;
61 /** An event mask of all the events that controller with the SHORT_NAMES option
62 * set is interested in receiving. */
63 static event_mask_t global_event_mask1short = 0;
65 /** True iff we have disabled log messages from being sent to the controller */
66 static int disable_log_messages = 0;
68 /** Macro: true if any control connection is interested in events of type
69 * <b>e</b>. */
70 #define EVENT_IS_INTERESTING(e) \
71 ((global_event_mask1long|global_event_mask1short) & (1<<(e)))
72 /** Macro: true if any control connection with the LONG_NAMES option is
73 * interested in events of type <b>e</b>. */
74 #define EVENT_IS_INTERESTING1L(e) (global_event_mask1long & (1<<(e)))
75 /** Macro: true if any control connection with the SHORT_NAMES option is
76 * interested in events of type <b>e</b>. */
77 #define EVENT_IS_INTERESTING1S(e) (global_event_mask1short & (1<<(e)))
79 /** If we're using cookie-type authentication, how long should our cookies be?
81 #define AUTHENTICATION_COOKIE_LEN 32
83 /** If true, we've set authentication_cookie to a secret code and
84 * stored it to disk. */
85 static int authentication_cookie_is_set = 0;
86 /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
87 * and which we're using to authenticate controllers. (If the controller can
88 * read it off disk, it has permission to connect. */
89 static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
91 /** A sufficiently large size to record the last bootstrap phase string. */
92 #define BOOTSTRAP_MSG_LEN 1024
94 /** What was the last bootstrap phase message we sent? We keep track
95 * of this so we can respond to getinfo status/bootstrap-phase queries. */
96 static char last_sent_bootstrap_message[BOOTSTRAP_MSG_LEN];
98 /** Flag for event_format_t. Indicates that we should use the old
99 * name format of nickname|hexdigest
101 #define SHORT_NAMES 1
102 /** Flag for event_format_t. Indicates that we should use the new
103 * name format of $hexdigest[=~]nickname
105 #define LONG_NAMES 2
106 #define ALL_NAMES (SHORT_NAMES|LONG_NAMES)
107 /** Flag for event_format_t. Indicates that we should use the new event
108 * format where extra event fields are allowed using a NAME=VAL format. */
109 #define EXTENDED_FORMAT 4
110 /** Flag for event_format_t. Indicates that we are using the old event format
111 * where extra fields aren't allowed. */
112 #define NONEXTENDED_FORMAT 8
113 #define ALL_FORMATS (EXTENDED_FORMAT|NONEXTENDED_FORMAT)
115 /** Bit field of flags to select how to format a controller event. Recognized
116 * flags are SHORT_NAMES, LONG_NAMES, EXTENDED_FORMAT, NONEXTENDED_FORMAT. */
117 typedef int event_format_t;
119 static void connection_printf_to_buf(control_connection_t *conn,
120 const char *format, ...)
121 CHECK_PRINTF(2,3);
122 static void send_control_done(control_connection_t *conn);
123 static void send_control_event(uint16_t event, event_format_t which,
124 const char *format, ...)
125 CHECK_PRINTF(3,4);
126 static void send_control_event_extended(uint16_t event, event_format_t which,
127 const char *format, ...)
128 CHECK_PRINTF(3,4);
129 static int handle_control_setconf(control_connection_t *conn, uint32_t len,
130 char *body);
131 static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
132 char *body);
133 static int handle_control_getconf(control_connection_t *conn, uint32_t len,
134 const char *body);
135 static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
136 const char *body);
137 static int handle_control_setevents(control_connection_t *conn, uint32_t len,
138 const char *body);
139 static int handle_control_authenticate(control_connection_t *conn,
140 uint32_t len,
141 const char *body);
142 static int handle_control_saveconf(control_connection_t *conn, uint32_t len,
143 const char *body);
144 static int handle_control_signal(control_connection_t *conn, uint32_t len,
145 const char *body);
146 static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
147 const char *body);
148 static char *list_getinfo_options(void);
149 static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
150 const char *body);
151 static int handle_control_extendcircuit(control_connection_t *conn,
152 uint32_t len,
153 const char *body);
154 static int handle_control_setcircuitpurpose(control_connection_t *conn,
155 uint32_t len, const char *body);
156 static int handle_control_attachstream(control_connection_t *conn,
157 uint32_t len,
158 const char *body);
159 static int handle_control_postdescriptor(control_connection_t *conn,
160 uint32_t len,
161 const char *body);
162 static int handle_control_redirectstream(control_connection_t *conn,
163 uint32_t len,
164 const char *body);
165 static int handle_control_closestream(control_connection_t *conn, uint32_t len,
166 const char *body);
167 static int handle_control_closecircuit(control_connection_t *conn,
168 uint32_t len,
169 const char *body);
170 static int handle_control_resolve(control_connection_t *conn, uint32_t len,
171 const char *body);
172 static int handle_control_usefeature(control_connection_t *conn,
173 uint32_t len,
174 const char *body);
175 static int write_stream_target_to_buf(edge_connection_t *conn, char *buf,
176 size_t len);
177 static void orconn_target_get_name(int long_names, char *buf, size_t len,
178 or_connection_t *conn);
179 static char *get_cookie_file(void);
181 /** Given a control event code for a message event, return the corresponding
182 * log severity. */
183 static INLINE int
184 event_to_log_severity(int event)
186 switch (event) {
187 case EVENT_DEBUG_MSG: return LOG_DEBUG;
188 case EVENT_INFO_MSG: return LOG_INFO;
189 case EVENT_NOTICE_MSG: return LOG_NOTICE;
190 case EVENT_WARN_MSG: return LOG_WARN;
191 case EVENT_ERR_MSG: return LOG_ERR;
192 default: return -1;
196 /** Given a log severity, return the corresponding control event code. */
197 static INLINE int
198 log_severity_to_event(int severity)
200 switch (severity) {
201 case LOG_DEBUG: return EVENT_DEBUG_MSG;
202 case LOG_INFO: return EVENT_INFO_MSG;
203 case LOG_NOTICE: return EVENT_NOTICE_MSG;
204 case LOG_WARN: return EVENT_WARN_MSG;
205 case LOG_ERR: return EVENT_ERR_MSG;
206 default: return -1;
210 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
211 * connection's event_mask field. */
212 void
213 control_update_global_event_mask(void)
215 smartlist_t *conns = get_connection_array();
216 event_mask_t old_mask, new_mask;
217 old_mask = global_event_mask1short;
218 old_mask |= global_event_mask1long;
220 global_event_mask1short = 0;
221 global_event_mask1long = 0;
222 SMARTLIST_FOREACH(conns, connection_t *, _conn,
224 if (_conn->type == CONN_TYPE_CONTROL &&
225 STATE_IS_OPEN(_conn->state)) {
226 control_connection_t *conn = TO_CONTROL_CONN(_conn);
227 if (conn->use_long_names)
228 global_event_mask1long |= conn->event_mask;
229 else
230 global_event_mask1short |= conn->event_mask;
234 new_mask = global_event_mask1short;
235 new_mask |= global_event_mask1long;
237 /* Handle the aftermath. Set up the log callback to tell us only what
238 * we want to hear...*/
239 control_adjust_event_log_severity();
241 /* ...then, if we've started logging stream bw, clear the appropriate
242 * fields. */
243 if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
244 (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
245 SMARTLIST_FOREACH(conns, connection_t *, conn,
247 if (conn->type == CONN_TYPE_AP) {
248 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
249 edge_conn->n_written = edge_conn->n_read = 0;
255 /** Adjust the log severities that result in control_event_logmsg being called
256 * to match the severity of log messages that any controllers are interested
257 * in. */
258 void
259 control_adjust_event_log_severity(void)
261 int i;
262 int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
264 for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
265 if (EVENT_IS_INTERESTING(i)) {
266 min_log_event = i;
267 break;
270 for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
271 if (EVENT_IS_INTERESTING(i)) {
272 max_log_event = i;
273 break;
276 if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE) ||
277 EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
278 if (min_log_event > EVENT_NOTICE_MSG)
279 min_log_event = EVENT_NOTICE_MSG;
280 if (max_log_event < EVENT_ERR_MSG)
281 max_log_event = EVENT_ERR_MSG;
283 if (min_log_event <= max_log_event)
284 change_callback_log_severity(event_to_log_severity(min_log_event),
285 event_to_log_severity(max_log_event),
286 control_event_logmsg);
287 else
288 change_callback_log_severity(LOG_ERR, LOG_ERR,
289 control_event_logmsg);
292 /** Return true iff the event with code <b>c</b> is being sent to any current
293 * control connection. This is useful if the amount of work needed to prepare
294 * to call the appropriate control_event_...() function is high.
297 control_event_is_interesting(int event)
299 return EVENT_IS_INTERESTING(event);
302 /** Append a NUL-terminated string <b>s</b> to the end of
303 * <b>conn</b>-\>outbuf.
305 static INLINE void
306 connection_write_str_to_buf(const char *s, control_connection_t *conn)
308 size_t len = strlen(s);
309 connection_write_to_buf(s, len, TO_CONN(conn));
312 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
313 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
314 * contents of <b>data</b> into *<b>out</b>, adding a period before any period
315 * that that appears at the start of a line, and adding a period-CRLF line at
316 * the end. Replace all LF characters sequences with CRLF. Return the number
317 * of bytes in *<b>out</b>.
319 /* static */ size_t
320 write_escaped_data(const char *data, size_t len, char **out)
322 size_t sz_out = len+8;
323 char *outp;
324 const char *start = data, *end;
325 int i;
326 int start_of_line;
327 for (i=0; i<(int)len; ++i) {
328 if (data[i]== '\n')
329 sz_out += 2; /* Maybe add a CR; maybe add a dot. */
331 *out = outp = tor_malloc(sz_out+1);
332 end = data+len;
333 start_of_line = 1;
334 while (data < end) {
335 if (*data == '\n') {
336 if (data > start && data[-1] != '\r')
337 *outp++ = '\r';
338 start_of_line = 1;
339 } else if (*data == '.') {
340 if (start_of_line) {
341 start_of_line = 0;
342 *outp++ = '.';
344 } else {
345 start_of_line = 0;
347 *outp++ = *data++;
349 if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
350 *outp++ = '\r';
351 *outp++ = '\n';
353 *outp++ = '.';
354 *outp++ = '\r';
355 *outp++ = '\n';
356 *outp = '\0'; /* NUL-terminate just in case. */
357 tor_assert((outp - *out) <= (int)sz_out);
358 return outp - *out;
361 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
362 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
363 * the contents of <b>data</b> into *<b>out</b>, removing any period
364 * that appears at the start of a line, and replacing all CRLF sequences
365 * with LF. Return the number of
366 * bytes in *<b>out</b>. */
367 /* static */ size_t
368 read_escaped_data(const char *data, size_t len, char **out)
370 char *outp;
371 const char *next;
372 const char *end;
374 *out = outp = tor_malloc(len+1);
376 end = data+len;
378 while (data < end) {
379 /* we're at the start of a line. */
380 if (*data == '.')
381 ++data;
382 next = memchr(data, '\n', end-data);
383 if (next) {
384 size_t n_to_copy = next-data;
385 /* Don't copy a CR that precedes this LF. */
386 if (n_to_copy && *(next-1) == '\r')
387 --n_to_copy;
388 memcpy(outp, data, n_to_copy);
389 outp += n_to_copy;
390 data = next+1; /* This will point at the start of the next line,
391 * or the end of the string, or a period. */
392 } else {
393 memcpy(outp, data, end-data);
394 outp += (end-data);
395 *outp = '\0';
396 return outp - *out;
398 *outp++ = '\n';
401 *outp = '\0';
402 return outp - *out;
405 /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
406 * double-quoted string with escaped characters, return the length of that
407 * string (as encoded, including quotes). Otherwise return -1. */
408 static INLINE int
409 get_escaped_string_length(const char *start, size_t in_len_max,
410 int *chars_out)
412 const char *cp, *end;
413 int chars = 0;
415 if (*start != '\"')
416 return -1;
418 cp = start+1;
419 end = start+in_len_max;
421 /* Calculate length. */
422 while (1) {
423 if (cp >= end) {
424 return -1; /* Too long. */
425 } else if (*cp == '\\') {
426 if (++cp == end)
427 return -1; /* Can't escape EOS. */
428 ++cp;
429 ++chars;
430 } else if (*cp == '\"') {
431 break;
432 } else {
433 ++cp;
434 ++chars;
437 if (chars_out)
438 *chars_out = chars;
439 return (int)(cp - start+1);
442 /** As decode_escaped_string, but does not decode the string: copies the
443 * entire thing, including quotation marks. */
444 static const char *
445 extract_escaped_string(const char *start, size_t in_len_max,
446 char **out, size_t *out_len)
448 int length = get_escaped_string_length(start, in_len_max, NULL);
449 if (length<0)
450 return NULL;
451 *out_len = length;
452 *out = tor_strndup(start, *out_len);
453 return start+length;
456 /** Given a pointer to a string starting at <b>start</b> containing
457 * <b>in_len_max</b> characters, decode a string beginning with one double
458 * quote, containing any number of non-quote characters or characters escaped
459 * with a backslash, and ending with a final double quote. Place the resulting
460 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
461 * store its length in <b>out_len</b>. On success, return a pointer to the
462 * character immediately following the escaped string. On failure, return
463 * NULL. */
464 static const char *
465 decode_escaped_string(const char *start, size_t in_len_max,
466 char **out, size_t *out_len)
468 const char *cp, *end;
469 char *outp;
470 int len, n_chars = 0;
472 len = get_escaped_string_length(start, in_len_max, &n_chars);
473 if (len<0)
474 return NULL;
476 end = start+len-1; /* Index of last quote. */
477 tor_assert(*end == '\"');
478 outp = *out = tor_malloc(len+1);
479 *out_len = n_chars;
481 cp = start+1;
482 while (cp < end) {
483 if (*cp == '\\')
484 ++cp;
485 *outp++ = *cp++;
487 *outp = '\0';
488 tor_assert((outp - *out) == (int)*out_len);
490 return end+1;
493 /** Acts like sprintf, but writes its formatted string to the end of
494 * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
495 * but it will always end with a CRLF sequence.
497 * Currently the length of the message is limited to 1024 (including the
498 * ending CR LF NUL ("\\r\\n\\0"). */
499 static void
500 connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
502 #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
503 va_list ap;
504 char buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE];
505 int r;
506 size_t len;
507 va_start(ap,format);
508 r = tor_vsnprintf(buf, sizeof(buf), format, ap);
509 va_end(ap);
510 if (r<0) {
511 log_warn(LD_BUG, "Unable to format string for controller.");
512 return;
514 len = strlen(buf);
515 if (memcmp("\r\n\0", buf+len-2, 3)) {
516 buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-1] = '\0';
517 buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-2] = '\n';
518 buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-3] = '\r';
520 connection_write_to_buf(buf, len, TO_CONN(conn));
523 /** Send a "DONE" message down the control connection <b>conn</b>. */
524 static void
525 send_control_done(control_connection_t *conn)
527 connection_write_str_to_buf("250 OK\r\n", conn);
530 /** Send an event to all v1 controllers that are listening for code
531 * <b>event</b>. The event's body is given by <b>msg</b>.
533 * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
534 * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
535 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
536 * to contollers that <em>have</em> enabled VERBOSE_NAMES.
538 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
539 * respect to the EXTENDED_EVENTS feature. */
540 static void
541 send_control_event_string(uint16_t event, event_format_t which,
542 const char *msg)
544 smartlist_t *conns = get_connection_array();
545 tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);
547 SMARTLIST_FOREACH(conns, connection_t *, conn,
549 if (conn->type == CONN_TYPE_CONTROL &&
550 !conn->marked_for_close &&
551 conn->state == CONTROL_CONN_STATE_OPEN) {
552 control_connection_t *control_conn = TO_CONTROL_CONN(conn);
553 if (control_conn->use_long_names) {
554 if (!(which & LONG_NAMES))
555 continue;
556 } else {
557 if (!(which & SHORT_NAMES))
558 continue;
560 if (control_conn->use_extended_events) {
561 if (!(which & EXTENDED_FORMAT))
562 continue;
563 } else {
564 if (!(which & NONEXTENDED_FORMAT))
565 continue;
567 if (control_conn->event_mask & (1<<event)) {
568 int is_err = 0;
569 connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
570 if (event == EVENT_ERR_MSG)
571 is_err = 1;
572 else if (event == EVENT_STATUS_GENERAL)
573 is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
574 else if (event == EVENT_STATUS_CLIENT)
575 is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
576 else if (event == EVENT_STATUS_SERVER)
577 is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
578 if (is_err)
579 connection_handle_write(TO_CONN(control_conn), 1);
585 /** Helper for send_control1_event and send_control1_event_extended:
586 * Send an event to all v1 controllers that are listening for code
587 * <b>event</b>. The event's body is created by the printf-style format in
588 * <b>format</b>, and other arguments as provided.
590 * If <b>extended</b> is true, and the format contains a single '@' character,
591 * it will be replaced with a space and all text after that character will be
592 * sent only to controllers that have enabled extended events.
594 * Currently the length of the message is limited to 1024 (including the
595 * ending \\r\\n\\0). */
596 static void
597 send_control_event_impl(uint16_t event, event_format_t which, int extended,
598 const char *format, va_list ap)
600 /* This is just a little longer than the longest allowed log message */
601 #define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
602 int r;
603 char buf[SEND_CONTROL1_EVENT_BUFFERSIZE];
604 size_t len;
605 char *cp;
607 r = tor_vsnprintf(buf, sizeof(buf), format, ap);
608 if (r<0) {
609 log_warn(LD_BUG, "Unable to format event for controller.");
610 return;
613 len = strlen(buf);
614 if (memcmp("\r\n\0", buf+len-2, 3)) {
615 /* if it is not properly terminated, do it now */
616 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-1] = '\0';
617 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-2] = '\n';
618 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-3] = '\r';
621 if (extended && (cp = strchr(buf, '@'))) {
622 which &= ~ALL_FORMATS;
623 *cp = ' ';
624 send_control_event_string(event, which|EXTENDED_FORMAT, buf);
625 memcpy(cp, "\r\n\0", 3);
626 send_control_event_string(event, which|NONEXTENDED_FORMAT, buf);
627 } else {
628 send_control_event_string(event, which|ALL_FORMATS, buf);
632 /** Send an event to all v1 controllers that are listening for code
633 * <b>event</b>. The event's body is created by the printf-style format in
634 * <b>format</b>, and other arguments as provided.
636 * Currently the length of the message is limited to 1024 (including the
637 * ending \\n\\r\\0. */
638 static void
639 send_control_event(uint16_t event, event_format_t which,
640 const char *format, ...)
642 va_list ap;
643 va_start(ap, format);
644 send_control_event_impl(event, which, 0, format, ap);
645 va_end(ap);
648 /** Send an event to all v1 controllers that are listening for code
649 * <b>event</b>. The event's body is created by the printf-style format in
650 * <b>format</b>, and other arguments as provided.
652 * If the format contains a single '@' character, it will be replaced with a
653 * space and all text after that character will be sent only to controllers
654 * that have enabled extended events.
656 * Currently the length of the message is limited to 1024 (including the
657 * ending \\n\\r\\0. */
658 static void
659 send_control_event_extended(uint16_t event, event_format_t which,
660 const char *format, ...)
662 va_list ap;
663 va_start(ap, format);
664 send_control_event_impl(event, which, 1, format, ap);
665 va_end(ap);
668 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
669 static origin_circuit_t *
670 get_circ(const char *id)
672 uint32_t n_id;
673 int ok;
674 n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
675 if (!ok)
676 return NULL;
677 return circuit_get_by_global_id(n_id);
680 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
681 static edge_connection_t *
682 get_stream(const char *id)
684 uint64_t n_id;
685 int ok;
686 connection_t *conn;
687 n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
688 if (!ok)
689 return NULL;
690 conn = connection_get_by_global_id(n_id);
691 if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
692 return NULL;
693 return TO_EDGE_CONN(conn);
696 /** Helper for setconf and resetconf. Acts like setconf, except
697 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
698 * contents of body.
700 static int
701 control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
702 int use_defaults)
704 setopt_err_t opt_err;
705 config_line_t *lines=NULL;
706 char *start = body;
707 char *errstring = NULL;
708 const int clear_first = 1;
710 char *config;
711 smartlist_t *entries = smartlist_create();
713 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
714 * separated by space. break it into a list of configuration entries. */
715 while (*body) {
716 char *eq = body;
717 char *key;
718 char *entry;
719 while (!TOR_ISSPACE(*eq) && *eq != '=')
720 ++eq;
721 key = tor_strndup(body, eq-body);
722 body = eq+1;
723 if (*eq == '=') {
724 char *val=NULL;
725 size_t val_len=0;
726 size_t ent_len;
727 if (*body != '\"') {
728 char *val_start = body;
729 while (!TOR_ISSPACE(*body))
730 body++;
731 val = tor_strndup(val_start, body-val_start);
732 val_len = strlen(val);
733 } else {
734 body = (char*)extract_escaped_string(body, (len - (body-start)),
735 &val, &val_len);
736 if (!body) {
737 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
738 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
739 smartlist_free(entries);
740 tor_free(key);
741 return 0;
744 ent_len = strlen(key)+val_len+3;
745 entry = tor_malloc(ent_len+1);
746 tor_snprintf(entry, ent_len, "%s %s", key, val);
747 tor_free(key);
748 tor_free(val);
749 } else {
750 entry = key;
752 smartlist_add(entries, entry);
753 while (TOR_ISSPACE(*body))
754 ++body;
757 smartlist_add(entries, tor_strdup(""));
758 config = smartlist_join_strings(entries, "\n", 0, NULL);
759 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
760 smartlist_free(entries);
762 if (config_get_lines(config, &lines) < 0) {
763 log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
764 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
765 conn);
766 tor_free(config);
767 return 0;
769 tor_free(config);
771 opt_err = options_trial_assign(lines, use_defaults, clear_first, &errstring);
773 const char *msg;
774 switch (opt_err) {
775 case SETOPT_ERR_MISC:
776 msg = "552 Unrecognized option";
777 break;
778 case SETOPT_ERR_PARSE:
779 msg = "513 Unacceptable option value";
780 break;
781 case SETOPT_ERR_TRANSITION:
782 msg = "553 Transition not allowed";
783 break;
784 case SETOPT_ERR_SETTING:
785 default:
786 msg = "553 Unable to set option";
787 break;
788 case SETOPT_OK:
789 config_free_lines(lines);
790 send_control_done(conn);
791 return 0;
793 log_warn(LD_CONTROL,
794 "Controller gave us config lines that didn't validate: %s",
795 errstring);
796 connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
797 config_free_lines(lines);
798 tor_free(errstring);
799 return 0;
803 /** Called when we receive a SETCONF message: parse the body and try
804 * to update our configuration. Reply with a DONE or ERROR message.
805 * Modifies the contents of body.*/
806 static int
807 handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
809 return control_setconf_helper(conn, len, body, 0);
812 /** Called when we receive a RESETCONF message: parse the body and try
813 * to update our configuration. Reply with a DONE or ERROR message.
814 * Modifies the contents of body. */
815 static int
816 handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
818 return control_setconf_helper(conn, len, body, 1);
821 /** Called when we receive a GETCONF message. Parse the request, and
822 * reply with a CONFVALUE or an ERROR message */
823 static int
824 handle_control_getconf(control_connection_t *conn, uint32_t body_len,
825 const char *body)
827 smartlist_t *questions = smartlist_create();
828 smartlist_t *answers = smartlist_create();
829 smartlist_t *unrecognized = smartlist_create();
830 char *msg = NULL;
831 size_t msg_len;
832 or_options_t *options = get_options();
833 int i, len;
835 (void) body_len; /* body is nul-terminated; so we can ignore len. */
836 smartlist_split_string(questions, body, " ",
837 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
838 SMARTLIST_FOREACH(questions, const char *, q,
840 if (!option_is_recognized(q)) {
841 smartlist_add(unrecognized, (char*) q);
842 } else {
843 config_line_t *answer = option_get_assignment(options,q);
844 if (!answer) {
845 const char *name = option_get_canonical_name(q);
846 size_t alen = strlen(name)+8;
847 char *astr = tor_malloc(alen);
848 tor_snprintf(astr, alen, "250-%s\r\n", name);
849 smartlist_add(answers, astr);
852 while (answer) {
853 config_line_t *next;
854 size_t alen = strlen(answer->key)+strlen(answer->value)+8;
855 char *astr = tor_malloc(alen);
856 tor_snprintf(astr, alen, "250-%s=%s\r\n",
857 answer->key, answer->value);
858 smartlist_add(answers, astr);
860 next = answer->next;
861 tor_free(answer->key);
862 tor_free(answer->value);
863 tor_free(answer);
864 answer = next;
869 if ((len = smartlist_len(unrecognized))) {
870 for (i=0; i < len-1; ++i)
871 connection_printf_to_buf(conn,
872 "552-Unrecognized configuration key \"%s\"\r\n",
873 (char*)smartlist_get(unrecognized, i));
874 connection_printf_to_buf(conn,
875 "552 Unrecognized configuration key \"%s\"\r\n",
876 (char*)smartlist_get(unrecognized, len-1));
877 } else if ((len = smartlist_len(answers))) {
878 char *tmp = smartlist_get(answers, len-1);
879 tor_assert(strlen(tmp)>4);
880 tmp[3] = ' ';
881 msg = smartlist_join_strings(answers, "", 0, &msg_len);
882 connection_write_to_buf(msg, msg_len, TO_CONN(conn));
883 } else {
884 connection_write_str_to_buf("250 OK\r\n", conn);
887 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
888 smartlist_free(answers);
889 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
890 smartlist_free(questions);
891 smartlist_free(unrecognized);
893 tor_free(msg);
895 return 0;
898 /** Called when we get a +LOADCONF message. */
899 static int
900 handle_control_loadconf(control_connection_t *conn, uint32_t len,
901 const char *body)
903 setopt_err_t retval;
904 char *errstring = NULL;
905 const char *msg = NULL;
906 (void) len;
908 retval = options_init_from_string(body, CMD_RUN_TOR, NULL, &errstring);
910 if (retval != SETOPT_OK) {
911 log_warn(LD_CONTROL,
912 "Controller gave us config file that didn't validate: %s",
913 errstring);
914 switch (retval) {
915 case SETOPT_ERR_PARSE:
916 msg = "552 Invalid config file";
917 break;
918 case SETOPT_ERR_TRANSITION:
919 msg = "553 Transition not allowed";
920 break;
921 case SETOPT_ERR_SETTING:
922 msg = "553 Unable to set option";
923 break;
924 case SETOPT_ERR_MISC:
925 default:
926 msg = "550 Unable to load config";
927 break;
928 case SETOPT_OK:
929 tor_fragile_assert();
930 break;
932 if (*errstring)
933 connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
934 else
935 connection_printf_to_buf(conn, "%s\r\n", msg);
936 tor_free(errstring);
937 return 0;
939 send_control_done(conn);
940 return 0;
943 /** Called when we get a SETEVENTS message: update conn->event_mask,
944 * and reply with DONE or ERROR. */
945 static int
946 handle_control_setevents(control_connection_t *conn, uint32_t len,
947 const char *body)
949 uint16_t event_code;
950 uint32_t event_mask = 0;
951 unsigned int extended = 0;
952 smartlist_t *events = smartlist_create();
954 (void) len;
956 smartlist_split_string(events, body, " ",
957 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
958 SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
960 if (!strcasecmp(ev, "EXTENDED")) {
961 extended = 1;
962 continue;
963 } else if (!strcasecmp(ev, "CIRC"))
964 event_code = EVENT_CIRCUIT_STATUS;
965 else if (!strcasecmp(ev, "STREAM"))
966 event_code = EVENT_STREAM_STATUS;
967 else if (!strcasecmp(ev, "ORCONN"))
968 event_code = EVENT_OR_CONN_STATUS;
969 else if (!strcasecmp(ev, "BW"))
970 event_code = EVENT_BANDWIDTH_USED;
971 else if (!strcasecmp(ev, "DEBUG"))
972 event_code = EVENT_DEBUG_MSG;
973 else if (!strcasecmp(ev, "INFO"))
974 event_code = EVENT_INFO_MSG;
975 else if (!strcasecmp(ev, "NOTICE"))
976 event_code = EVENT_NOTICE_MSG;
977 else if (!strcasecmp(ev, "WARN"))
978 event_code = EVENT_WARN_MSG;
979 else if (!strcasecmp(ev, "ERR"))
980 event_code = EVENT_ERR_MSG;
981 else if (!strcasecmp(ev, "NEWDESC"))
982 event_code = EVENT_NEW_DESC;
983 else if (!strcasecmp(ev, "ADDRMAP"))
984 event_code = EVENT_ADDRMAP;
985 else if (!strcasecmp(ev, "AUTHDIR_NEWDESCS"))
986 event_code = EVENT_AUTHDIR_NEWDESCS;
987 else if (!strcasecmp(ev, "DESCCHANGED"))
988 event_code = EVENT_DESCCHANGED;
989 else if (!strcasecmp(ev, "NS"))
990 event_code = EVENT_NS;
991 else if (!strcasecmp(ev, "STATUS_GENERAL"))
992 event_code = EVENT_STATUS_GENERAL;
993 else if (!strcasecmp(ev, "STATUS_CLIENT"))
994 event_code = EVENT_STATUS_CLIENT;
995 else if (!strcasecmp(ev, "STATUS_SERVER"))
996 event_code = EVENT_STATUS_SERVER;
997 else if (!strcasecmp(ev, "GUARD"))
998 event_code = EVENT_GUARD;
999 else if (!strcasecmp(ev, "STREAM_BW"))
1000 event_code = EVENT_STREAM_BANDWIDTH_USED;
1001 else if (!strcasecmp(ev, "CLIENTS_SEEN"))
1002 event_code = EVENT_CLIENTS_SEEN;
1003 else if (!strcasecmp(ev, "NEWCONSENSUS"))
1004 event_code = EVENT_NEWCONSENSUS;
1005 else {
1006 connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
1007 ev);
1008 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
1009 smartlist_free(events);
1010 return 0;
1012 event_mask |= (1 << event_code);
1014 SMARTLIST_FOREACH_END(ev);
1015 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
1016 smartlist_free(events);
1018 conn->event_mask = event_mask;
1019 if (extended)
1020 conn->use_extended_events = 1;
1022 control_update_global_event_mask();
1023 send_control_done(conn);
1024 return 0;
1027 /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
1028 * Return a smartlist of acceptable passwords (unterminated strings of
1029 * length S2K_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on failure.
1031 smartlist_t *
1032 decode_hashed_passwords(config_line_t *passwords)
1034 char decoded[64];
1035 config_line_t *cl;
1036 smartlist_t *sl = smartlist_create();
1038 tor_assert(passwords);
1040 for (cl = passwords; cl; cl = cl->next) {
1041 const char *hashed = cl->value;
1043 if (!strcmpstart(hashed, "16:")) {
1044 if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
1045 || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
1046 goto err;
1048 } else {
1049 if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
1050 != S2K_SPECIFIER_LEN+DIGEST_LEN) {
1051 goto err;
1054 smartlist_add(sl, tor_memdup(decoded, S2K_SPECIFIER_LEN+DIGEST_LEN));
1057 return sl;
1059 err:
1060 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
1061 smartlist_free(sl);
1062 return NULL;
1065 /** Called when we get an AUTHENTICATE message. Check whether the
1066 * authentication is valid, and if so, update the connection's state to
1067 * OPEN. Reply with DONE or ERROR.
1069 static int
1070 handle_control_authenticate(control_connection_t *conn, uint32_t len,
1071 const char *body)
1073 int used_quoted_string = 0;
1074 or_options_t *options = get_options();
1075 const char *errstr = NULL;
1076 char *password;
1077 size_t password_len;
1078 const char *cp;
1079 int i;
1080 int bad_cookie=0, bad_password=0;
1081 smartlist_t *sl = NULL;
1083 if (TOR_ISXDIGIT(body[0])) {
1084 cp = body;
1085 while (TOR_ISXDIGIT(*cp))
1086 ++cp;
1087 i = (int)(cp - body);
1088 tor_assert(i>0);
1089 password_len = i/2;
1090 password = tor_malloc(password_len + 1);
1091 if (base16_decode(password, password_len+1, body, i)<0) {
1092 connection_write_str_to_buf(
1093 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1094 "password? If so, the standard requires that you put it in "
1095 "double quotes.\r\n", conn);
1096 connection_mark_for_close(TO_CONN(conn));
1097 tor_free(password);
1098 return 0;
1100 } else if (TOR_ISSPACE(body[0])) {
1101 password = tor_strdup("");
1102 password_len = 0;
1103 } else {
1104 if (!decode_escaped_string(body, len, &password, &password_len)) {
1105 connection_write_str_to_buf("551 Invalid quoted string. You need "
1106 "to put the password in double quotes.\r\n", conn);
1107 connection_mark_for_close(TO_CONN(conn));
1108 return 0;
1110 used_quoted_string = 1;
1113 if (!options->CookieAuthentication && !options->HashedControlPassword &&
1114 !options->HashedControlSessionPassword) {
1115 /* if Tor doesn't demand any stronger authentication, then
1116 * the controller can get in with anything. */
1117 goto ok;
1120 if (options->CookieAuthentication) {
1121 int also_password = options->HashedControlPassword != NULL ||
1122 options->HashedControlSessionPassword != NULL;
1123 if (password_len != AUTHENTICATION_COOKIE_LEN) {
1124 if (!also_password) {
1125 log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
1126 "(%d)", (int)password_len);
1127 errstr = "Wrong length on authentication cookie.";
1128 goto err;
1130 bad_cookie = 1;
1131 } else if (memcmp(authentication_cookie, password, password_len)) {
1132 if (!also_password) {
1133 log_warn(LD_CONTROL, "Got mismatched authentication cookie");
1134 errstr = "Authentication cookie did not match expected value.";
1135 goto err;
1137 bad_cookie = 1;
1138 } else {
1139 goto ok;
1143 if (options->HashedControlPassword ||
1144 options->HashedControlSessionPassword) {
1145 int bad = 0;
1146 smartlist_t *sl_tmp;
1147 char received[DIGEST_LEN];
1148 int also_cookie = options->CookieAuthentication;
1149 sl = smartlist_create();
1150 if (options->HashedControlPassword) {
1151 sl_tmp = decode_hashed_passwords(options->HashedControlPassword);
1152 if (!sl_tmp)
1153 bad = 1;
1154 else {
1155 smartlist_add_all(sl, sl_tmp);
1156 smartlist_free(sl_tmp);
1159 if (options->HashedControlSessionPassword) {
1160 sl_tmp = decode_hashed_passwords(options->HashedControlSessionPassword);
1161 if (!sl_tmp)
1162 bad = 1;
1163 else {
1164 smartlist_add_all(sl, sl_tmp);
1165 smartlist_free(sl_tmp);
1168 if (bad) {
1169 if (!also_cookie) {
1170 log_warn(LD_CONTROL,
1171 "Couldn't decode HashedControlPassword: invalid base16");
1172 errstr="Couldn't decode HashedControlPassword value in configuration.";
1174 bad_password = 1;
1175 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1176 smartlist_free(sl);
1177 } else {
1178 SMARTLIST_FOREACH(sl, char *, expected,
1180 secret_to_key(received,DIGEST_LEN,password,password_len,expected);
1181 if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
1182 goto ok;
1184 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1185 smartlist_free(sl);
1187 if (used_quoted_string)
1188 errstr = "Password did not match HashedControlPassword value from "
1189 "configuration";
1190 else
1191 errstr = "Password did not match HashedControlPassword value from "
1192 "configuration. Maybe you tried a plain text password? "
1193 "If so, the standard requires that you put it in double quotes.";
1194 bad_password = 1;
1195 if (!also_cookie)
1196 goto err;
1200 /** We only get here if both kinds of authentication failed. */
1201 tor_assert(bad_password && bad_cookie);
1202 log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
1203 errstr = "Password did not match HashedControlPassword *or* authentication "
1204 "cookie.";
1206 err:
1207 tor_free(password);
1208 connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n",
1209 errstr ? errstr : "Unknown reason.");
1210 connection_mark_for_close(TO_CONN(conn));
1211 return 0;
1213 log_info(LD_CONTROL, "Authenticated control connection (%d)", conn->_base.s);
1214 send_control_done(conn);
1215 conn->_base.state = CONTROL_CONN_STATE_OPEN;
1216 tor_free(password);
1217 if (sl) { /* clean up */
1218 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1219 smartlist_free(sl);
1221 return 0;
1224 /** Called when we get a SAVECONF command. Try to flush the current options to
1225 * disk, and report success or failure. */
1226 static int
1227 handle_control_saveconf(control_connection_t *conn, uint32_t len,
1228 const char *body)
1230 (void) len;
1231 (void) body;
1232 if (options_save_current()<0) {
1233 connection_write_str_to_buf(
1234 "551 Unable to write configuration to disk.\r\n", conn);
1235 } else {
1236 send_control_done(conn);
1238 return 0;
1241 /** Called when we get a SIGNAL command. React to the provided signal, and
1242 * report success or failure. (If the signal results in a shutdown, success
1243 * may not be reported.) */
1244 static int
1245 handle_control_signal(control_connection_t *conn, uint32_t len,
1246 const char *body)
1248 int sig;
1249 int n = 0;
1250 char *s;
1252 (void) len;
1254 while (body[n] && ! TOR_ISSPACE(body[n]))
1255 ++n;
1256 s = tor_strndup(body, n);
1257 if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
1258 sig = SIGHUP;
1259 else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
1260 sig = SIGINT;
1261 else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
1262 sig = SIGUSR1;
1263 else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
1264 sig = SIGUSR2;
1265 else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
1266 sig = SIGTERM;
1267 else if (!strcasecmp(s, "NEWNYM"))
1268 sig = SIGNEWNYM;
1269 else if (!strcasecmp(s, "CLEARDNSCACHE"))
1270 sig = SIGCLEARDNSCACHE;
1271 else {
1272 connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
1274 sig = -1;
1276 tor_free(s);
1277 if (sig<0)
1278 return 0;
1280 send_control_done(conn);
1281 /* Flush the "done" first if the signal might make us shut down. */
1282 if (sig == SIGTERM || sig == SIGINT)
1283 connection_handle_write(TO_CONN(conn), 1);
1284 control_signal_act(sig);
1285 return 0;
1288 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1289 * and report success or failrue. */
1290 static int
1291 handle_control_mapaddress(control_connection_t *conn, uint32_t len,
1292 const char *body)
1294 smartlist_t *elts;
1295 smartlist_t *lines;
1296 smartlist_t *reply;
1297 char *r;
1298 size_t sz;
1299 (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
1301 lines = smartlist_create();
1302 elts = smartlist_create();
1303 reply = smartlist_create();
1304 smartlist_split_string(lines, body, " ",
1305 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1306 SMARTLIST_FOREACH(lines, char *, line,
1308 tor_strlower(line);
1309 smartlist_split_string(elts, line, "=", 0, 2);
1310 if (smartlist_len(elts) == 2) {
1311 const char *from = smartlist_get(elts,0);
1312 const char *to = smartlist_get(elts,1);
1313 size_t anslen = strlen(line)+512;
1314 char *ans = tor_malloc(anslen);
1315 if (address_is_invalid_destination(to, 1)) {
1316 tor_snprintf(ans, anslen,
1317 "512-syntax error: invalid address '%s'", to);
1318 smartlist_add(reply, ans);
1319 log_warn(LD_CONTROL,
1320 "Skipping invalid argument '%s' in MapAddress msg", to);
1321 } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
1322 const char *address = addressmap_register_virtual_address(
1323 !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
1324 tor_strdup(to));
1325 if (!address) {
1326 tor_snprintf(ans, anslen,
1327 "451-resource exhausted: skipping '%s'", line);
1328 smartlist_add(reply, ans);
1329 log_warn(LD_CONTROL,
1330 "Unable to allocate address for '%s' in MapAddress msg",
1331 safe_str(line));
1332 } else {
1333 tor_snprintf(ans, anslen, "250-%s=%s", address, to);
1334 smartlist_add(reply, ans);
1336 } else {
1337 addressmap_register(from, tor_strdup(to), 1, ADDRMAPSRC_CONTROLLER);
1338 tor_snprintf(ans, anslen, "250-%s", line);
1339 smartlist_add(reply, ans);
1341 } else {
1342 size_t anslen = strlen(line)+256;
1343 char *ans = tor_malloc(anslen);
1344 tor_snprintf(ans, anslen, "512-syntax error: mapping '%s' is "
1345 "not of expected form 'foo=bar'.", line);
1346 smartlist_add(reply, ans);
1347 log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
1348 "number of items.", safe_str(line));
1350 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
1351 smartlist_clear(elts);
1353 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1354 smartlist_free(lines);
1355 smartlist_free(elts);
1357 if (smartlist_len(reply)) {
1358 ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
1359 r = smartlist_join_strings(reply, "\r\n", 1, &sz);
1360 connection_write_to_buf(r, sz, TO_CONN(conn));
1361 tor_free(r);
1362 } else {
1363 const char *response =
1364 "512 syntax error: not enough arguments to mapaddress.\r\n";
1365 connection_write_to_buf(response, strlen(response), TO_CONN(conn));
1368 SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
1369 smartlist_free(reply);
1370 return 0;
1373 /** Implementation helper for GETINFO: knows the answers for various
1374 * trivial-to-implement questions. */
1375 static int
1376 getinfo_helper_misc(control_connection_t *conn, const char *question,
1377 char **answer)
1379 (void) conn;
1380 if (!strcmp(question, "version")) {
1381 *answer = tor_strdup(get_version());
1382 } else if (!strcmp(question, "config-file")) {
1383 *answer = tor_strdup(get_torrc_fname());
1384 } else if (!strcmp(question, "info/names")) {
1385 *answer = list_getinfo_options();
1386 } else if (!strcmp(question, "events/names")) {
1387 *answer = tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
1388 "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
1389 "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
1390 "GUARD STREAM_BW CLIENTS_SEEN NEWCONSENSUS");
1391 } else if (!strcmp(question, "features/names")) {
1392 *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1393 } else if (!strcmp(question, "address")) {
1394 uint32_t addr;
1395 if (router_pick_published_address(get_options(), &addr) < 0)
1396 return -1;
1397 *answer = tor_dup_ip(addr);
1398 } else if (!strcmp(question, "dir-usage")) {
1399 *answer = directory_dump_request_log();
1400 } else if (!strcmp(question, "fingerprint")) {
1401 routerinfo_t *me = router_get_my_routerinfo();
1402 if (!me)
1403 return -1;
1404 *answer = tor_malloc(HEX_DIGEST_LEN+1);
1405 base16_encode(*answer, HEX_DIGEST_LEN+1, me->cache_info.identity_digest,
1406 DIGEST_LEN);
1408 return 0;
1411 /** Awful hack: return a newly allocated string based on a routerinfo and
1412 * (possibly) an extrainfo, sticking the read-history and write-history from
1413 * <b>ei</b> into the resulting string. The thing you get back won't
1414 * necessarily have a valid signature.
1416 * New code should never use this; it's for backward compatibility.
1418 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1419 * not be NUL-terminated. */
1420 static char *
1421 munge_extrainfo_into_routerinfo(const char *ri_body, signed_descriptor_t *ri,
1422 signed_descriptor_t *ei)
1424 char *out = NULL, *outp;
1425 int i;
1426 const char *router_sig;
1427 const char *ei_body = signed_descriptor_get_body(ei);
1428 size_t ri_len = ri->signed_descriptor_len;
1429 size_t ei_len = ei->signed_descriptor_len;
1430 if (!ei_body)
1431 goto bail;
1433 outp = out = tor_malloc(ri_len+ei_len+1);
1434 if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
1435 goto bail;
1436 ++router_sig;
1437 memcpy(out, ri_body, router_sig-ri_body);
1438 outp += router_sig-ri_body;
1440 for (i=0; i < 2; ++i) {
1441 const char *kwd = i?"\nwrite-history ":"\nread-history ";
1442 const char *cp, *eol;
1443 if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
1444 continue;
1445 ++cp;
1446 eol = memchr(cp, '\n', ei_len - (cp-ei_body));
1447 memcpy(outp, cp, eol-cp+1);
1448 outp += eol-cp+1;
1450 memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
1451 *outp++ = '\0';
1452 tor_assert(outp-out < (int)(ri_len+ei_len+1));
1454 return out;
1455 bail:
1456 tor_free(out);
1457 return tor_strndup(ri_body, ri->signed_descriptor_len);
1460 /** Implementation helper for GETINFO: knows the answers for questions about
1461 * directory information. */
1462 static int
1463 getinfo_helper_dir(control_connection_t *control_conn,
1464 const char *question, char **answer)
1466 if (!strcmpstart(question, "desc/id/")) {
1467 routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
1468 if (ri) {
1469 const char *body = signed_descriptor_get_body(&ri->cache_info);
1470 if (body)
1471 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1473 } else if (!strcmpstart(question, "desc/name/")) {
1474 routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
1475 if (ri) {
1476 const char *body = signed_descriptor_get_body(&ri->cache_info);
1477 if (body)
1478 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1480 } else if (!strcmp(question, "desc/all-recent")) {
1481 routerlist_t *routerlist = router_get_routerlist();
1482 smartlist_t *sl = smartlist_create();
1483 if (routerlist && routerlist->routers) {
1484 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
1486 const char *body = signed_descriptor_get_body(&ri->cache_info);
1487 if (body)
1488 smartlist_add(sl,
1489 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1492 *answer = smartlist_join_strings(sl, "", 0, NULL);
1493 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1494 smartlist_free(sl);
1495 } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
1496 /* XXXX Remove this once Torstat asks for extrainfos. */
1497 routerlist_t *routerlist = router_get_routerlist();
1498 smartlist_t *sl = smartlist_create();
1499 if (routerlist && routerlist->routers) {
1500 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
1502 const char *body = signed_descriptor_get_body(&ri->cache_info);
1503 signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
1504 ri->cache_info.extra_info_digest);
1505 if (ei && body) {
1506 smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
1507 &ri->cache_info, ei));
1508 } else if (body) {
1509 smartlist_add(sl,
1510 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1514 *answer = smartlist_join_strings(sl, "", 0, NULL);
1515 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1516 smartlist_free(sl);
1517 } else if (!strcmpstart(question, "desc-annotations/id/")) {
1518 routerinfo_t *ri = router_get_by_hexdigest(question+
1519 strlen("desc-annotations/id/"));
1520 if (ri) {
1521 const char *annotations =
1522 signed_descriptor_get_annotations(&ri->cache_info);
1523 if (annotations)
1524 *answer = tor_strndup(annotations,
1525 ri->cache_info.annotations_len);
1527 } else if (!strcmpstart(question, "dir/server/")) {
1528 size_t answer_len = 0, url_len = strlen(question)+2;
1529 char *url = tor_malloc(url_len);
1530 smartlist_t *descs = smartlist_create();
1531 const char *msg;
1532 int res;
1533 char *cp;
1534 tor_snprintf(url, url_len, "/tor/%s", question+4);
1535 res = dirserv_get_routerdescs(descs, url, &msg);
1536 if (res) {
1537 log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
1538 smartlist_free(descs);
1539 return -1;
1541 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1542 answer_len += sd->signed_descriptor_len);
1543 cp = *answer = tor_malloc(answer_len+1);
1544 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1546 memcpy(cp, signed_descriptor_get_body(sd),
1547 sd->signed_descriptor_len);
1548 cp += sd->signed_descriptor_len;
1550 *cp = '\0';
1551 tor_free(url);
1552 smartlist_free(descs);
1553 } else if (!strcmpstart(question, "dir/status/")) {
1554 if (directory_permits_controller_requests(get_options())) {
1555 size_t len=0;
1556 char *cp;
1557 smartlist_t *status_list = smartlist_create();
1558 dirserv_get_networkstatus_v2(status_list,
1559 question+strlen("dir/status/"));
1560 SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
1561 cp = *answer = tor_malloc(len+1);
1562 SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
1563 memcpy(cp, d->dir, d->dir_len);
1564 cp += d->dir_len;
1566 *cp = '\0';
1567 smartlist_free(status_list);
1568 } else {
1569 smartlist_t *fp_list = smartlist_create();
1570 smartlist_t *status_list = smartlist_create();
1571 dirserv_get_networkstatus_v2_fingerprints(
1572 fp_list, question+strlen("dir/status/"));
1573 SMARTLIST_FOREACH(fp_list, const char *, fp, {
1574 char *s;
1575 char *fname = networkstatus_get_cache_filename(fp);
1576 s = read_file_to_str(fname, 0, NULL);
1577 if (s)
1578 smartlist_add(status_list, s);
1579 tor_free(fname);
1581 SMARTLIST_FOREACH(fp_list, char *, fp, tor_free(fp));
1582 smartlist_free(fp_list);
1583 *answer = smartlist_join_strings(status_list, "", 0, NULL);
1584 SMARTLIST_FOREACH(status_list, char *, s, tor_free(s));
1585 smartlist_free(status_list);
1587 } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
1588 if (directory_caches_dir_info(get_options())) {
1589 const cached_dir_t *consensus = dirserv_get_consensus();
1590 if (consensus)
1591 *answer = tor_strdup(consensus->dir);
1593 if (!*answer) { /* try loading it from disk */
1594 char *filename = get_datadir_fname("cached-consensus");
1595 *answer = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
1596 tor_free(filename);
1598 } else if (!strcmp(question, "network-status")) { /* v1 */
1599 routerlist_t *routerlist = router_get_routerlist();
1600 int verbose = control_conn->use_long_names;
1601 if (!routerlist || !routerlist->routers ||
1602 list_server_status_v1(routerlist->routers, answer,
1603 verbose ? 2 : 1) < 0) {
1604 return -1;
1606 } else if (!strcmpstart(question, "extra-info/digest/")) {
1607 question += strlen("extra-info/digest/");
1608 if (strlen(question) == HEX_DIGEST_LEN) {
1609 char d[DIGEST_LEN];
1610 signed_descriptor_t *sd = NULL;
1611 if (base16_decode(d, sizeof(d), question, strlen(question))==0) {
1612 /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
1613 * but I don't want to risk affecting other parts of the code,
1614 * especially since the rules for using our own extrainfo (including
1615 * when it might be freed) are different from those for using one
1616 * we have downloaded. */
1617 if (router_extrainfo_digest_is_me(d))
1618 sd = &(router_get_my_extrainfo()->cache_info);
1619 else
1620 sd = extrainfo_get_by_descriptor_digest(d);
1622 if (sd) {
1623 const char *body = signed_descriptor_get_body(sd);
1624 if (body)
1625 *answer = tor_strndup(body, sd->signed_descriptor_len);
1630 return 0;
1633 /** Implementation helper for GETINFO: knows how to generate summaries of the
1634 * current states of things we send events about. */
1635 static int
1636 getinfo_helper_events(control_connection_t *control_conn,
1637 const char *question, char **answer)
1639 if (!strcmp(question, "circuit-status")) {
1640 circuit_t *circ;
1641 smartlist_t *status = smartlist_create();
1642 for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
1643 char *s, *path;
1644 size_t slen;
1645 const char *state;
1646 const char *purpose;
1647 if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
1648 continue;
1649 if (control_conn->use_long_names)
1650 path = circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ));
1651 else
1652 path = circuit_list_path(TO_ORIGIN_CIRCUIT(circ),0);
1653 if (circ->state == CIRCUIT_STATE_OPEN)
1654 state = "BUILT";
1655 else if (strlen(path))
1656 state = "EXTENDED";
1657 else
1658 state = "LAUNCHED";
1660 purpose = circuit_purpose_to_controller_string(circ->purpose);
1661 slen = strlen(path)+strlen(state)+strlen(purpose)+30;
1662 s = tor_malloc(slen+1);
1663 tor_snprintf(s, slen, "%lu %s%s%s PURPOSE=%s",
1664 (unsigned long)TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1665 state, *path ? " " : "", path, purpose);
1666 smartlist_add(status, s);
1667 tor_free(path);
1669 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1670 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1671 smartlist_free(status);
1672 } else if (!strcmp(question, "stream-status")) {
1673 smartlist_t *conns = get_connection_array();
1674 smartlist_t *status = smartlist_create();
1675 char buf[256];
1676 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1677 const char *state;
1678 edge_connection_t *conn;
1679 char *s;
1680 size_t slen;
1681 circuit_t *circ;
1682 origin_circuit_t *origin_circ = NULL;
1683 if (base_conn->type != CONN_TYPE_AP ||
1684 base_conn->marked_for_close ||
1685 base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
1686 base_conn->state == AP_CONN_STATE_NATD_WAIT)
1687 continue;
1688 conn = TO_EDGE_CONN(base_conn);
1689 switch (conn->_base.state)
1691 case AP_CONN_STATE_CONTROLLER_WAIT:
1692 case AP_CONN_STATE_CIRCUIT_WAIT:
1693 if (conn->socks_request &&
1694 SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
1695 state = "NEWRESOLVE";
1696 else
1697 state = "NEW";
1698 break;
1699 case AP_CONN_STATE_RENDDESC_WAIT:
1700 case AP_CONN_STATE_CONNECT_WAIT:
1701 state = "SENTCONNECT"; break;
1702 case AP_CONN_STATE_RESOLVE_WAIT:
1703 state = "SENTRESOLVE"; break;
1704 case AP_CONN_STATE_OPEN:
1705 state = "SUCCEEDED"; break;
1706 default:
1707 log_warn(LD_BUG, "Asked for stream in unknown state %d",
1708 conn->_base.state);
1709 continue;
1711 circ = circuit_get_by_edge_conn(conn);
1712 if (circ && CIRCUIT_IS_ORIGIN(circ))
1713 origin_circ = TO_ORIGIN_CIRCUIT(circ);
1714 write_stream_target_to_buf(conn, buf, sizeof(buf));
1715 slen = strlen(buf)+strlen(state)+32;
1716 s = tor_malloc(slen+1);
1717 tor_snprintf(s, slen, "%lu %s %lu %s",
1718 (unsigned long) conn->_base.global_identifier,state,
1719 origin_circ?
1720 (unsigned long)origin_circ->global_identifier : 0ul,
1721 buf);
1722 smartlist_add(status, s);
1723 } SMARTLIST_FOREACH_END(base_conn);
1724 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1725 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1726 smartlist_free(status);
1727 } else if (!strcmp(question, "orconn-status")) {
1728 smartlist_t *conns = get_connection_array();
1729 smartlist_t *status = smartlist_create();
1730 SMARTLIST_FOREACH(conns, connection_t *, base_conn,
1732 const char *state;
1733 char *s;
1734 char name[128];
1735 size_t slen;
1736 or_connection_t *conn;
1737 if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
1738 continue;
1739 conn = TO_OR_CONN(base_conn);
1740 if (conn->_base.state == OR_CONN_STATE_OPEN)
1741 state = "CONNECTED";
1742 else if (conn->nickname)
1743 state = "LAUNCHED";
1744 else
1745 state = "NEW";
1746 orconn_target_get_name(control_conn->use_long_names, name, sizeof(name),
1747 conn);
1748 slen = strlen(name)+strlen(state)+2;
1749 s = tor_malloc(slen+1);
1750 tor_snprintf(s, slen, "%s %s", name, state);
1751 smartlist_add(status, s);
1753 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1754 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1755 smartlist_free(status);
1756 } else if (!strcmpstart(question, "addr-mappings/") ||
1757 !strcmpstart(question, "address-mappings/")) {
1758 time_t min_e, max_e;
1759 smartlist_t *mappings;
1760 int want_expiry = !strcmpstart(question, "address-mappings/");
1761 if (!strcmpstart(question, "addr-mappings/")) {
1762 /* XXXX022 This has been deprecated since 0.2.0.3-alpha, and has
1763 generated a warning since 0.2.1.10-alpha; remove late in 0.2.2.x. */
1764 log_warn(LD_CONTROL, "Controller used obsolete addr-mappings/ GETINFO "
1765 "key; use address-mappings/ instead.");
1767 question += strlen(want_expiry ? "address-mappings/"
1768 : "addr-mappings/");
1769 if (!strcmp(question, "all")) {
1770 min_e = 0; max_e = TIME_MAX;
1771 } else if (!strcmp(question, "cache")) {
1772 min_e = 2; max_e = TIME_MAX;
1773 } else if (!strcmp(question, "config")) {
1774 min_e = 0; max_e = 0;
1775 } else if (!strcmp(question, "control")) {
1776 min_e = 1; max_e = 1;
1777 } else {
1778 return 0;
1780 mappings = smartlist_create();
1781 addressmap_get_mappings(mappings, min_e, max_e, want_expiry);
1782 *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
1783 SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
1784 smartlist_free(mappings);
1785 } else if (!strcmpstart(question, "status/")) {
1786 /* Note that status/ is not a catch-all for events; there's only supposed
1787 * to be a status GETINFO if there's a corresponding STATUS event. */
1788 if (!strcmp(question, "status/circuit-established")) {
1789 *answer = tor_strdup(has_completed_circuit ? "1" : "0");
1790 } else if (!strcmp(question, "status/enough-dir-info")) {
1791 *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
1792 } else if (!strcmp(question, "status/good-server-descriptor")) {
1793 *answer = tor_strdup(directories_have_accepted_server_descriptor()
1794 ? "1" : "0");
1795 } else if (!strcmp(question, "status/reachability-succeeded/or")) {
1796 *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
1797 } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
1798 *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
1799 } else if (!strcmp(question, "status/reachability-succeeded")) {
1800 *answer = tor_malloc(16);
1801 tor_snprintf(*answer, 16, "OR=%d DIR=%d",
1802 check_whether_orport_reachable() ? 1 : 0,
1803 check_whether_dirport_reachable() ? 1 : 0);
1804 } else if (!strcmp(question, "status/bootstrap-phase")) {
1805 *answer = tor_strdup(last_sent_bootstrap_message);
1806 } else if (!strcmpstart(question, "status/version/")) {
1807 int is_server = server_mode(get_options());
1808 networkstatus_t *c = networkstatus_get_latest_consensus();
1809 version_status_t status;
1810 const char *recommended;
1811 if (c) {
1812 recommended = is_server ? c->server_versions : c->client_versions;
1813 status = tor_version_is_obsolete(VERSION, recommended);
1814 } else {
1815 recommended = "?";
1816 status = VS_UNKNOWN;
1819 if (!strcmp(question, "status/version/recommended")) {
1820 *answer = tor_strdup(recommended);
1821 return 0;
1823 if (!strcmp(question, "status/version/current")) {
1824 switch (status)
1826 case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
1827 case VS_OLD: *answer = tor_strdup("obsolete"); break;
1828 case VS_NEW: *answer = tor_strdup("new"); break;
1829 case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
1830 case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
1831 case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
1832 case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
1833 default: tor_fragile_assert();
1835 } else if (!strcmp(question, "status/version/num-versioning") ||
1836 !strcmp(question, "status/version/num-concurring")) {
1837 char s[33];
1838 tor_snprintf(s, sizeof(s), "%d", get_n_authorities(V3_AUTHORITY));
1839 *answer = tor_strdup(s);
1840 log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
1841 "information", question);
1843 } else if (!strcmp(question, "status/clients-seen")) {
1844 char geoip_start[ISO_TIME_LEN+1];
1845 size_t answer_len;
1846 char *geoip_summary = extrainfo_get_client_geoip_summary(time(NULL));
1848 if (!geoip_summary)
1849 return -1;
1851 answer_len = strlen("TimeStarted=\"\" CountrySummary=") +
1852 ISO_TIME_LEN + strlen(geoip_summary) + 1;
1853 *answer = tor_malloc(answer_len);
1854 format_iso_time(geoip_start, geoip_get_history_start());
1855 tor_snprintf(*answer, answer_len,
1856 "TimeStarted=\"%s\" CountrySummary=%s",
1857 geoip_start, geoip_summary);
1858 tor_free(geoip_summary);
1859 } else {
1860 return 0;
1863 return 0;
1866 /** Callback function for GETINFO: on a given control connection, try to
1867 * answer the question <b>q</b> and store the newly-allocated answer in
1868 * *<b>a</b>. If there's no answer, or an error occurs, just don't set
1869 * <b>a</b>. Return 0.
1871 typedef int (*getinfo_helper_t)(control_connection_t *,
1872 const char *q, char **a);
1874 /** A single item for the GETINFO question-to-answer-function table. */
1875 typedef struct getinfo_item_t {
1876 const char *varname; /**< The value (or prefix) of the question. */
1877 getinfo_helper_t fn; /**< The function that knows the answer: NULL if
1878 * this entry is documentation-only. */
1879 const char *desc; /**< Description of the variable. */
1880 int is_prefix; /** Must varname match exactly, or must it be a prefix? */
1881 } getinfo_item_t;
1883 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
1884 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
1885 #define DOC(name, desc) { name, NULL, desc, 0 }
1887 /** Table mapping questions accepted by GETINFO to the functions that know how
1888 * to answer them. */
1889 static const getinfo_item_t getinfo_items[] = {
1890 ITEM("version", misc, "The current version of Tor."),
1891 ITEM("config-file", misc, "Current location of the \"torrc\" file."),
1892 ITEM("accounting/bytes", accounting,
1893 "Number of bytes read/written so far in the accounting interval."),
1894 ITEM("accounting/bytes-left", accounting,
1895 "Number of bytes left to write/read so far in the accounting interval."),
1896 ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
1897 ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
1898 ITEM("accounting/interval-start", accounting,
1899 "Time when the accounting period starts."),
1900 ITEM("accounting/interval-end", accounting,
1901 "Time when the accounting period ends."),
1902 ITEM("accounting/interval-wake", accounting,
1903 "Time to wake up in this accounting period."),
1904 ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
1905 ITEM("entry-guards", entry_guards,
1906 "Which nodes are we using as entry guards?"),
1907 ITEM("fingerprint", misc, NULL),
1908 PREFIX("config/", config, "Current configuration values."),
1909 DOC("config/names",
1910 "List of configuration options, types, and documentation."),
1911 ITEM("info/names", misc,
1912 "List of GETINFO options, types, and documentation."),
1913 ITEM("events/names", misc,
1914 "Events that the controller can ask for with SETEVENTS."),
1915 ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
1916 PREFIX("desc/id/", dir, "Router descriptors by ID."),
1917 PREFIX("desc/name/", dir, "Router descriptors by nickname."),
1918 ITEM("desc/all-recent", dir,
1919 "All non-expired, non-superseded router descriptors."),
1920 ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
1921 PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
1922 ITEM("ns/all", networkstatus,
1923 "Brief summary of router status (v2 directory format)"),
1924 PREFIX("ns/id/", networkstatus,
1925 "Brief summary of router status by ID (v2 directory format)."),
1926 PREFIX("ns/name/", networkstatus,
1927 "Brief summary of router status by nickname (v2 directory format)."),
1928 PREFIX("ns/purpose/", networkstatus,
1929 "Brief summary of router status by purpose (v2 directory format)."),
1931 PREFIX("unregistered-servers-", dirserv_unregistered, NULL),
1932 ITEM("network-status", dir,
1933 "Brief summary of router status (v1 directory format)"),
1934 ITEM("circuit-status", events, "List of current circuits originating here."),
1935 ITEM("stream-status", events,"List of current streams."),
1936 ITEM("orconn-status", events, "A list of current OR connections."),
1937 PREFIX("address-mappings/", events, NULL),
1938 DOC("address-mappings/all", "Current address mappings."),
1939 DOC("address-mappings/cache", "Current cached DNS replies."),
1940 DOC("address-mappings/config",
1941 "Current address mappings from configuration."),
1942 DOC("address-mappings/control", "Current address mappings from controller."),
1943 PREFIX("addr-mappings/", events, NULL),
1944 DOC("addr-mappings/all", "Current address mappings without expiry times."),
1945 DOC("addr-mappings/cache",
1946 "Current cached DNS replies without expiry times."),
1947 DOC("addr-mappings/config",
1948 "Current address mappings from configuration without expiry times."),
1949 DOC("addr-mappings/control",
1950 "Current address mappings from controller without expiry times."),
1951 PREFIX("status/", events, NULL),
1952 DOC("status/circuit-established",
1953 "Whether we think client functionality is working."),
1954 DOC("status/enough-dir-info",
1955 "Whether we have enough up-to-date directory information to build "
1956 "circuits."),
1957 DOC("status/bootstrap-phase",
1958 "The last bootstrap phase status event that Tor sent."),
1959 DOC("status/clients-seen",
1960 "Breakdown of client countries seen by a bridge."),
1961 DOC("status/version/recommended", "List of currently recommended versions."),
1962 DOC("status/version/current", "Status of the current version."),
1963 DOC("status/version/num-versioning", "Number of versioning authorities."),
1964 DOC("status/version/num-concurring",
1965 "Number of versioning authorities agreeing on the status of the "
1966 "current version"),
1967 ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
1968 ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
1969 PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
1970 PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
1971 PREFIX("dir/status/", dir,
1972 "v2 networkstatus docs as retrieved from a DirPort."),
1973 ITEM("dir/status-vote/current/consensus", dir,
1974 "v3 Networkstatus consensus as retrieved from a DirPort."),
1975 PREFIX("exit-policy/default", policies,
1976 "The default value appended to the configured exit policy."),
1977 PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
1978 { NULL, NULL, NULL, 0 }
1981 /** Allocate and return a list of recognized GETINFO options. */
1982 static char *
1983 list_getinfo_options(void)
1985 int i;
1986 char buf[300];
1987 smartlist_t *lines = smartlist_create();
1988 char *ans;
1989 for (i = 0; getinfo_items[i].varname; ++i) {
1990 if (!getinfo_items[i].desc)
1991 continue;
1993 tor_snprintf(buf, sizeof(buf), "%s%s -- %s\n",
1994 getinfo_items[i].varname,
1995 getinfo_items[i].is_prefix ? "*" : "",
1996 getinfo_items[i].desc);
1997 smartlist_add(lines, tor_strdup(buf));
1999 smartlist_sort_strings(lines);
2001 ans = smartlist_join_strings(lines, "", 0, NULL);
2002 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
2003 smartlist_free(lines);
2005 return ans;
2008 /** Lookup the 'getinfo' entry <b>question</b>, and return
2009 * the answer in <b>*answer</b> (or NULL if key not recognized).
2010 * Return 0 if success or unrecognized, or -1 if recognized but
2011 * internal error. */
2012 static int
2013 handle_getinfo_helper(control_connection_t *control_conn,
2014 const char *question, char **answer)
2016 int i;
2017 *answer = NULL; /* unrecognized key by default */
2019 for (i = 0; getinfo_items[i].varname; ++i) {
2020 int match;
2021 if (getinfo_items[i].is_prefix)
2022 match = !strcmpstart(question, getinfo_items[i].varname);
2023 else
2024 match = !strcmp(question, getinfo_items[i].varname);
2025 if (match) {
2026 tor_assert(getinfo_items[i].fn);
2027 return getinfo_items[i].fn(control_conn, question, answer);
2031 return 0; /* unrecognized */
2034 /** Called when we receive a GETINFO command. Try to fetch all requested
2035 * information, and reply with information or error message. */
2036 static int
2037 handle_control_getinfo(control_connection_t *conn, uint32_t len,
2038 const char *body)
2040 smartlist_t *questions = smartlist_create();
2041 smartlist_t *answers = smartlist_create();
2042 smartlist_t *unrecognized = smartlist_create();
2043 char *msg = NULL, *ans = NULL;
2044 int i;
2045 (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
2047 smartlist_split_string(questions, body, " ",
2048 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2049 SMARTLIST_FOREACH(questions, const char *, q,
2051 if (handle_getinfo_helper(conn, q, &ans) < 0) {
2052 connection_write_str_to_buf("551 Internal error\r\n", conn);
2053 goto done;
2055 if (!ans) {
2056 smartlist_add(unrecognized, (char*)q);
2057 } else {
2058 smartlist_add(answers, tor_strdup(q));
2059 smartlist_add(answers, ans);
2062 if (smartlist_len(unrecognized)) {
2063 for (i=0; i < smartlist_len(unrecognized)-1; ++i)
2064 connection_printf_to_buf(conn,
2065 "552-Unrecognized key \"%s\"\r\n",
2066 (char*)smartlist_get(unrecognized, i));
2067 connection_printf_to_buf(conn,
2068 "552 Unrecognized key \"%s\"\r\n",
2069 (char*)smartlist_get(unrecognized, i));
2070 goto done;
2073 for (i = 0; i < smartlist_len(answers); i += 2) {
2074 char *k = smartlist_get(answers, i);
2075 char *v = smartlist_get(answers, i+1);
2076 if (!strchr(v, '\n') && !strchr(v, '\r')) {
2077 connection_printf_to_buf(conn, "250-%s=", k);
2078 connection_write_str_to_buf(v, conn);
2079 connection_write_str_to_buf("\r\n", conn);
2080 } else {
2081 char *esc = NULL;
2082 size_t esc_len;
2083 esc_len = write_escaped_data(v, strlen(v), &esc);
2084 connection_printf_to_buf(conn, "250+%s=\r\n", k);
2085 connection_write_to_buf(esc, esc_len, TO_CONN(conn));
2086 tor_free(esc);
2089 connection_write_str_to_buf("250 OK\r\n", conn);
2091 done:
2092 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
2093 smartlist_free(answers);
2094 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
2095 smartlist_free(questions);
2096 smartlist_free(unrecognized);
2097 tor_free(msg);
2099 return 0;
2102 /** Given a string, convert it to a circuit purpose. */
2103 static uint8_t
2104 circuit_purpose_from_string(const char *string)
2106 if (!strcmpstart(string, "purpose="))
2107 string += strlen("purpose=");
2109 if (!strcmp(string, "general"))
2110 return CIRCUIT_PURPOSE_C_GENERAL;
2111 else if (!strcmp(string, "controller"))
2112 return CIRCUIT_PURPOSE_CONTROLLER;
2113 else
2114 return CIRCUIT_PURPOSE_UNKNOWN;
2117 /** Return a newly allocated smartlist containing the arguments to the command
2118 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
2119 * or if <b>max_args</b> is nonnegative and there are more than
2120 * <b>max_args</b> arguments, send a 512 error to the controller, using
2121 * <b>command</b> as the command name in the error message. */
2122 static smartlist_t *
2123 getargs_helper(const char *command, control_connection_t *conn,
2124 const char *body, int min_args, int max_args)
2126 smartlist_t *args = smartlist_create();
2127 smartlist_split_string(args, body, " ",
2128 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2129 if (smartlist_len(args) < min_args) {
2130 connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
2131 goto err;
2132 } else if (max_args >= 0 && smartlist_len(args) > max_args) {
2133 connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
2134 goto err;
2136 return args;
2137 err:
2138 SMARTLIST_FOREACH(args, char *, s, tor_free(s));
2139 smartlist_free(args);
2140 return NULL;
2143 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
2144 * circuit, and report success or failure. */
2145 static int
2146 handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
2147 const char *body)
2149 smartlist_t *router_nicknames=NULL, *routers=NULL;
2150 origin_circuit_t *circ = NULL;
2151 int zero_circ;
2152 uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
2153 smartlist_t *args;
2154 (void) len;
2156 router_nicknames = smartlist_create();
2158 args = getargs_helper("EXTENDCIRCUIT", conn, body, 2, -1);
2159 if (!args)
2160 goto done;
2162 zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
2163 if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
2164 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2165 (char*)smartlist_get(args, 0));
2167 smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
2169 if (zero_circ && smartlist_len(args)>2) {
2170 char *purp = smartlist_get(args,2);
2171 intended_purpose = circuit_purpose_from_string(purp);
2172 if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
2173 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
2174 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2175 smartlist_free(args);
2176 goto done;
2179 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2180 smartlist_free(args);
2181 if (!zero_circ && !circ) {
2182 goto done;
2185 routers = smartlist_create();
2186 SMARTLIST_FOREACH(router_nicknames, const char *, n,
2188 routerinfo_t *r = router_get_by_nickname(n, 1);
2189 if (!r) {
2190 connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
2191 goto done;
2193 smartlist_add(routers, r);
2195 if (!smartlist_len(routers)) {
2196 connection_write_str_to_buf("512 No router names provided\r\n", conn);
2197 goto done;
2200 if (zero_circ) {
2201 /* start a new circuit */
2202 circ = origin_circuit_init(intended_purpose, 0);
2205 /* now circ refers to something that is ready to be extended */
2206 SMARTLIST_FOREACH(routers, routerinfo_t *, r,
2208 extend_info_t *info = extend_info_from_router(r);
2209 circuit_append_new_exit(circ, info);
2210 extend_info_free(info);
2213 /* now that we've populated the cpath, start extending */
2214 if (zero_circ) {
2215 int err_reason = 0;
2216 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
2217 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2218 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
2219 goto done;
2221 } else {
2222 if (circ->_base.state == CIRCUIT_STATE_OPEN) {
2223 int err_reason = 0;
2224 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
2225 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
2226 log_info(LD_CONTROL,
2227 "send_next_onion_skin failed; circuit marked for closing.");
2228 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2229 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
2230 goto done;
2235 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
2236 (unsigned long)circ->global_identifier);
2237 if (zero_circ) /* send a 'launched' event, for completeness */
2238 control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
2239 done:
2240 SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
2241 smartlist_free(router_nicknames);
2242 if (routers)
2243 smartlist_free(routers);
2244 return 0;
2247 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
2248 * circuit and it's a valid purpose, change it. */
2249 static int
2250 handle_control_setcircuitpurpose(control_connection_t *conn,
2251 uint32_t len, const char *body)
2253 origin_circuit_t *circ = NULL;
2254 uint8_t new_purpose;
2255 smartlist_t *args;
2256 (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
2258 args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
2259 if (!args)
2260 goto done;
2262 if (!(circ = get_circ(smartlist_get(args,0)))) {
2263 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2264 (char*)smartlist_get(args, 0));
2265 goto done;
2269 char *purp = smartlist_get(args,1);
2270 new_purpose = circuit_purpose_from_string(purp);
2271 if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
2272 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
2273 goto done;
2277 circ->_base.purpose = new_purpose;
2278 connection_write_str_to_buf("250 OK\r\n", conn);
2280 done:
2281 if (args) {
2282 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2283 smartlist_free(args);
2285 return 0;
2288 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
2289 * stream, and report success or failure. */
2290 static int
2291 handle_control_attachstream(control_connection_t *conn, uint32_t len,
2292 const char *body)
2294 edge_connection_t *ap_conn = NULL;
2295 origin_circuit_t *circ = NULL;
2296 int zero_circ;
2297 smartlist_t *args;
2298 crypt_path_t *cpath=NULL;
2299 int hop=0, hop_line_ok=1;
2300 (void) len;
2302 args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
2303 if (!args)
2304 return 0;
2306 zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
2308 if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
2309 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2310 (char*)smartlist_get(args, 0));
2311 } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
2312 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2313 (char*)smartlist_get(args, 1));
2314 } else if (circ && smartlist_len(args) > 2) {
2315 char *hopstring = smartlist_get(args, 2);
2316 if (!strcasecmpstart(hopstring, "HOP=")) {
2317 hopstring += strlen("HOP=");
2318 hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
2319 &hop_line_ok, NULL);
2320 if (!hop_line_ok) { /* broken hop line */
2321 connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
2325 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2326 smartlist_free(args);
2327 if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
2328 return 0;
2330 if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT &&
2331 ap_conn->_base.state != AP_CONN_STATE_CONNECT_WAIT &&
2332 ap_conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
2333 connection_write_str_to_buf(
2334 "555 Connection is not managed by controller.\r\n",
2335 conn);
2336 return 0;
2339 /* Do we need to detach it first? */
2340 if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT) {
2341 circuit_t *tmpcirc = circuit_get_by_edge_conn(ap_conn);
2342 connection_edge_end(ap_conn, END_STREAM_REASON_TIMEOUT);
2343 /* Un-mark it as ending, since we're going to reuse it. */
2344 ap_conn->edge_has_sent_end = 0;
2345 ap_conn->end_reason = 0;
2346 if (tmpcirc)
2347 circuit_detach_stream(tmpcirc,ap_conn);
2348 ap_conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
2351 if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
2352 connection_write_str_to_buf(
2353 "551 Can't attach stream to non-open origin circuit\r\n",
2354 conn);
2355 return 0;
2357 /* Is this a single hop circuit? */
2358 if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
2359 routerinfo_t *r = NULL;
2360 char* exit_digest;
2361 if (circ->build_state &&
2362 circ->build_state->chosen_exit &&
2363 circ->build_state->chosen_exit->identity_digest) {
2364 exit_digest = circ->build_state->chosen_exit->identity_digest;
2365 r = router_get_by_digest(exit_digest);
2367 /* Do both the client and relay allow one-hop exit circuits? */
2368 if (!r || !r->allow_single_hop_exits ||
2369 !get_options()->AllowSingleHopCircuits) {
2370 connection_write_str_to_buf(
2371 "551 Can't attach stream to this one-hop circuit.\r\n", conn);
2372 return 0;
2374 ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
2377 if (circ && hop>0) {
2378 /* find this hop in the circuit, and set cpath */
2379 cpath = circuit_get_cpath_hop(circ, hop);
2380 if (!cpath) {
2381 connection_printf_to_buf(conn,
2382 "551 Circuit doesn't have %d hops.\r\n", hop);
2383 return 0;
2386 if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
2387 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
2388 return 0;
2390 send_control_done(conn);
2391 return 0;
2394 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
2395 * descriptor, and report success or failure. */
2396 static int
2397 handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
2398 const char *body)
2400 char *desc;
2401 const char *msg=NULL;
2402 uint8_t purpose = ROUTER_PURPOSE_GENERAL;
2403 int cache = 0; /* eventually, we may switch this to 1 */
2405 char *cp = memchr(body, '\n', len);
2406 smartlist_t *args = smartlist_create();
2407 tor_assert(cp);
2408 *cp++ = '\0';
2410 smartlist_split_string(args, body, " ",
2411 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2412 SMARTLIST_FOREACH(args, char *, option,
2414 if (!strcasecmpstart(option, "purpose=")) {
2415 option += strlen("purpose=");
2416 purpose = router_purpose_from_string(option);
2417 if (purpose == ROUTER_PURPOSE_UNKNOWN) {
2418 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
2419 option);
2420 goto done;
2422 } else if (!strcasecmpstart(option, "cache=")) {
2423 option += strlen("cache=");
2424 if (!strcmp(option, "no"))
2425 cache = 0;
2426 else if (!strcmp(option, "yes"))
2427 cache = 1;
2428 else {
2429 connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
2430 option);
2431 goto done;
2433 } else { /* unrecognized argument? */
2434 connection_printf_to_buf(conn,
2435 "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
2436 goto done;
2440 read_escaped_data(cp, len-(cp-body), &desc);
2442 switch (router_load_single_router(desc, purpose, cache, &msg)) {
2443 case -1:
2444 if (!msg) msg = "Could not parse descriptor";
2445 connection_printf_to_buf(conn, "554 %s\r\n", msg);
2446 break;
2447 case 0:
2448 if (!msg) msg = "Descriptor not added";
2449 connection_printf_to_buf(conn, "251 %s\r\n",msg);
2450 break;
2451 case 1:
2452 send_control_done(conn);
2453 break;
2456 tor_free(desc);
2457 done:
2458 SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
2459 smartlist_free(args);
2460 return 0;
2463 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
2464 * address of the named AP stream, and report success or failure. */
2465 static int
2466 handle_control_redirectstream(control_connection_t *conn, uint32_t len,
2467 const char *body)
2469 edge_connection_t *ap_conn = NULL;
2470 char *new_addr = NULL;
2471 uint16_t new_port = 0;
2472 smartlist_t *args;
2473 (void) len;
2475 args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
2476 if (!args)
2477 return 0;
2479 if (!(ap_conn = get_stream(smartlist_get(args, 0)))
2480 || !ap_conn->socks_request) {
2481 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2482 (char*)smartlist_get(args, 0));
2483 } else {
2484 int ok = 1;
2485 if (smartlist_len(args) > 2) { /* they included a port too */
2486 new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
2487 10, 1, 65535, &ok, NULL);
2489 if (!ok) {
2490 connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
2491 (char*)smartlist_get(args, 2));
2492 } else {
2493 new_addr = tor_strdup(smartlist_get(args, 1));
2497 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2498 smartlist_free(args);
2499 if (!new_addr)
2500 return 0;
2502 strlcpy(ap_conn->socks_request->address, new_addr,
2503 sizeof(ap_conn->socks_request->address));
2504 if (new_port)
2505 ap_conn->socks_request->port = new_port;
2506 tor_free(new_addr);
2507 send_control_done(conn);
2508 return 0;
2511 /** Called when we get a CLOSESTREAM command; try to close the named stream
2512 * and report success or failure. */
2513 static int
2514 handle_control_closestream(control_connection_t *conn, uint32_t len,
2515 const char *body)
2517 edge_connection_t *ap_conn=NULL;
2518 uint8_t reason=0;
2519 smartlist_t *args;
2520 int ok;
2521 (void) len;
2523 args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
2524 if (!args)
2525 return 0;
2527 else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
2528 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2529 (char*)smartlist_get(args, 0));
2530 else {
2531 reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
2532 &ok, NULL);
2533 if (!ok) {
2534 connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
2535 (char*)smartlist_get(args, 1));
2536 ap_conn = NULL;
2539 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2540 smartlist_free(args);
2541 if (!ap_conn)
2542 return 0;
2544 connection_mark_unattached_ap(ap_conn, reason);
2545 send_control_done(conn);
2546 return 0;
2549 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
2550 * and report success or failure. */
2551 static int
2552 handle_control_closecircuit(control_connection_t *conn, uint32_t len,
2553 const char *body)
2555 origin_circuit_t *circ = NULL;
2556 int safe = 0;
2557 smartlist_t *args;
2558 (void) len;
2560 args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
2561 if (!args)
2562 return 0;
2564 if (!(circ=get_circ(smartlist_get(args, 0))))
2565 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2566 (char*)smartlist_get(args, 0));
2567 else {
2568 int i;
2569 for (i=1; i < smartlist_len(args); ++i) {
2570 if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
2571 safe = 1;
2572 else
2573 log_info(LD_CONTROL, "Skipping unknown option %s",
2574 (char*)smartlist_get(args,i));
2577 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2578 smartlist_free(args);
2579 if (!circ)
2580 return 0;
2582 if (!safe || !circ->p_streams) {
2583 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
2586 send_control_done(conn);
2587 return 0;
2590 /** Called when we get a RESOLVE command: start trying to resolve
2591 * the listed addresses. */
2592 static int
2593 handle_control_resolve(control_connection_t *conn, uint32_t len,
2594 const char *body)
2596 smartlist_t *args, *failed;
2597 int is_reverse = 0;
2598 (void) len; /* body is nul-terminated; it's safe to ignore the length */
2600 if (!(conn->event_mask & (1L<<EVENT_ADDRMAP))) {
2601 log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
2602 "isn't listening for ADDRMAP events. It probably won't see "
2603 "the answer.");
2605 args = smartlist_create();
2606 smartlist_split_string(args, body, " ",
2607 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2608 if (smartlist_len(args) &&
2609 !strcasecmp(smartlist_get(args, 0), "mode=reverse")) {
2610 char *cp = smartlist_get(args, 0);
2611 smartlist_del_keeporder(args, 0);
2612 tor_free(cp);
2613 is_reverse = 1;
2615 failed = smartlist_create();
2616 SMARTLIST_FOREACH(args, const char *, arg, {
2617 if (dnsserv_launch_request(arg, is_reverse)<0)
2618 smartlist_add(failed, (char*)arg);
2621 send_control_done(conn);
2622 SMARTLIST_FOREACH(failed, const char *, arg, {
2623 control_event_address_mapped(arg, arg, time(NULL),
2624 "Unable to launch resolve request");
2627 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2628 smartlist_free(args);
2629 smartlist_free(failed);
2630 return 0;
2633 /** Called when we get a PROTOCOLINFO command: send back a reply. */
2634 static int
2635 handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
2636 const char *body)
2638 const char *bad_arg = NULL;
2639 smartlist_t *args;
2640 (void)len;
2642 conn->have_sent_protocolinfo = 1;
2643 args = smartlist_create();
2644 smartlist_split_string(args, body, " ",
2645 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2646 SMARTLIST_FOREACH(args, const char *, arg, {
2647 int ok;
2648 tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
2649 if (!ok) {
2650 bad_arg = arg;
2651 break;
2654 if (bad_arg) {
2655 connection_printf_to_buf(conn, "513 No such version %s\r\n",
2656 escaped(bad_arg));
2657 /* Don't tolerate bad arguments when not authenticated. */
2658 if (!STATE_IS_OPEN(TO_CONN(conn)->state))
2659 connection_mark_for_close(TO_CONN(conn));
2660 goto done;
2661 } else {
2662 or_options_t *options = get_options();
2663 int cookies = options->CookieAuthentication;
2664 char *cfile = get_cookie_file();
2665 char *esc_cfile = esc_for_log(cfile);
2666 char *methods;
2668 int passwd = (options->HashedControlPassword != NULL ||
2669 options->HashedControlSessionPassword != NULL);
2670 smartlist_t *mlist = smartlist_create();
2671 if (cookies)
2672 smartlist_add(mlist, (char*)"COOKIE");
2673 if (passwd)
2674 smartlist_add(mlist, (char*)"HASHEDPASSWORD");
2675 if (!cookies && !passwd)
2676 smartlist_add(mlist, (char*)"NULL");
2677 methods = smartlist_join_strings(mlist, ",", 0, NULL);
2678 smartlist_free(mlist);
2681 connection_printf_to_buf(conn,
2682 "250-PROTOCOLINFO 1\r\n"
2683 "250-AUTH METHODS=%s%s%s\r\n"
2684 "250-VERSION Tor=%s\r\n"
2685 "250 OK\r\n",
2686 methods,
2687 cookies?" COOKIEFILE=":"",
2688 cookies?esc_cfile:"",
2689 escaped(VERSION));
2690 tor_free(methods);
2691 tor_free(cfile);
2692 tor_free(esc_cfile);
2694 done:
2695 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2696 smartlist_free(args);
2697 return 0;
2700 /** Called when we get a USEFEATURE command: parse the feature list, and
2701 * set up the control_connection's options properly. */
2702 static int
2703 handle_control_usefeature(control_connection_t *conn,
2704 uint32_t len,
2705 const char *body)
2707 smartlist_t *args;
2708 int verbose_names = 0, extended_events = 0;
2709 int bad = 0;
2710 (void) len; /* body is nul-terminated; it's safe to ignore the length */
2711 args = smartlist_create();
2712 smartlist_split_string(args, body, " ",
2713 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2714 SMARTLIST_FOREACH(args, const char *, arg, {
2715 if (!strcasecmp(arg, "VERBOSE_NAMES"))
2716 verbose_names = 1;
2717 else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
2718 extended_events = 1;
2719 else {
2720 connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
2721 arg);
2722 bad = 1;
2723 break;
2727 if (!bad) {
2728 if (verbose_names) {
2729 conn->use_long_names = 1;
2730 control_update_global_event_mask();
2732 if (extended_events)
2733 conn->use_extended_events = 1;
2734 send_control_done(conn);
2737 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2738 smartlist_free(args);
2739 return 0;
2742 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
2744 connection_control_finished_flushing(control_connection_t *conn)
2746 tor_assert(conn);
2748 connection_stop_writing(TO_CONN(conn));
2749 return 0;
2752 /** Called when <b>conn</b> has gotten its socket closed. */
2754 connection_control_reached_eof(control_connection_t *conn)
2756 tor_assert(conn);
2758 log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
2759 connection_mark_for_close(TO_CONN(conn));
2760 return 0;
2763 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
2764 * stage of the protocol. */
2765 static int
2766 is_valid_initial_command(control_connection_t *conn, const char *cmd)
2768 if (conn->_base.state == CONTROL_CONN_STATE_OPEN)
2769 return 1;
2770 if (!strcasecmp(cmd, "PROTOCOLINFO"))
2771 return !conn->have_sent_protocolinfo;
2772 if (!strcasecmp(cmd, "AUTHENTICATE") ||
2773 !strcasecmp(cmd, "QUIT"))
2774 return 1;
2775 return 0;
2778 /** Do not accept any control command of more than 1MB in length. Anything
2779 * that needs to be anywhere near this long probably means that one of our
2780 * interfaces is broken. */
2781 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
2783 /** Called when data has arrived on a v1 control connection: Try to fetch
2784 * commands from conn->inbuf, and execute them.
2787 connection_control_process_inbuf(control_connection_t *conn)
2789 size_t data_len;
2790 uint32_t cmd_data_len;
2791 int cmd_len;
2792 char *args;
2794 tor_assert(conn);
2795 tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN ||
2796 conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH);
2798 if (!conn->incoming_cmd) {
2799 conn->incoming_cmd = tor_malloc(1024);
2800 conn->incoming_cmd_len = 1024;
2801 conn->incoming_cmd_cur_len = 0;
2804 if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
2805 peek_buf_has_control0_command(conn->_base.inbuf)) {
2806 /* Detect v0 commands and send a "no more v0" message. */
2807 size_t body_len;
2808 char buf[128];
2809 set_uint16(buf+2, htons(0x0000)); /* type == error */
2810 set_uint16(buf+4, htons(0x0001)); /* code == internal error */
2811 strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
2812 "and later; upgrade your controller.",
2813 sizeof(buf)-6);
2814 body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
2815 set_uint16(buf+0, htons(body_len));
2816 connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
2817 connection_mark_for_close(TO_CONN(conn));
2818 conn->_base.hold_open_until_flushed = 1;
2819 return 0;
2822 again:
2823 while (1) {
2824 size_t last_idx;
2825 int r;
2826 /* First, fetch a line. */
2827 do {
2828 data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
2829 r = fetch_from_buf_line(conn->_base.inbuf,
2830 conn->incoming_cmd+conn->incoming_cmd_cur_len,
2831 &data_len);
2832 if (r == 0)
2833 /* Line not all here yet. Wait. */
2834 return 0;
2835 else if (r == -1) {
2836 if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
2837 connection_write_str_to_buf("500 Line too long.\r\n", conn);
2838 connection_stop_reading(TO_CONN(conn));
2839 connection_mark_for_close(TO_CONN(conn));
2840 conn->_base.hold_open_until_flushed = 1;
2842 while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
2843 conn->incoming_cmd_len *= 2;
2844 conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
2845 conn->incoming_cmd_len);
2847 } while (r != 1);
2849 tor_assert(data_len);
2851 last_idx = conn->incoming_cmd_cur_len;
2852 conn->incoming_cmd_cur_len += (int)data_len;
2854 /* We have appended a line to incoming_cmd. Is the command done? */
2855 if (last_idx == 0 && *conn->incoming_cmd != '+')
2856 /* One line command, didn't start with '+'. */
2857 break;
2858 /* XXXX this code duplication is kind of dumb. */
2859 if (last_idx+3 == conn->incoming_cmd_cur_len &&
2860 !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
2861 /* Just appended ".\r\n"; we're done. Remove it. */
2862 conn->incoming_cmd[last_idx] = '\0';
2863 conn->incoming_cmd_cur_len -= 3;
2864 break;
2865 } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
2866 !memcmp(conn->incoming_cmd + last_idx, ".\n", 2)) {
2867 /* Just appended ".\n"; we're done. Remove it. */
2868 conn->incoming_cmd[last_idx] = '\0';
2869 conn->incoming_cmd_cur_len -= 2;
2870 break;
2872 /* Otherwise, read another line. */
2874 data_len = conn->incoming_cmd_cur_len;
2875 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
2876 * recognize it.
2878 cmd_len = 0;
2879 while ((size_t)cmd_len < data_len
2880 && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
2881 ++cmd_len;
2883 data_len -= cmd_len;
2884 conn->incoming_cmd[cmd_len]='\0';
2885 args = conn->incoming_cmd+cmd_len+1;
2886 while (*args == ' ' || *args == '\t') {
2887 ++args;
2888 --data_len;
2891 /* Quit is always valid. */
2892 if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
2893 connection_write_str_to_buf("250 closing connection\r\n", conn);
2894 connection_mark_for_close(TO_CONN(conn));
2895 return 0;
2898 if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
2899 !is_valid_initial_command(conn, conn->incoming_cmd)) {
2900 connection_write_str_to_buf("514 Authentication required.\r\n", conn);
2901 connection_mark_for_close(TO_CONN(conn));
2902 return 0;
2905 if (data_len >= UINT32_MAX) {
2906 connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
2907 connection_mark_for_close(TO_CONN(conn));
2908 return 0;
2911 cmd_data_len = (uint32_t)data_len;
2912 if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
2913 if (handle_control_setconf(conn, cmd_data_len, args))
2914 return -1;
2915 } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
2916 if (handle_control_resetconf(conn, cmd_data_len, args))
2917 return -1;
2918 } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
2919 if (handle_control_getconf(conn, cmd_data_len, args))
2920 return -1;
2921 } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
2922 if (handle_control_loadconf(conn, cmd_data_len, args))
2923 return -1;
2924 } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
2925 if (handle_control_setevents(conn, cmd_data_len, args))
2926 return -1;
2927 } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
2928 if (handle_control_authenticate(conn, cmd_data_len, args))
2929 return -1;
2930 } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
2931 if (handle_control_saveconf(conn, cmd_data_len, args))
2932 return -1;
2933 } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
2934 if (handle_control_signal(conn, cmd_data_len, args))
2935 return -1;
2936 } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
2937 if (handle_control_mapaddress(conn, cmd_data_len, args))
2938 return -1;
2939 } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
2940 if (handle_control_getinfo(conn, cmd_data_len, args))
2941 return -1;
2942 } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
2943 if (handle_control_extendcircuit(conn, cmd_data_len, args))
2944 return -1;
2945 } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
2946 if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
2947 return -1;
2948 } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
2949 connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
2950 } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
2951 if (handle_control_attachstream(conn, cmd_data_len, args))
2952 return -1;
2953 } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
2954 if (handle_control_postdescriptor(conn, cmd_data_len, args))
2955 return -1;
2956 } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
2957 if (handle_control_redirectstream(conn, cmd_data_len, args))
2958 return -1;
2959 } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
2960 if (handle_control_closestream(conn, cmd_data_len, args))
2961 return -1;
2962 } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
2963 if (handle_control_closecircuit(conn, cmd_data_len, args))
2964 return -1;
2965 } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
2966 if (handle_control_usefeature(conn, cmd_data_len, args))
2967 return -1;
2968 } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
2969 if (handle_control_resolve(conn, cmd_data_len, args))
2970 return -1;
2971 } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
2972 if (handle_control_protocolinfo(conn, cmd_data_len, args))
2973 return -1;
2974 } else {
2975 connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
2976 conn->incoming_cmd);
2979 conn->incoming_cmd_cur_len = 0;
2980 goto again;
2983 /** Something has happened to circuit <b>circ</b>: tell any interested
2984 * control connections. */
2986 control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
2987 int reason_code)
2989 const char *status;
2990 char extended_buf[96];
2991 int providing_reason=0;
2992 char *path=NULL;
2993 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
2994 return 0;
2995 tor_assert(circ);
2997 if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS))
2998 path = circuit_list_path(circ,0);
3000 switch (tp)
3002 case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
3003 case CIRC_EVENT_BUILT: status = "BUILT"; break;
3004 case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
3005 case CIRC_EVENT_FAILED: status = "FAILED"; break;
3006 case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
3007 default:
3008 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3009 return 0;
3012 tor_snprintf(extended_buf, sizeof(extended_buf), "PURPOSE=%s",
3013 circuit_purpose_to_controller_string(circ->_base.purpose));
3015 if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
3016 const char *reason_str = circuit_end_reason_to_control_string(reason_code);
3017 char *reason = NULL;
3018 size_t n=strlen(extended_buf);
3019 providing_reason=1;
3020 if (!reason_str) {
3021 reason = tor_malloc(16);
3022 tor_snprintf(reason, 16, "UNKNOWN_%d", reason_code);
3023 reason_str = reason;
3025 if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
3026 tor_snprintf(extended_buf+n, sizeof(extended_buf)-n,
3027 " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
3028 } else {
3029 tor_snprintf(extended_buf+n, sizeof(extended_buf)-n,
3030 " REASON=%s", reason_str);
3032 tor_free(reason);
3035 if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS)) {
3036 const char *sp = strlen(path) ? " " : "";
3037 send_control_event_extended(EVENT_CIRCUIT_STATUS, SHORT_NAMES,
3038 "650 CIRC %lu %s%s%s@%s\r\n",
3039 (unsigned long)circ->global_identifier,
3040 status, sp, path, extended_buf);
3042 if (EVENT_IS_INTERESTING1L(EVENT_CIRCUIT_STATUS)) {
3043 char *vpath = circuit_list_path_for_controller(circ);
3044 const char *sp = strlen(vpath) ? " " : "";
3045 send_control_event_extended(EVENT_CIRCUIT_STATUS, LONG_NAMES,
3046 "650 CIRC %lu %s%s%s@%s\r\n",
3047 (unsigned long)circ->global_identifier,
3048 status, sp, vpath, extended_buf);
3049 tor_free(vpath);
3052 tor_free(path);
3054 return 0;
3057 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
3058 * <b>buf</b>, determine the address:port combination requested on
3059 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
3060 * failure. */
3061 static int
3062 write_stream_target_to_buf(edge_connection_t *conn, char *buf, size_t len)
3064 char buf2[256];
3065 if (conn->chosen_exit_name)
3066 if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
3067 return -1;
3068 if (!conn->socks_request)
3069 return -1;
3070 if (tor_snprintf(buf, len, "%s%s%s:%d",
3071 conn->socks_request->address,
3072 conn->chosen_exit_name ? buf2 : "",
3073 !conn->chosen_exit_name &&
3074 connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
3075 conn->socks_request->port)<0)
3076 return -1;
3077 return 0;
3080 /** Something has happened to the stream associated with AP connection
3081 * <b>conn</b>: tell any interested control connections. */
3083 control_event_stream_status(edge_connection_t *conn, stream_status_event_t tp,
3084 int reason_code)
3086 char reason_buf[64];
3087 char addrport_buf[64];
3088 const char *status;
3089 circuit_t *circ;
3090 origin_circuit_t *origin_circ = NULL;
3091 char buf[256];
3092 const char *purpose = "";
3093 tor_assert(conn->socks_request);
3095 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
3096 return 0;
3098 if (tp == STREAM_EVENT_CLOSED &&
3099 (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
3100 return 0;
3102 write_stream_target_to_buf(conn, buf, sizeof(buf));
3104 reason_buf[0] = '\0';
3105 switch (tp)
3107 case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
3108 case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
3109 case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
3110 case STREAM_EVENT_FAILED: status = "FAILED"; break;
3111 case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
3112 case STREAM_EVENT_NEW: status = "NEW"; break;
3113 case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
3114 case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
3115 case STREAM_EVENT_REMAP: status = "REMAP"; break;
3116 default:
3117 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3118 return 0;
3120 if (reason_code && (tp == STREAM_EVENT_FAILED ||
3121 tp == STREAM_EVENT_CLOSED ||
3122 tp == STREAM_EVENT_FAILED_RETRIABLE)) {
3123 const char *reason_str = stream_end_reason_to_control_string(reason_code);
3124 char *r = NULL;
3125 if (!reason_str) {
3126 r = tor_malloc(16);
3127 tor_snprintf(r, 16, "UNKNOWN_%d", reason_code);
3128 reason_str = r;
3130 if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
3131 tor_snprintf(reason_buf, sizeof(reason_buf),
3132 "REASON=END REMOTE_REASON=%s", reason_str);
3133 else
3134 tor_snprintf(reason_buf, sizeof(reason_buf),
3135 "REASON=%s", reason_str);
3136 tor_free(r);
3137 } else if (reason_code && tp == STREAM_EVENT_REMAP) {
3138 switch (reason_code) {
3139 case REMAP_STREAM_SOURCE_CACHE:
3140 strlcpy(reason_buf, "SOURCE=CACHE", sizeof(reason_buf));
3141 break;
3142 case REMAP_STREAM_SOURCE_EXIT:
3143 strlcpy(reason_buf, "SOURCE=EXIT", sizeof(reason_buf));
3144 break;
3145 default:
3146 tor_snprintf(reason_buf, sizeof(reason_buf), "REASON=UNKNOWN_%d",
3147 reason_code);
3148 /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
3149 break;
3153 if (tp == STREAM_EVENT_NEW) {
3154 tor_snprintf(addrport_buf,sizeof(addrport_buf), "%sSOURCE_ADDR=%s:%d",
3155 strlen(reason_buf) ? " " : "",
3156 TO_CONN(conn)->address, TO_CONN(conn)->port );
3157 } else {
3158 addrport_buf[0] = '\0';
3161 if (tp == STREAM_EVENT_NEW_RESOLVE) {
3162 purpose = " PURPOSE=DNS_REQUEST";
3163 } else if (tp == STREAM_EVENT_NEW) {
3164 if (conn->is_dns_request ||
3165 (conn->socks_request &&
3166 SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)))
3167 purpose = " PURPOSE=DNS_REQUEST";
3168 else if (conn->use_begindir) {
3169 connection_t *linked = TO_CONN(conn)->linked_conn;
3170 int linked_dir_purpose = -1;
3171 if (linked && linked->type == CONN_TYPE_DIR)
3172 linked_dir_purpose = linked->purpose;
3173 if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
3174 purpose = " PURPOSE=DIR_UPLOAD";
3175 else
3176 purpose = " PURPOSE=DIR_FETCH";
3177 } else
3178 purpose = " PURPOSE=USER";
3181 circ = circuit_get_by_edge_conn(conn);
3182 if (circ && CIRCUIT_IS_ORIGIN(circ))
3183 origin_circ = TO_ORIGIN_CIRCUIT(circ);
3184 send_control_event_extended(EVENT_STREAM_STATUS, ALL_NAMES,
3185 "650 STREAM "U64_FORMAT" %s %lu %s@%s%s%s\r\n",
3186 U64_PRINTF_ARG(conn->_base.global_identifier), status,
3187 origin_circ?
3188 (unsigned long)origin_circ->global_identifier : 0ul,
3189 buf, reason_buf, addrport_buf, purpose);
3191 /* XXX need to specify its intended exit, etc? */
3193 return 0;
3196 /** Figure out the best name for the target router of an OR connection
3197 * <b>conn</b>, and write it into the <b>len</b>-character buffer
3198 * <b>name</b>. Use verbose names if <b>long_names</b> is set. */
3199 static void
3200 orconn_target_get_name(int long_names,
3201 char *name, size_t len, or_connection_t *conn)
3203 if (! long_names) {
3204 if (conn->nickname)
3205 strlcpy(name, conn->nickname, len);
3206 else
3207 tor_snprintf(name, len, "%s:%d",
3208 conn->_base.address, conn->_base.port);
3209 } else {
3210 routerinfo_t *ri = router_get_by_digest(conn->identity_digest);
3211 if (ri) {
3212 tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
3213 router_get_verbose_nickname(name, ri);
3214 } else if (! tor_digest_is_zero(conn->identity_digest)) {
3215 name[0] = '$';
3216 base16_encode(name+1, len-1, conn->identity_digest,
3217 DIGEST_LEN);
3218 } else {
3219 tor_snprintf(name, len, "%s:%d",
3220 conn->_base.address, conn->_base.port);
3225 /** Called when the status of an OR connection <b>conn</b> changes: tell any
3226 * interested control connections. <b>tp</b> is the new status for the
3227 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
3228 * may be the reason why.
3231 control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
3232 int reason)
3234 int ncircs = 0;
3235 const char *status;
3236 char name[128];
3237 char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
3239 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
3240 return 0;
3242 switch (tp)
3244 case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
3245 case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
3246 case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
3247 case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
3248 case OR_CONN_EVENT_NEW: status = "NEW"; break;
3249 default:
3250 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3251 return 0;
3253 ncircs = circuit_count_pending_on_or_conn(conn);
3254 ncircs += conn->n_circuits;
3255 if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
3256 tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
3257 reason ? " " : "", ncircs);
3260 if (EVENT_IS_INTERESTING1S(EVENT_OR_CONN_STATUS)) {
3261 orconn_target_get_name(0, name, sizeof(name), conn);
3262 send_control_event_extended(EVENT_OR_CONN_STATUS, SHORT_NAMES,
3263 "650 ORCONN %s %s@%s%s%s\r\n",
3264 name, status,
3265 reason ? "REASON=" : "",
3266 orconn_end_reason_to_control_string(reason),
3267 ncircs_buf);
3269 if (EVENT_IS_INTERESTING1L(EVENT_OR_CONN_STATUS)) {
3270 orconn_target_get_name(1, name, sizeof(name), conn);
3271 send_control_event_extended(EVENT_OR_CONN_STATUS, LONG_NAMES,
3272 "650 ORCONN %s %s@%s%s%s\r\n",
3273 name, status,
3274 reason ? "REASON=" : "",
3275 orconn_end_reason_to_control_string(reason),
3276 ncircs_buf);
3279 return 0;
3282 /** A second or more has elapsed: tell any interested control
3283 * connections how much bandwidth streams have used. */
3285 control_event_stream_bandwidth_used(void)
3287 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
3288 smartlist_t *conns = get_connection_array();
3289 edge_connection_t *edge_conn;
3291 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
3293 if (conn->type != CONN_TYPE_AP)
3294 continue;
3295 edge_conn = TO_EDGE_CONN(conn);
3296 if (!edge_conn->n_read && !edge_conn->n_written)
3297 continue;
3299 send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_NAMES,
3300 "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
3301 U64_PRINTF_ARG(edge_conn->_base.global_identifier),
3302 (unsigned long)edge_conn->n_read,
3303 (unsigned long)edge_conn->n_written);
3305 edge_conn->n_written = edge_conn->n_read = 0;
3307 SMARTLIST_FOREACH_END(conn);
3310 return 0;
3313 /** A second or more has elapsed: tell any interested control
3314 * connections how much bandwidth we used. */
3316 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
3318 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
3319 send_control_event(EVENT_BANDWIDTH_USED, ALL_NAMES,
3320 "650 BW %lu %lu\r\n",
3321 (unsigned long)n_read,
3322 (unsigned long)n_written);
3325 return 0;
3328 /** Called when we are sending a log message to the controllers: suspend
3329 * sending further log messages to the controllers until we're done. Used by
3330 * CONN_LOG_PROTECT. */
3331 void
3332 disable_control_logging(void)
3334 ++disable_log_messages;
3337 /** We're done sending a log message to the controllers: re-enable controller
3338 * logging. Used by CONN_LOG_PROTECT. */
3339 void
3340 enable_control_logging(void)
3342 if (--disable_log_messages < 0)
3343 tor_assert(0);
3346 /** We got a log message: tell any interested control connections. */
3347 void
3348 control_event_logmsg(int severity, uint32_t domain, const char *msg)
3350 int event;
3352 if (disable_log_messages)
3353 return;
3355 if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
3356 severity <= LOG_NOTICE) {
3357 char *esc = esc_for_log(msg);
3358 ++disable_log_messages;
3359 control_event_general_status(severity, "BUG REASON=\"%s\"", esc);
3360 --disable_log_messages;
3361 tor_free(esc);
3364 event = log_severity_to_event(severity);
3365 if (event >= 0 && EVENT_IS_INTERESTING(event)) {
3366 char *b = NULL;
3367 const char *s;
3368 if (strchr(msg, '\n')) {
3369 char *cp;
3370 b = tor_strdup(msg);
3371 for (cp = b; *cp; ++cp)
3372 if (*cp == '\r' || *cp == '\n')
3373 *cp = ' ';
3375 switch (severity) {
3376 case LOG_DEBUG: s = "DEBUG"; break;
3377 case LOG_INFO: s = "INFO"; break;
3378 case LOG_NOTICE: s = "NOTICE"; break;
3379 case LOG_WARN: s = "WARN"; break;
3380 case LOG_ERR: s = "ERR"; break;
3381 default: s = "UnknownLogSeverity"; break;
3383 ++disable_log_messages;
3384 send_control_event(event, ALL_NAMES, "650 %s %s\r\n", s, b?b:msg);
3385 --disable_log_messages;
3386 tor_free(b);
3390 /** Called whenever we receive new router descriptors: tell any
3391 * interested control connections. <b>routers</b> is a list of
3392 * routerinfo_t's.
3395 control_event_descriptors_changed(smartlist_t *routers)
3397 size_t len;
3398 char *msg;
3399 smartlist_t *identities = NULL;
3400 char buf[HEX_DIGEST_LEN+1];
3402 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
3403 return 0;
3404 if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC)) {
3405 identities = smartlist_create();
3406 SMARTLIST_FOREACH(routers, routerinfo_t *, r,
3408 base16_encode(buf,sizeof(buf),r->cache_info.identity_digest,DIGEST_LEN);
3409 smartlist_add(identities, tor_strdup(buf));
3412 if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC)) {
3413 char *ids = smartlist_join_strings(identities, " ", 0, &len);
3414 size_t ids_len = strlen(ids)+32;
3415 msg = tor_malloc(ids_len);
3416 tor_snprintf(msg, ids_len, "650 NEWDESC %s\r\n", ids);
3417 send_control_event_string(EVENT_NEW_DESC, SHORT_NAMES|ALL_FORMATS, msg);
3418 tor_free(ids);
3419 tor_free(msg);
3421 if (EVENT_IS_INTERESTING1L(EVENT_NEW_DESC)) {
3422 smartlist_t *names = smartlist_create();
3423 char *ids;
3424 size_t names_len;
3425 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
3426 char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
3427 router_get_verbose_nickname(b, ri);
3428 smartlist_add(names, b);
3430 ids = smartlist_join_strings(names, " ", 0, &names_len);
3431 names_len = strlen(ids)+32;
3432 msg = tor_malloc(names_len);
3433 tor_snprintf(msg, names_len, "650 NEWDESC %s\r\n", ids);
3434 send_control_event_string(EVENT_NEW_DESC, LONG_NAMES|ALL_FORMATS, msg);
3435 tor_free(ids);
3436 tor_free(msg);
3437 SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
3438 smartlist_free(names);
3440 if (identities) {
3441 SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
3442 smartlist_free(identities);
3444 return 0;
3447 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
3448 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
3449 * <b>error</b> is non-NULL, it is an error code describing the failure
3450 * mode of the mapping.
3453 control_event_address_mapped(const char *from, const char *to, time_t expires,
3454 const char *error)
3456 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
3457 return 0;
3459 if (expires < 3 || expires == TIME_MAX)
3460 send_control_event_extended(EVENT_ADDRMAP, ALL_NAMES,
3461 "650 ADDRMAP %s %s NEVER@%s\r\n", from, to,
3462 error?error:"");
3463 else {
3464 char buf[ISO_TIME_LEN+1];
3465 char buf2[ISO_TIME_LEN+1];
3466 format_local_iso_time(buf,expires);
3467 format_iso_time(buf2,expires);
3468 send_control_event_extended(EVENT_ADDRMAP, ALL_NAMES,
3469 "650 ADDRMAP %s %s \"%s\""
3470 "@%s%sEXPIRES=\"%s\"\r\n",
3471 from, to, buf,
3472 error?error:"", error?" ":"",
3473 buf2);
3476 return 0;
3479 /** The authoritative dirserver has received a new descriptor that
3480 * has passed basic syntax checks and is properly self-signed.
3482 * Notify any interested party of the new descriptor and what has
3483 * been done with it, and also optionally give an explanation/reason. */
3485 control_event_or_authdir_new_descriptor(const char *action,
3486 const char *desc, size_t desclen,
3487 const char *msg)
3489 char firstline[1024];
3490 char *buf;
3491 size_t totallen;
3492 char *esc = NULL;
3493 size_t esclen;
3495 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
3496 return 0;
3498 tor_snprintf(firstline, sizeof(firstline),
3499 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
3500 action,
3501 msg ? msg : "");
3503 /* Escape the server descriptor properly */
3504 esclen = write_escaped_data(desc, desclen, &esc);
3506 totallen = strlen(firstline) + esclen + 1;
3507 buf = tor_malloc(totallen);
3508 strlcpy(buf, firstline, totallen);
3509 strlcpy(buf+strlen(firstline), esc, totallen);
3510 send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_NAMES|ALL_FORMATS,
3511 buf);
3512 send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_NAMES|ALL_FORMATS,
3513 "650 OK\r\n");
3514 tor_free(esc);
3515 tor_free(buf);
3517 return 0;
3520 /** Helper function for NS-style events. Constructs and sends an event
3521 * of type <b>event</b> with string <b>event_string</b> out of the set of
3522 * networkstatuses <b>statuses</b>. Currently it is used for NS events
3523 * and NEWCONSENSUS events. */
3524 static int
3525 control_event_networkstatus_changed_helper(smartlist_t *statuses,
3526 uint16_t event,
3527 const char *event_string)
3529 smartlist_t *strs;
3530 char *s, *esc = NULL;
3531 if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
3532 return 0;
3534 strs = smartlist_create();
3535 smartlist_add(strs, tor_strdup("650+"));
3536 smartlist_add(strs, tor_strdup(event_string));
3537 smartlist_add(strs, tor_strdup("\r\n"));
3538 SMARTLIST_FOREACH(statuses, routerstatus_t *, rs,
3540 s = networkstatus_getinfo_helper_single(rs);
3541 if (!s) continue;
3542 smartlist_add(strs, s);
3545 s = smartlist_join_strings(strs, "", 0, NULL);
3546 write_escaped_data(s, strlen(s), &esc);
3547 SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
3548 smartlist_free(strs);
3549 tor_free(s);
3550 send_control_event_string(event, ALL_NAMES|ALL_FORMATS, esc);
3551 send_control_event_string(event, ALL_NAMES|ALL_FORMATS,
3552 "650 OK\r\n");
3554 tor_free(esc);
3555 return 0;
3558 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
3559 * an NS event to any controller that cares. */
3561 control_event_networkstatus_changed(smartlist_t *statuses)
3563 return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
3566 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
3567 * event consisting of an NS-style line for each relay in the consensus. */
3569 control_event_newconsensus(const networkstatus_t *consensus)
3571 if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
3572 return 0;
3573 return control_event_networkstatus_changed_helper(
3574 consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
3577 /** Called when a single local_routerstatus_t has changed: Sends an NS event
3578 * to any countroller that cares. */
3580 control_event_networkstatus_changed_single(routerstatus_t *rs)
3582 smartlist_t *statuses;
3583 int r;
3585 if (!EVENT_IS_INTERESTING(EVENT_NS))
3586 return 0;
3588 statuses = smartlist_create();
3589 smartlist_add(statuses, rs);
3590 r = control_event_networkstatus_changed(statuses);
3591 smartlist_free(statuses);
3592 return r;
3595 /** Our own router descriptor has changed; tell any controllers that care.
3598 control_event_my_descriptor_changed(void)
3600 send_control_event(EVENT_DESCCHANGED, ALL_NAMES, "650 DESCCHANGED\r\n");
3601 return 0;
3604 /** Helper: sends a status event where <b>type</b> is one of
3605 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
3606 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
3607 * string corresponding to <b>args</b>. */
3608 static int
3609 control_event_status(int type, int severity, const char *format, va_list args)
3611 char format_buf[160];
3612 const char *status, *sev;
3614 switch (type) {
3615 case EVENT_STATUS_GENERAL:
3616 status = "STATUS_GENERAL";
3617 break;
3618 case EVENT_STATUS_CLIENT:
3619 status = "STATUS_CLIENT";
3620 break;
3621 case EVENT_STATUS_SERVER:
3622 status = "STATUS_SERVER";
3623 break;
3624 default:
3625 log_warn(LD_BUG, "Unrecognized status type %d", type);
3626 return -1;
3628 switch (severity) {
3629 case LOG_NOTICE:
3630 sev = "NOTICE";
3631 break;
3632 case LOG_WARN:
3633 sev = "WARN";
3634 break;
3635 case LOG_ERR:
3636 sev = "ERR";
3637 break;
3638 default:
3639 log_warn(LD_BUG, "Unrecognized status severity %d", severity);
3640 return -1;
3642 if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s %s\r\n",
3643 status, sev, format)<0) {
3644 log_warn(LD_BUG, "Format string too long.");
3645 return -1;
3648 send_control_event_impl(type, ALL_NAMES|ALL_FORMATS, 0, format_buf, args);
3649 return 0;
3652 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
3653 * by formatting the arguments using the printf-style <b>format</b>. */
3655 control_event_general_status(int severity, const char *format, ...)
3657 va_list ap;
3658 int r;
3659 if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
3660 return 0;
3662 va_start(ap, format);
3663 r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
3664 va_end(ap);
3665 return r;
3668 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
3669 * by formatting the arguments using the printf-style <b>format</b>. */
3671 control_event_client_status(int severity, const char *format, ...)
3673 va_list ap;
3674 int r;
3675 if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
3676 return 0;
3678 va_start(ap, format);
3679 r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
3680 va_end(ap);
3681 return r;
3684 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
3685 * by formatting the arguments using the printf-style <b>format</b>. */
3687 control_event_server_status(int severity, const char *format, ...)
3689 va_list ap;
3690 int r;
3691 if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
3692 return 0;
3694 va_start(ap, format);
3695 r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
3696 va_end(ap);
3697 return r;
3700 /** Called when the status of an entry guard with the given <b>nickname</b>
3701 * and identity <b>digest</b> has changed to <b>status</b>: tells any
3702 * controllers that care. */
3704 control_event_guard(const char *nickname, const char *digest,
3705 const char *status)
3707 char hbuf[HEX_DIGEST_LEN+1];
3708 base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
3709 if (!EVENT_IS_INTERESTING(EVENT_GUARD))
3710 return 0;
3712 if (EVENT_IS_INTERESTING1L(EVENT_GUARD)) {
3713 char buf[MAX_VERBOSE_NICKNAME_LEN+1];
3714 routerinfo_t *ri = router_get_by_digest(digest);
3715 if (ri) {
3716 router_get_verbose_nickname(buf, ri);
3717 } else {
3718 tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
3720 send_control_event(EVENT_GUARD, LONG_NAMES,
3721 "650 GUARD ENTRY %s %s\r\n", buf, status);
3723 if (EVENT_IS_INTERESTING1S(EVENT_GUARD)) {
3724 send_control_event(EVENT_GUARD, SHORT_NAMES,
3725 "650 GUARD ENTRY $%s %s\r\n", hbuf, status);
3727 return 0;
3730 /** Helper: Return a newly allocated string containing a path to the
3731 * file where we store our authentication cookie. */
3732 static char *
3733 get_cookie_file(void)
3735 or_options_t *options = get_options();
3736 if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
3737 return tor_strdup(options->CookieAuthFile);
3738 } else {
3739 return get_datadir_fname("control_auth_cookie");
3743 /** Choose a random authentication cookie and write it to disk.
3744 * Anybody who can read the cookie from disk will be considered
3745 * authorized to use the control connection. Return -1 if we can't
3746 * write the file, or 0 on success. */
3748 init_cookie_authentication(int enabled)
3750 char *fname;
3751 if (!enabled) {
3752 authentication_cookie_is_set = 0;
3753 return 0;
3756 /* We don't want to generate a new cookie every time we call
3757 * options_act(). One should be enough. */
3758 if (authentication_cookie_is_set)
3759 return 0; /* all set */
3761 fname = get_cookie_file();
3762 crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
3763 authentication_cookie_is_set = 1;
3764 if (write_bytes_to_file(fname, authentication_cookie,
3765 AUTHENTICATION_COOKIE_LEN, 1)) {
3766 log_warn(LD_FS,"Error writing authentication cookie to %s.",
3767 escaped(fname));
3768 tor_free(fname);
3769 return -1;
3771 #ifndef MS_WINDOWS
3772 if (get_options()->CookieAuthFileGroupReadable) {
3773 if (chmod(fname, 0640)) {
3774 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
3777 #endif
3779 tor_free(fname);
3780 return 0;
3783 /** Convert the name of a bootstrapping phase <b>s</b> into strings
3784 * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
3785 static int
3786 bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
3787 const char **summary)
3789 switch (s) {
3790 case BOOTSTRAP_STATUS_UNDEF:
3791 *tag = "undef";
3792 *summary = "Undefined";
3793 break;
3794 case BOOTSTRAP_STATUS_STARTING:
3795 *tag = "starting";
3796 *summary = "Starting";
3797 break;
3798 case BOOTSTRAP_STATUS_CONN_DIR:
3799 *tag = "conn_dir";
3800 *summary = "Connecting to directory server";
3801 break;
3802 case BOOTSTRAP_STATUS_HANDSHAKE:
3803 *tag = "status_handshake";
3804 *summary = "Finishing handshake";
3805 break;
3806 case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
3807 *tag = "handshake_dir";
3808 *summary = "Finishing handshake with directory server";
3809 break;
3810 case BOOTSTRAP_STATUS_ONEHOP_CREATE:
3811 *tag = "onehop_create";
3812 *summary = "Establishing an encrypted directory connection";
3813 break;
3814 case BOOTSTRAP_STATUS_REQUESTING_STATUS:
3815 *tag = "requesting_status";
3816 *summary = "Asking for networkstatus consensus";
3817 break;
3818 case BOOTSTRAP_STATUS_LOADING_STATUS:
3819 *tag = "loading_status";
3820 *summary = "Loading networkstatus consensus";
3821 break;
3822 case BOOTSTRAP_STATUS_LOADING_KEYS:
3823 *tag = "loading_keys";
3824 *summary = "Loading authority key certs";
3825 break;
3826 case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
3827 *tag = "requesting_descriptors";
3828 *summary = "Asking for relay descriptors";
3829 break;
3830 case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
3831 *tag = "loading_descriptors";
3832 *summary = "Loading relay descriptors";
3833 break;
3834 case BOOTSTRAP_STATUS_CONN_OR:
3835 *tag = "conn_or";
3836 *summary = "Connecting to the Tor network";
3837 break;
3838 case BOOTSTRAP_STATUS_HANDSHAKE_OR:
3839 *tag = "handshake_or";
3840 *summary = "Finishing handshake with first hop";
3841 break;
3842 case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
3843 *tag = "circuit_create";
3844 *summary = "Establishing a Tor circuit";
3845 break;
3846 case BOOTSTRAP_STATUS_DONE:
3847 *tag = "done";
3848 *summary = "Done";
3849 break;
3850 default:
3851 // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
3852 *tag = *summary = "unknown";
3853 return -1;
3855 return 0;
3858 /** What percentage through the bootstrap process are we? We remember
3859 * this so we can avoid sending redundant bootstrap status events, and
3860 * so we can guess context for the bootstrap messages which are
3861 * ambiguous. It starts at 'undef', but gets set to 'starting' while
3862 * Tor initializes. */
3863 static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
3865 /** How many problems have we had getting to the next bootstrapping phase?
3866 * These include failure to establish a connection to a Tor relay,
3867 * failures to finish the TLS handshake, failures to validate the
3868 * consensus document, etc. */
3869 static int bootstrap_problems = 0;
3871 /* We only tell the controller once we've hit a threshold of problems
3872 * for the current phase. */
3873 #define BOOTSTRAP_PROBLEM_THRESHOLD 10
3875 /** Called when Tor has made progress at bootstrapping its directory
3876 * information and initial circuits.
3878 * <b>status</b> is the new status, that is, what task we will be doing
3879 * next. <b>percent</b> is zero if we just started this task, else it
3880 * represents progress on the task. */
3881 void
3882 control_event_bootstrap(bootstrap_status_t status, int progress)
3884 const char *tag, *summary;
3885 char buf[BOOTSTRAP_MSG_LEN];
3887 if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
3888 return; /* already bootstrapped; nothing to be done here. */
3890 /* special case for handshaking status, since our TLS handshaking code
3891 * can't distinguish what the connection is going to be for. */
3892 if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
3893 if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
3894 status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
3895 } else {
3896 status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
3900 if (status > bootstrap_percent ||
3901 (progress && progress > bootstrap_percent)) {
3902 bootstrap_status_to_string(status, &tag, &summary);
3903 log(status ? LOG_NOTICE : LOG_INFO, LD_CONTROL,
3904 "Bootstrapped %d%%: %s.", progress ? progress : status, summary);
3905 tor_snprintf(buf, sizeof(buf),
3906 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
3907 progress ? progress : status, tag, summary);
3908 tor_snprintf(last_sent_bootstrap_message,
3909 sizeof(last_sent_bootstrap_message),
3910 "NOTICE %s", buf);
3911 control_event_client_status(LOG_NOTICE, "%s", buf);
3912 if (status > bootstrap_percent) {
3913 bootstrap_percent = status; /* new milestone reached */
3915 if (progress > bootstrap_percent) {
3916 /* incremental progress within a milestone */
3917 bootstrap_percent = progress;
3918 bootstrap_problems = 0; /* Progress! Reset our problem counter. */
3923 /** Called when Tor has failed to make bootstrapping progress in a way
3924 * that indicates a problem. <b>warn</b> gives a hint as to why, and
3925 * <b>reason</b> provides an "or_conn_end_reason" tag.
3927 void
3928 control_event_bootstrap_problem(const char *warn, int reason)
3930 int status = bootstrap_percent;
3931 const char *tag, *summary;
3932 char buf[BOOTSTRAP_MSG_LEN];
3933 const char *recommendation = "ignore";
3935 if (bootstrap_percent == 100)
3936 return; /* already bootstrapped; nothing to be done here. */
3938 bootstrap_problems++;
3940 if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
3941 recommendation = "warn";
3943 if (reason == END_OR_CONN_REASON_NO_ROUTE)
3944 recommendation = "warn";
3946 if (get_options()->UseBridges &&
3947 !any_bridge_descriptors_known() &&
3948 !any_pending_bridge_descriptor_fetches())
3949 recommendation = "warn";
3951 while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
3952 status--; /* find a recognized status string based on current progress */
3953 status = bootstrap_percent; /* set status back to the actual number */
3955 log_fn(!strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO,
3956 LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
3957 "count %d; recommendation %s)",
3958 status, summary, warn,
3959 orconn_end_reason_to_control_string(reason),
3960 bootstrap_problems, recommendation);
3961 tor_snprintf(buf, sizeof(buf),
3962 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
3963 "COUNT=%d RECOMMENDATION=%s",
3964 bootstrap_percent, tag, summary, warn,
3965 orconn_end_reason_to_control_string(reason), bootstrap_problems,
3966 recommendation);
3967 tor_snprintf(last_sent_bootstrap_message,
3968 sizeof(last_sent_bootstrap_message),
3969 "WARN %s", buf);
3970 control_event_client_status(LOG_WARN, "%s", buf);
3973 /** We just generated a new summary of which countries we've seen clients
3974 * from recently. Send a copy to the controller in case it wants to
3975 * display it for the user. */
3976 void
3977 control_event_clients_seen(const char *timestarted, const char *countries)
3979 send_control_event(EVENT_CLIENTS_SEEN, 0,
3980 "650 CLIENTS_SEEN TimeStarted=\"%s\" CountrySummary=%s\r\n",
3981 timestarted, countries);