1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2011, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
7 * \brief Implementation for Tor's control-socket interface.
8 * See doc/spec/control-spec.txt for full details on protocol.
11 #define CONTROL_PRIVATE
15 #include "circuitbuild.h"
16 #include "circuitlist.h"
17 #include "circuituse.h"
19 #include "connection.h"
20 #include "connection_edge.h"
22 #include "directory.h"
26 #include "hibernate.h"
28 #include "networkstatus.h"
32 #include "routerlist.h"
33 #include "routerparse.h"
35 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
36 * finished authentication and is accepting commands. */
37 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
39 /* Recognized asynchronous event types. It's okay to expand this list
40 * because it is used both as a list of v0 event types, and as indices
41 * into the bitfield to determine which controllers want which events.
43 #define _EVENT_MIN 0x0001
44 #define EVENT_CIRCUIT_STATUS 0x0001
45 #define EVENT_STREAM_STATUS 0x0002
46 #define EVENT_OR_CONN_STATUS 0x0003
47 #define EVENT_BANDWIDTH_USED 0x0004
48 #define EVENT_LOG_OBSOLETE 0x0005 /* Can reclaim this. */
49 #define EVENT_NEW_DESC 0x0006
50 #define EVENT_DEBUG_MSG 0x0007
51 #define EVENT_INFO_MSG 0x0008
52 #define EVENT_NOTICE_MSG 0x0009
53 #define EVENT_WARN_MSG 0x000A
54 #define EVENT_ERR_MSG 0x000B
55 #define EVENT_ADDRMAP 0x000C
56 // #define EVENT_AUTHDIR_NEWDESCS 0x000D
57 #define EVENT_DESCCHANGED 0x000E
58 // #define EVENT_NS 0x000F
59 #define EVENT_STATUS_CLIENT 0x0010
60 #define EVENT_STATUS_SERVER 0x0011
61 #define EVENT_STATUS_GENERAL 0x0012
62 #define EVENT_GUARD 0x0013
63 #define EVENT_STREAM_BANDWIDTH_USED 0x0014
64 #define EVENT_CLIENTS_SEEN 0x0015
65 #define EVENT_NEWCONSENSUS 0x0016
66 #define EVENT_BUILDTIMEOUT_SET 0x0017
67 #define _EVENT_MAX 0x0017
68 /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
70 /** Bitfield: The bit 1<<e is set if <b>any</b> open control
71 * connection is interested in events of type <b>e</b>. We use this
72 * so that we can decide to skip generating event messages that nobody
73 * has interest in without having to walk over the global connection
76 typedef uint32_t event_mask_t
;
78 /** An event mask of all the events that any controller is interested in
80 static event_mask_t global_event_mask
= 0;
82 /** True iff we have disabled log messages from being sent to the controller */
83 static int disable_log_messages
= 0;
85 /** Macro: true if any control connection is interested in events of type
87 #define EVENT_IS_INTERESTING(e) \
88 (global_event_mask & (1<<(e)))
90 /** If we're using cookie-type authentication, how long should our cookies be?
92 #define AUTHENTICATION_COOKIE_LEN 32
94 /** If true, we've set authentication_cookie to a secret code and
95 * stored it to disk. */
96 static int authentication_cookie_is_set
= 0;
97 /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
98 * and which we're using to authenticate controllers. (If the controller can
99 * read it off disk, it has permission to connect. */
100 static char authentication_cookie
[AUTHENTICATION_COOKIE_LEN
];
102 /** A sufficiently large size to record the last bootstrap phase string. */
103 #define BOOTSTRAP_MSG_LEN 1024
105 /** What was the last bootstrap phase message we sent? We keep track
106 * of this so we can respond to getinfo status/bootstrap-phase queries. */
107 static char last_sent_bootstrap_message
[BOOTSTRAP_MSG_LEN
];
109 /** Flag for event_format_t. Indicates that we should use the one standard
112 #define ALL_FORMATS 1
114 /** Bit field of flags to select how to format a controller event. Recognized
115 * flag is ALL_FORMATS. */
116 typedef int event_format_t
;
118 static void connection_printf_to_buf(control_connection_t
*conn
,
119 const char *format
, ...)
121 static void send_control_done(control_connection_t
*conn
);
122 static void send_control_event(uint16_t event
, event_format_t which
,
123 const char *format
, ...)
125 static int handle_control_setconf(control_connection_t
*conn
, uint32_t len
,
127 static int handle_control_resetconf(control_connection_t
*conn
, uint32_t len
,
129 static int handle_control_getconf(control_connection_t
*conn
, uint32_t len
,
131 static int handle_control_loadconf(control_connection_t
*conn
, uint32_t len
,
133 static int handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
135 static int handle_control_authenticate(control_connection_t
*conn
,
138 static int handle_control_signal(control_connection_t
*conn
, uint32_t len
,
140 static int handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
142 static char *list_getinfo_options(void);
143 static int handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
145 static int handle_control_extendcircuit(control_connection_t
*conn
,
148 static int handle_control_setcircuitpurpose(control_connection_t
*conn
,
149 uint32_t len
, const char *body
);
150 static int handle_control_attachstream(control_connection_t
*conn
,
153 static int handle_control_postdescriptor(control_connection_t
*conn
,
156 static int handle_control_redirectstream(control_connection_t
*conn
,
159 static int handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
161 static int handle_control_closecircuit(control_connection_t
*conn
,
164 static int handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
166 static int handle_control_usefeature(control_connection_t
*conn
,
169 static int write_stream_target_to_buf(edge_connection_t
*conn
, char *buf
,
171 static void orconn_target_get_name(char *buf
, size_t len
,
172 or_connection_t
*conn
);
173 static char *get_cookie_file(void);
175 /** Given a control event code for a message event, return the corresponding
178 event_to_log_severity(int event
)
181 case EVENT_DEBUG_MSG
: return LOG_DEBUG
;
182 case EVENT_INFO_MSG
: return LOG_INFO
;
183 case EVENT_NOTICE_MSG
: return LOG_NOTICE
;
184 case EVENT_WARN_MSG
: return LOG_WARN
;
185 case EVENT_ERR_MSG
: return LOG_ERR
;
190 /** Given a log severity, return the corresponding control event code. */
192 log_severity_to_event(int severity
)
195 case LOG_DEBUG
: return EVENT_DEBUG_MSG
;
196 case LOG_INFO
: return EVENT_INFO_MSG
;
197 case LOG_NOTICE
: return EVENT_NOTICE_MSG
;
198 case LOG_WARN
: return EVENT_WARN_MSG
;
199 case LOG_ERR
: return EVENT_ERR_MSG
;
204 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
205 * connection's event_mask field. */
207 control_update_global_event_mask(void)
209 smartlist_t
*conns
= get_connection_array();
210 event_mask_t old_mask
, new_mask
;
211 old_mask
= global_event_mask
;
213 global_event_mask
= 0;
214 SMARTLIST_FOREACH(conns
, connection_t
*, _conn
,
216 if (_conn
->type
== CONN_TYPE_CONTROL
&&
217 STATE_IS_OPEN(_conn
->state
)) {
218 control_connection_t
*conn
= TO_CONTROL_CONN(_conn
);
219 global_event_mask
|= conn
->event_mask
;
223 new_mask
= global_event_mask
;
225 /* Handle the aftermath. Set up the log callback to tell us only what
226 * we want to hear...*/
227 control_adjust_event_log_severity();
229 /* ...then, if we've started logging stream bw, clear the appropriate
231 if (! (old_mask
& EVENT_STREAM_BANDWIDTH_USED
) &&
232 (new_mask
& EVENT_STREAM_BANDWIDTH_USED
)) {
233 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
235 if (conn
->type
== CONN_TYPE_AP
) {
236 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
237 edge_conn
->n_written
= edge_conn
->n_read
= 0;
243 /** Adjust the log severities that result in control_event_logmsg being called
244 * to match the severity of log messages that any controllers are interested
247 control_adjust_event_log_severity(void)
250 int min_log_event
=EVENT_ERR_MSG
, max_log_event
=EVENT_DEBUG_MSG
;
252 for (i
= EVENT_DEBUG_MSG
; i
<= EVENT_ERR_MSG
; ++i
) {
253 if (EVENT_IS_INTERESTING(i
)) {
258 for (i
= EVENT_ERR_MSG
; i
>= EVENT_DEBUG_MSG
; --i
) {
259 if (EVENT_IS_INTERESTING(i
)) {
264 if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE
) ||
265 EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
)) {
266 if (min_log_event
> EVENT_NOTICE_MSG
)
267 min_log_event
= EVENT_NOTICE_MSG
;
268 if (max_log_event
< EVENT_ERR_MSG
)
269 max_log_event
= EVENT_ERR_MSG
;
271 if (min_log_event
<= max_log_event
)
272 change_callback_log_severity(event_to_log_severity(min_log_event
),
273 event_to_log_severity(max_log_event
),
274 control_event_logmsg
);
276 change_callback_log_severity(LOG_ERR
, LOG_ERR
,
277 control_event_logmsg
);
280 /** Return true iff the event with code <b>c</b> is being sent to any current
281 * control connection. This is useful if the amount of work needed to prepare
282 * to call the appropriate control_event_...() function is high.
285 control_event_is_interesting(int event
)
287 return EVENT_IS_INTERESTING(event
);
290 /** Append a NUL-terminated string <b>s</b> to the end of
291 * <b>conn</b>-\>outbuf.
294 connection_write_str_to_buf(const char *s
, control_connection_t
*conn
)
296 size_t len
= strlen(s
);
297 connection_write_to_buf(s
, len
, TO_CONN(conn
));
300 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
301 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
302 * contents of <b>data</b> into *<b>out</b>, adding a period before any period
303 * that appears at the start of a line, and adding a period-CRLF line at
304 * the end. Replace all LF characters sequences with CRLF. Return the number
305 * of bytes in *<b>out</b>.
308 write_escaped_data(const char *data
, size_t len
, char **out
)
310 size_t sz_out
= len
+8;
312 const char *start
= data
, *end
;
315 for (i
=0; i
<(int)len
; ++i
) {
317 sz_out
+= 2; /* Maybe add a CR; maybe add a dot. */
319 *out
= outp
= tor_malloc(sz_out
+1);
324 if (data
> start
&& data
[-1] != '\r')
327 } else if (*data
== '.') {
337 if (outp
< *out
+2 || memcmp(outp
-2, "\r\n", 2)) {
344 *outp
= '\0'; /* NUL-terminate just in case. */
345 tor_assert((outp
- *out
) <= (int)sz_out
);
349 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
350 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
351 * the contents of <b>data</b> into *<b>out</b>, removing any period
352 * that appears at the start of a line, and replacing all CRLF sequences
353 * with LF. Return the number of
354 * bytes in *<b>out</b>. */
356 read_escaped_data(const char *data
, size_t len
, char **out
)
362 *out
= outp
= tor_malloc(len
+1);
367 /* we're at the start of a line. */
370 next
= memchr(data
, '\n', end
-data
);
372 size_t n_to_copy
= next
-data
;
373 /* Don't copy a CR that precedes this LF. */
374 if (n_to_copy
&& *(next
-1) == '\r')
376 memcpy(outp
, data
, n_to_copy
);
378 data
= next
+1; /* This will point at the start of the next line,
379 * or the end of the string, or a period. */
381 memcpy(outp
, data
, end
-data
);
393 /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
394 * double-quoted string with escaped characters, return the length of that
395 * string (as encoded, including quotes). Otherwise return -1. */
397 get_escaped_string_length(const char *start
, size_t in_len_max
,
400 const char *cp
, *end
;
407 end
= start
+in_len_max
;
409 /* Calculate length. */
412 return -1; /* Too long. */
413 } else if (*cp
== '\\') {
415 return -1; /* Can't escape EOS. */
418 } else if (*cp
== '\"') {
427 return (int)(cp
- start
+1);
430 /** As decode_escaped_string, but does not decode the string: copies the
431 * entire thing, including quotation marks. */
433 extract_escaped_string(const char *start
, size_t in_len_max
,
434 char **out
, size_t *out_len
)
436 int length
= get_escaped_string_length(start
, in_len_max
, NULL
);
440 *out
= tor_strndup(start
, *out_len
);
444 /** Given a pointer to a string starting at <b>start</b> containing
445 * <b>in_len_max</b> characters, decode a string beginning with one double
446 * quote, containing any number of non-quote characters or characters escaped
447 * with a backslash, and ending with a final double quote. Place the resulting
448 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
449 * store its length in <b>out_len</b>. On success, return a pointer to the
450 * character immediately following the escaped string. On failure, return
453 decode_escaped_string(const char *start
, size_t in_len_max
,
454 char **out
, size_t *out_len
)
456 const char *cp
, *end
;
458 int len
, n_chars
= 0;
460 len
= get_escaped_string_length(start
, in_len_max
, &n_chars
);
464 end
= start
+len
-1; /* Index of last quote. */
465 tor_assert(*end
== '\"');
466 outp
= *out
= tor_malloc(len
+1);
476 tor_assert((outp
- *out
) == (int)*out_len
);
481 /** Acts like sprintf, but writes its formatted string to the end of
482 * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
483 * but it will always end with a CRLF sequence.
485 * Currently the length of the message is limited to 1024 (including the
486 * ending CR LF NUL ("\\r\\n\\0"). */
488 connection_printf_to_buf(control_connection_t
*conn
, const char *format
, ...)
490 #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
492 char buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
];
496 r
= tor_vsnprintf(buf
, sizeof(buf
), format
, ap
);
499 log_warn(LD_BUG
, "Unable to format string for controller.");
503 if (memcmp("\r\n\0", buf
+len
-2, 3)) {
504 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-1] = '\0';
505 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-2] = '\n';
506 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-3] = '\r';
508 connection_write_to_buf(buf
, len
, TO_CONN(conn
));
511 /** Send a "DONE" message down the control connection <b>conn</b>. */
513 send_control_done(control_connection_t
*conn
)
515 connection_write_str_to_buf("250 OK\r\n", conn
);
518 /** Send an event to all v1 controllers that are listening for code
519 * <b>event</b>. The event's body is given by <b>msg</b>.
521 * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
522 * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
523 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
524 * to controllers that <em>have</em> enabled VERBOSE_NAMES.
526 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
527 * respect to the EXTENDED_EVENTS feature. */
529 send_control_event_string(uint16_t event
, event_format_t which
,
532 smartlist_t
*conns
= get_connection_array();
534 tor_assert(event
>= _EVENT_MIN
&& event
<= _EVENT_MAX
);
536 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
537 if (conn
->type
== CONN_TYPE_CONTROL
&&
538 !conn
->marked_for_close
&&
539 conn
->state
== CONTROL_CONN_STATE_OPEN
) {
540 control_connection_t
*control_conn
= TO_CONTROL_CONN(conn
);
542 if (control_conn
->event_mask
& (1<<event
)) {
544 connection_write_to_buf(msg
, strlen(msg
), TO_CONN(control_conn
));
545 if (event
== EVENT_ERR_MSG
)
547 else if (event
== EVENT_STATUS_GENERAL
)
548 is_err
= !strcmpstart(msg
, "STATUS_GENERAL ERR ");
549 else if (event
== EVENT_STATUS_CLIENT
)
550 is_err
= !strcmpstart(msg
, "STATUS_CLIENT ERR ");
551 else if (event
== EVENT_STATUS_SERVER
)
552 is_err
= !strcmpstart(msg
, "STATUS_SERVER ERR ");
554 connection_handle_write(TO_CONN(control_conn
), 1);
557 } SMARTLIST_FOREACH_END(conn
);
560 /** Helper for send_control1_event and send_control1_event_extended:
561 * Send an event to all v1 controllers that are listening for code
562 * <b>event</b>. The event's body is created by the printf-style format in
563 * <b>format</b>, and other arguments as provided.
565 * Currently the length of the message is limited to 1024 (including the
566 * ending \\r\\n\\0). */
568 send_control_event_impl(uint16_t event
, event_format_t which
,
569 const char *format
, va_list ap
)
571 /* This is just a little longer than the longest allowed log message */
572 #define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
574 char buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
];
577 r
= tor_vsnprintf(buf
, sizeof(buf
), format
, ap
);
579 log_warn(LD_BUG
, "Unable to format event for controller.");
584 if (memcmp("\r\n\0", buf
+len
-2, 3)) {
585 /* if it is not properly terminated, do it now */
586 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-1] = '\0';
587 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-2] = '\n';
588 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-3] = '\r';
591 send_control_event_string(event
, which
|ALL_FORMATS
, buf
);
594 /** Send an event to all v1 controllers that are listening for code
595 * <b>event</b>. The event's body is created by the printf-style format in
596 * <b>format</b>, and other arguments as provided.
598 * Currently the length of the message is limited to 1024 (including the
599 * ending \\n\\r\\0. */
601 send_control_event(uint16_t event
, event_format_t which
,
602 const char *format
, ...)
605 va_start(ap
, format
);
606 send_control_event_impl(event
, which
, format
, ap
);
610 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
611 static origin_circuit_t
*
612 get_circ(const char *id
)
616 n_id
= (uint32_t) tor_parse_ulong(id
, 10, 0, UINT32_MAX
, &ok
, NULL
);
619 return circuit_get_by_global_id(n_id
);
622 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
623 static edge_connection_t
*
624 get_stream(const char *id
)
629 n_id
= tor_parse_uint64(id
, 10, 0, UINT64_MAX
, &ok
, NULL
);
632 conn
= connection_get_by_global_id(n_id
);
633 if (!conn
|| conn
->type
!= CONN_TYPE_AP
|| conn
->marked_for_close
)
635 return TO_EDGE_CONN(conn
);
638 /** Helper for setconf and resetconf. Acts like setconf, except
639 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
643 control_setconf_helper(control_connection_t
*conn
, uint32_t len
, char *body
,
646 setopt_err_t opt_err
;
647 config_line_t
*lines
=NULL
;
649 char *errstring
= NULL
;
650 const int clear_first
= 1;
653 smartlist_t
*entries
= smartlist_create();
655 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
656 * separated by space. break it into a list of configuration entries. */
661 while (!TOR_ISSPACE(*eq
) && *eq
!= '=')
663 key
= tor_strndup(body
, eq
-body
);
670 char *val_start
= body
;
671 while (!TOR_ISSPACE(*body
))
673 val
= tor_strndup(val_start
, body
-val_start
);
674 val_len
= strlen(val
);
676 body
= (char*)extract_escaped_string(body
, (len
- (body
-start
)),
679 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn
);
680 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
681 smartlist_free(entries
);
686 ent_len
= strlen(key
)+val_len
+3;
687 entry
= tor_malloc(ent_len
+1);
688 tor_snprintf(entry
, ent_len
, "%s %s", key
, val
);
694 smartlist_add(entries
, entry
);
695 while (TOR_ISSPACE(*body
))
699 smartlist_add(entries
, tor_strdup(""));
700 config
= smartlist_join_strings(entries
, "\n", 0, NULL
);
701 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
702 smartlist_free(entries
);
704 if (config_get_lines(config
, &lines
) < 0) {
705 log_warn(LD_CONTROL
,"Controller gave us config lines we can't parse.");
706 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
713 opt_err
= options_trial_assign(lines
, use_defaults
, clear_first
, &errstring
);
717 case SETOPT_ERR_MISC
:
718 msg
= "552 Unrecognized option";
720 case SETOPT_ERR_PARSE
:
721 msg
= "513 Unacceptable option value";
723 case SETOPT_ERR_TRANSITION
:
724 msg
= "553 Transition not allowed";
726 case SETOPT_ERR_SETTING
:
728 msg
= "553 Unable to set option";
731 config_free_lines(lines
);
732 send_control_done(conn
);
736 "Controller gave us config lines that didn't validate: %s",
738 connection_printf_to_buf(conn
, "%s: %s\r\n", msg
, errstring
);
739 config_free_lines(lines
);
745 /** Called when we receive a SETCONF message: parse the body and try
746 * to update our configuration. Reply with a DONE or ERROR message.
747 * Modifies the contents of body.*/
749 handle_control_setconf(control_connection_t
*conn
, uint32_t len
, char *body
)
751 return control_setconf_helper(conn
, len
, body
, 0);
754 /** Called when we receive a RESETCONF message: parse the body and try
755 * to update our configuration. Reply with a DONE or ERROR message.
756 * Modifies the contents of body. */
758 handle_control_resetconf(control_connection_t
*conn
, uint32_t len
, char *body
)
760 return control_setconf_helper(conn
, len
, body
, 1);
763 /** Called when we receive a GETCONF message. Parse the request, and
764 * reply with a CONFVALUE or an ERROR message */
766 handle_control_getconf(control_connection_t
*conn
, uint32_t body_len
,
769 smartlist_t
*questions
= smartlist_create();
770 smartlist_t
*answers
= smartlist_create();
771 smartlist_t
*unrecognized
= smartlist_create();
774 or_options_t
*options
= get_options();
777 (void) body_len
; /* body is NUL-terminated; so we can ignore len. */
778 smartlist_split_string(questions
, body
, " ",
779 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
780 SMARTLIST_FOREACH(questions
, const char *, q
,
782 if (!option_is_recognized(q
)) {
783 smartlist_add(unrecognized
, (char*) q
);
785 config_line_t
*answer
= option_get_assignment(options
,q
);
787 const char *name
= option_get_canonical_name(q
);
788 size_t alen
= strlen(name
)+8;
789 char *astr
= tor_malloc(alen
);
790 tor_snprintf(astr
, alen
, "250-%s\r\n", name
);
791 smartlist_add(answers
, astr
);
796 size_t alen
= strlen(answer
->key
)+strlen(answer
->value
)+8;
797 char *astr
= tor_malloc(alen
);
798 tor_snprintf(astr
, alen
, "250-%s=%s\r\n",
799 answer
->key
, answer
->value
);
800 smartlist_add(answers
, astr
);
803 tor_free(answer
->key
);
804 tor_free(answer
->value
);
811 if ((len
= smartlist_len(unrecognized
))) {
812 for (i
=0; i
< len
-1; ++i
)
813 connection_printf_to_buf(conn
,
814 "552-Unrecognized configuration key \"%s\"\r\n",
815 (char*)smartlist_get(unrecognized
, i
));
816 connection_printf_to_buf(conn
,
817 "552 Unrecognized configuration key \"%s\"\r\n",
818 (char*)smartlist_get(unrecognized
, len
-1));
819 } else if ((len
= smartlist_len(answers
))) {
820 char *tmp
= smartlist_get(answers
, len
-1);
821 tor_assert(strlen(tmp
)>4);
823 msg
= smartlist_join_strings(answers
, "", 0, &msg_len
);
824 connection_write_to_buf(msg
, msg_len
, TO_CONN(conn
));
826 connection_write_str_to_buf("250 OK\r\n", conn
);
829 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
830 smartlist_free(answers
);
831 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
832 smartlist_free(questions
);
833 smartlist_free(unrecognized
);
840 /** Called when we get a +LOADCONF message. */
842 handle_control_loadconf(control_connection_t
*conn
, uint32_t len
,
846 char *errstring
= NULL
;
847 const char *msg
= NULL
;
850 retval
= options_init_from_string(body
, CMD_RUN_TOR
, NULL
, &errstring
);
852 if (retval
!= SETOPT_OK
)
854 "Controller gave us config file that didn't validate: %s",
858 case SETOPT_ERR_PARSE
:
859 msg
= "552 Invalid config file";
861 case SETOPT_ERR_TRANSITION
:
862 msg
= "553 Transition not allowed";
864 case SETOPT_ERR_SETTING
:
865 msg
= "553 Unable to set option";
867 case SETOPT_ERR_MISC
:
869 msg
= "550 Unable to load config";
876 connection_printf_to_buf(conn
, "%s: %s\r\n", msg
, errstring
);
878 connection_printf_to_buf(conn
, "%s\r\n", msg
);
880 send_control_done(conn
);
886 /** Called when we get a SETEVENTS message: update conn->event_mask,
887 * and reply with DONE or ERROR. */
889 handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
893 uint32_t event_mask
= 0;
894 smartlist_t
*events
= smartlist_create();
898 smartlist_split_string(events
, body
, " ",
899 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
900 SMARTLIST_FOREACH_BEGIN(events
, const char *, ev
)
902 if (!strcasecmp(ev
, "EXTENDED")) {
904 } else if (!strcasecmp(ev
, "CIRC"))
905 event_code
= EVENT_CIRCUIT_STATUS
;
906 else if (!strcasecmp(ev
, "STREAM"))
907 event_code
= EVENT_STREAM_STATUS
;
908 else if (!strcasecmp(ev
, "ORCONN"))
909 event_code
= EVENT_OR_CONN_STATUS
;
910 else if (!strcasecmp(ev
, "BW"))
911 event_code
= EVENT_BANDWIDTH_USED
;
912 else if (!strcasecmp(ev
, "DEBUG"))
913 event_code
= EVENT_DEBUG_MSG
;
914 else if (!strcasecmp(ev
, "INFO"))
915 event_code
= EVENT_INFO_MSG
;
916 else if (!strcasecmp(ev
, "NOTICE"))
917 event_code
= EVENT_NOTICE_MSG
;
918 else if (!strcasecmp(ev
, "WARN"))
919 event_code
= EVENT_WARN_MSG
;
920 else if (!strcasecmp(ev
, "ERR"))
921 event_code
= EVENT_ERR_MSG
;
922 else if (!strcasecmp(ev
, "NEWDESC"))
923 event_code
= EVENT_NEW_DESC
;
924 else if (!strcasecmp(ev
, "ADDRMAP"))
925 event_code
= EVENT_ADDRMAP
;
926 else if (!strcasecmp(ev
, "AUTHDIR_NEWDESCS"))
927 event_code
= EVENT_AUTHDIR_NEWDESCS
;
928 else if (!strcasecmp(ev
, "DESCCHANGED"))
929 event_code
= EVENT_DESCCHANGED
;
930 else if (!strcasecmp(ev
, "NS"))
931 event_code
= EVENT_NS
;
932 else if (!strcasecmp(ev
, "STATUS_GENERAL"))
933 event_code
= EVENT_STATUS_GENERAL
;
934 else if (!strcasecmp(ev
, "STATUS_CLIENT"))
935 event_code
= EVENT_STATUS_CLIENT
;
936 else if (!strcasecmp(ev
, "STATUS_SERVER"))
937 event_code
= EVENT_STATUS_SERVER
;
938 else if (!strcasecmp(ev
, "GUARD"))
939 event_code
= EVENT_GUARD
;
940 else if (!strcasecmp(ev
, "STREAM_BW"))
941 event_code
= EVENT_STREAM_BANDWIDTH_USED
;
942 else if (!strcasecmp(ev
, "CLIENTS_SEEN"))
943 event_code
= EVENT_CLIENTS_SEEN
;
944 else if (!strcasecmp(ev
, "NEWCONSENSUS"))
945 event_code
= EVENT_NEWCONSENSUS
;
946 else if (!strcasecmp(ev
, "BUILDTIMEOUT_SET"))
947 event_code
= EVENT_BUILDTIMEOUT_SET
;
949 connection_printf_to_buf(conn
, "552 Unrecognized event \"%s\"\r\n",
951 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
952 smartlist_free(events
);
955 event_mask
|= (1 << event_code
);
957 SMARTLIST_FOREACH_END(ev
);
958 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
959 smartlist_free(events
);
961 conn
->event_mask
= event_mask
;
963 control_update_global_event_mask();
964 send_control_done(conn
);
968 /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
969 * Return a smartlist of acceptable passwords (unterminated strings of
970 * length S2K_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on failure.
973 decode_hashed_passwords(config_line_t
*passwords
)
977 smartlist_t
*sl
= smartlist_create();
979 tor_assert(passwords
);
981 for (cl
= passwords
; cl
; cl
= cl
->next
) {
982 const char *hashed
= cl
->value
;
984 if (!strcmpstart(hashed
, "16:")) {
985 if (base16_decode(decoded
, sizeof(decoded
), hashed
+3, strlen(hashed
+3))<0
986 || strlen(hashed
+3) != (S2K_SPECIFIER_LEN
+DIGEST_LEN
)*2) {
990 if (base64_decode(decoded
, sizeof(decoded
), hashed
, strlen(hashed
))
991 != S2K_SPECIFIER_LEN
+DIGEST_LEN
) {
995 smartlist_add(sl
, tor_memdup(decoded
, S2K_SPECIFIER_LEN
+DIGEST_LEN
));
1001 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
1006 /** Called when we get an AUTHENTICATE message. Check whether the
1007 * authentication is valid, and if so, update the connection's state to
1008 * OPEN. Reply with DONE or ERROR.
1011 handle_control_authenticate(control_connection_t
*conn
, uint32_t len
,
1014 int used_quoted_string
= 0;
1015 or_options_t
*options
= get_options();
1016 const char *errstr
= NULL
;
1018 size_t password_len
;
1021 int bad_cookie
=0, bad_password
=0;
1022 smartlist_t
*sl
= NULL
;
1024 if (TOR_ISXDIGIT(body
[0])) {
1026 while (TOR_ISXDIGIT(*cp
))
1028 i
= (int)(cp
- body
);
1031 password
= tor_malloc(password_len
+ 1);
1032 if (base16_decode(password
, password_len
+1, body
, i
)<0) {
1033 connection_write_str_to_buf(
1034 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1035 "password? If so, the standard requires that you put it in "
1036 "double quotes.\r\n", conn
);
1037 connection_mark_for_close(TO_CONN(conn
));
1041 } else if (TOR_ISSPACE(body
[0])) {
1042 password
= tor_strdup("");
1045 if (!decode_escaped_string(body
, len
, &password
, &password_len
)) {
1046 connection_write_str_to_buf("551 Invalid quoted string. You need "
1047 "to put the password in double quotes.\r\n", conn
);
1048 connection_mark_for_close(TO_CONN(conn
));
1051 used_quoted_string
= 1;
1054 if (!options
->CookieAuthentication
&& !options
->HashedControlPassword
&&
1055 !options
->HashedControlSessionPassword
) {
1056 /* if Tor doesn't demand any stronger authentication, then
1057 * the controller can get in with anything. */
1061 if (options
->CookieAuthentication
) {
1062 int also_password
= options
->HashedControlPassword
!= NULL
||
1063 options
->HashedControlSessionPassword
!= NULL
;
1064 if (password_len
!= AUTHENTICATION_COOKIE_LEN
) {
1065 if (!also_password
) {
1066 log_warn(LD_CONTROL
, "Got authentication cookie with wrong length "
1067 "(%d)", (int)password_len
);
1068 errstr
= "Wrong length on authentication cookie.";
1072 } else if (memcmp(authentication_cookie
, password
, password_len
)) {
1073 if (!also_password
) {
1074 log_warn(LD_CONTROL
, "Got mismatched authentication cookie");
1075 errstr
= "Authentication cookie did not match expected value.";
1084 if (options
->HashedControlPassword
||
1085 options
->HashedControlSessionPassword
) {
1087 smartlist_t
*sl_tmp
;
1088 char received
[DIGEST_LEN
];
1089 int also_cookie
= options
->CookieAuthentication
;
1090 sl
= smartlist_create();
1091 if (options
->HashedControlPassword
) {
1092 sl_tmp
= decode_hashed_passwords(options
->HashedControlPassword
);
1096 smartlist_add_all(sl
, sl_tmp
);
1097 smartlist_free(sl_tmp
);
1100 if (options
->HashedControlSessionPassword
) {
1101 sl_tmp
= decode_hashed_passwords(options
->HashedControlSessionPassword
);
1105 smartlist_add_all(sl
, sl_tmp
);
1106 smartlist_free(sl_tmp
);
1111 log_warn(LD_CONTROL
,
1112 "Couldn't decode HashedControlPassword: invalid base16");
1113 errstr
="Couldn't decode HashedControlPassword value in configuration.";
1116 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1119 SMARTLIST_FOREACH(sl
, char *, expected
,
1121 secret_to_key(received
,DIGEST_LEN
,password
,password_len
,expected
);
1122 if (!memcmp(expected
+S2K_SPECIFIER_LEN
, received
, DIGEST_LEN
))
1125 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1128 if (used_quoted_string
)
1129 errstr
= "Password did not match HashedControlPassword value from "
1132 errstr
= "Password did not match HashedControlPassword value from "
1133 "configuration. Maybe you tried a plain text password? "
1134 "If so, the standard requires that you put it in double quotes.";
1141 /** We only get here if both kinds of authentication failed. */
1142 tor_assert(bad_password
&& bad_cookie
);
1143 log_warn(LD_CONTROL
, "Bad password or authentication cookie on controller.");
1144 errstr
= "Password did not match HashedControlPassword *or* authentication "
1149 connection_printf_to_buf(conn
, "515 Authentication failed: %s\r\n",
1150 errstr
? errstr
: "Unknown reason.");
1151 connection_mark_for_close(TO_CONN(conn
));
1154 log_info(LD_CONTROL
, "Authenticated control connection (%d)", conn
->_base
.s
);
1155 send_control_done(conn
);
1156 conn
->_base
.state
= CONTROL_CONN_STATE_OPEN
;
1158 if (sl
) { /* clean up */
1159 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1165 /** Called when we get a SAVECONF command. Try to flush the current options to
1166 * disk, and report success or failure. */
1168 handle_control_saveconf(control_connection_t
*conn
, uint32_t len
,
1173 if (options_save_current()<0) {
1174 connection_write_str_to_buf(
1175 "551 Unable to write configuration to disk.\r\n", conn
);
1177 send_control_done(conn
);
1182 /** Called when we get a SIGNAL command. React to the provided signal, and
1183 * report success or failure. (If the signal results in a shutdown, success
1184 * may not be reported.) */
1186 handle_control_signal(control_connection_t
*conn
, uint32_t len
,
1195 while (body
[n
] && ! TOR_ISSPACE(body
[n
]))
1197 s
= tor_strndup(body
, n
);
1198 if (!strcasecmp(s
, "RELOAD") || !strcasecmp(s
, "HUP"))
1200 else if (!strcasecmp(s
, "SHUTDOWN") || !strcasecmp(s
, "INT"))
1202 else if (!strcasecmp(s
, "DUMP") || !strcasecmp(s
, "USR1"))
1204 else if (!strcasecmp(s
, "DEBUG") || !strcasecmp(s
, "USR2"))
1206 else if (!strcasecmp(s
, "HALT") || !strcasecmp(s
, "TERM"))
1208 else if (!strcasecmp(s
, "NEWNYM"))
1210 else if (!strcasecmp(s
, "CLEARDNSCACHE"))
1211 sig
= SIGCLEARDNSCACHE
;
1213 connection_printf_to_buf(conn
, "552 Unrecognized signal code \"%s\"\r\n",
1221 send_control_done(conn
);
1222 /* Flush the "done" first if the signal might make us shut down. */
1223 if (sig
== SIGTERM
|| sig
== SIGINT
)
1224 connection_handle_write(TO_CONN(conn
), 1);
1225 signal_callback(0,0,(void*)(uintptr_t)sig
);
1230 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1231 * and report success or failure. */
1233 handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
1241 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
1243 lines
= smartlist_create();
1244 elts
= smartlist_create();
1245 reply
= smartlist_create();
1246 smartlist_split_string(lines
, body
, " ",
1247 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1248 SMARTLIST_FOREACH(lines
, char *, line
,
1251 smartlist_split_string(elts
, line
, "=", 0, 2);
1252 if (smartlist_len(elts
) == 2) {
1253 const char *from
= smartlist_get(elts
,0);
1254 const char *to
= smartlist_get(elts
,1);
1255 size_t anslen
= strlen(line
)+512;
1256 char *ans
= tor_malloc(anslen
);
1257 if (address_is_invalid_destination(to
, 1)) {
1258 tor_snprintf(ans
, anslen
,
1259 "512-syntax error: invalid address '%s'", to
);
1260 smartlist_add(reply
, ans
);
1261 log_warn(LD_CONTROL
,
1262 "Skipping invalid argument '%s' in MapAddress msg", to
);
1263 } else if (!strcmp(from
, ".") || !strcmp(from
, "0.0.0.0")) {
1264 const char *address
= addressmap_register_virtual_address(
1265 !strcmp(from
,".") ? RESOLVED_TYPE_HOSTNAME
: RESOLVED_TYPE_IPV4
,
1268 tor_snprintf(ans
, anslen
,
1269 "451-resource exhausted: skipping '%s'", line
);
1270 smartlist_add(reply
, ans
);
1271 log_warn(LD_CONTROL
,
1272 "Unable to allocate address for '%s' in MapAddress msg",
1273 safe_str_client(line
));
1275 tor_snprintf(ans
, anslen
, "250-%s=%s", address
, to
);
1276 smartlist_add(reply
, ans
);
1279 addressmap_register(from
, tor_strdup(to
), 1, ADDRMAPSRC_CONTROLLER
);
1280 tor_snprintf(ans
, anslen
, "250-%s", line
);
1281 smartlist_add(reply
, ans
);
1284 size_t anslen
= strlen(line
)+256;
1285 char *ans
= tor_malloc(anslen
);
1286 tor_snprintf(ans
, anslen
, "512-syntax error: mapping '%s' is "
1287 "not of expected form 'foo=bar'.", line
);
1288 smartlist_add(reply
, ans
);
1289 log_info(LD_CONTROL
, "Skipping MapAddress '%s': wrong "
1291 safe_str_client(line
));
1293 SMARTLIST_FOREACH(elts
, char *, cp
, tor_free(cp
));
1294 smartlist_clear(elts
);
1296 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
1297 smartlist_free(lines
);
1298 smartlist_free(elts
);
1300 if (smartlist_len(reply
)) {
1301 ((char*)smartlist_get(reply
,smartlist_len(reply
)-1))[3] = ' ';
1302 r
= smartlist_join_strings(reply
, "\r\n", 1, &sz
);
1303 connection_write_to_buf(r
, sz
, TO_CONN(conn
));
1306 const char *response
=
1307 "512 syntax error: not enough arguments to mapaddress.\r\n";
1308 connection_write_to_buf(response
, strlen(response
), TO_CONN(conn
));
1311 SMARTLIST_FOREACH(reply
, char *, cp
, tor_free(cp
));
1312 smartlist_free(reply
);
1316 /** Implementation helper for GETINFO: knows the answers for various
1317 * trivial-to-implement questions. */
1319 getinfo_helper_misc(control_connection_t
*conn
, const char *question
,
1320 char **answer
, const char **errmsg
)
1323 if (!strcmp(question
, "version")) {
1324 *answer
= tor_strdup(get_version());
1325 } else if (!strcmp(question
, "config-file")) {
1326 *answer
= tor_strdup(get_torrc_fname());
1327 } else if (!strcmp(question
, "config-text")) {
1328 *answer
= options_dump(get_options(), 1);
1329 } else if (!strcmp(question
, "info/names")) {
1330 *answer
= list_getinfo_options();
1331 } else if (!strcmp(question
, "events/names")) {
1332 *answer
= tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
1333 "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
1334 "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
1335 "GUARD STREAM_BW CLIENTS_SEEN NEWCONSENSUS");
1336 } else if (!strcmp(question
, "features/names")) {
1337 *answer
= tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1338 } else if (!strcmp(question
, "address")) {
1340 if (router_pick_published_address(get_options(), &addr
) < 0) {
1341 *errmsg
= "Address unknown";
1344 *answer
= tor_dup_ip(addr
);
1345 } else if (!strcmp(question
, "dir-usage")) {
1346 *answer
= directory_dump_request_log();
1347 } else if (!strcmp(question
, "fingerprint")) {
1348 routerinfo_t
*me
= router_get_my_routerinfo();
1350 *errmsg
= "No routerdesc known; am I really a server?";
1353 *answer
= tor_malloc(HEX_DIGEST_LEN
+1);
1354 base16_encode(*answer
, HEX_DIGEST_LEN
+1, me
->cache_info
.identity_digest
,
1360 /** Awful hack: return a newly allocated string based on a routerinfo and
1361 * (possibly) an extrainfo, sticking the read-history and write-history from
1362 * <b>ei</b> into the resulting string. The thing you get back won't
1363 * necessarily have a valid signature.
1365 * New code should never use this; it's for backward compatibility.
1367 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1368 * not be NUL-terminated. */
1370 munge_extrainfo_into_routerinfo(const char *ri_body
, signed_descriptor_t
*ri
,
1371 signed_descriptor_t
*ei
)
1373 char *out
= NULL
, *outp
;
1375 const char *router_sig
;
1376 const char *ei_body
= signed_descriptor_get_body(ei
);
1377 size_t ri_len
= ri
->signed_descriptor_len
;
1378 size_t ei_len
= ei
->signed_descriptor_len
;
1382 outp
= out
= tor_malloc(ri_len
+ei_len
+1);
1383 if (!(router_sig
= tor_memstr(ri_body
, ri_len
, "\nrouter-signature")))
1386 memcpy(out
, ri_body
, router_sig
-ri_body
);
1387 outp
+= router_sig
-ri_body
;
1389 for (i
=0; i
< 2; ++i
) {
1390 const char *kwd
= i
?"\nwrite-history ":"\nread-history ";
1391 const char *cp
, *eol
;
1392 if (!(cp
= tor_memstr(ei_body
, ei_len
, kwd
)))
1395 eol
= memchr(cp
, '\n', ei_len
- (cp
-ei_body
));
1396 memcpy(outp
, cp
, eol
-cp
+1);
1399 memcpy(outp
, router_sig
, ri_len
- (router_sig
-ri_body
));
1401 tor_assert(outp
-out
< (int)(ri_len
+ei_len
+1));
1406 return tor_strndup(ri_body
, ri
->signed_descriptor_len
);
1409 /** Implementation helper for GETINFO: knows the answers for questions about
1410 * directory information. */
1412 getinfo_helper_dir(control_connection_t
*control_conn
,
1413 const char *question
, char **answer
,
1414 const char **errmsg
)
1416 (void) control_conn
;
1417 if (!strcmpstart(question
, "desc/id/")) {
1418 routerinfo_t
*ri
= router_get_by_hexdigest(question
+strlen("desc/id/"));
1420 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1422 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
1424 } else if (!strcmpstart(question
, "desc/name/")) {
1425 routerinfo_t
*ri
= router_get_by_nickname(question
+strlen("desc/name/"),1);
1427 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1429 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
1431 } else if (!strcmp(question
, "desc/all-recent")) {
1432 routerlist_t
*routerlist
= router_get_routerlist();
1433 smartlist_t
*sl
= smartlist_create();
1434 if (routerlist
&& routerlist
->routers
) {
1435 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
1437 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1440 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
1443 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
1444 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
1446 } else if (!strcmp(question
, "desc/all-recent-extrainfo-hack")) {
1447 /* XXXX Remove this once Torstat asks for extrainfos. */
1448 routerlist_t
*routerlist
= router_get_routerlist();
1449 smartlist_t
*sl
= smartlist_create();
1450 if (routerlist
&& routerlist
->routers
) {
1451 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
1453 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1454 signed_descriptor_t
*ei
= extrainfo_get_by_descriptor_digest(
1455 ri
->cache_info
.extra_info_digest
);
1457 smartlist_add(sl
, munge_extrainfo_into_routerinfo(body
,
1458 &ri
->cache_info
, ei
));
1461 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
1465 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
1466 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
1468 } else if (!strcmpstart(question
, "desc-annotations/id/")) {
1469 routerinfo_t
*ri
= router_get_by_hexdigest(question
+
1470 strlen("desc-annotations/id/"));
1472 const char *annotations
=
1473 signed_descriptor_get_annotations(&ri
->cache_info
);
1475 *answer
= tor_strndup(annotations
,
1476 ri
->cache_info
.annotations_len
);
1478 } else if (!strcmpstart(question
, "dir/server/")) {
1479 size_t answer_len
= 0, url_len
= strlen(question
)+2;
1480 char *url
= tor_malloc(url_len
);
1481 smartlist_t
*descs
= smartlist_create();
1485 tor_snprintf(url
, url_len
, "/tor/%s", question
+4);
1486 res
= dirserv_get_routerdescs(descs
, url
, &msg
);
1488 log_warn(LD_CONTROL
, "getinfo '%s': %s", question
, msg
);
1489 smartlist_free(descs
);
1494 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
1495 answer_len
+= sd
->signed_descriptor_len
);
1496 cp
= *answer
= tor_malloc(answer_len
+1);
1497 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
1499 memcpy(cp
, signed_descriptor_get_body(sd
),
1500 sd
->signed_descriptor_len
);
1501 cp
+= sd
->signed_descriptor_len
;
1505 smartlist_free(descs
);
1506 } else if (!strcmpstart(question
, "dir/status/")) {
1507 if (directory_permits_controller_requests(get_options())) {
1510 smartlist_t
*status_list
= smartlist_create();
1511 dirserv_get_networkstatus_v2(status_list
,
1512 question
+strlen("dir/status/"));
1513 SMARTLIST_FOREACH(status_list
, cached_dir_t
*, d
, len
+= d
->dir_len
);
1514 cp
= *answer
= tor_malloc(len
+1);
1515 SMARTLIST_FOREACH(status_list
, cached_dir_t
*, d
, {
1516 memcpy(cp
, d
->dir
, d
->dir_len
);
1520 smartlist_free(status_list
);
1522 smartlist_t
*fp_list
= smartlist_create();
1523 smartlist_t
*status_list
= smartlist_create();
1524 dirserv_get_networkstatus_v2_fingerprints(
1525 fp_list
, question
+strlen("dir/status/"));
1526 SMARTLIST_FOREACH(fp_list
, const char *, fp
, {
1528 char *fname
= networkstatus_get_cache_filename(fp
);
1529 s
= read_file_to_str(fname
, 0, NULL
);
1531 smartlist_add(status_list
, s
);
1534 SMARTLIST_FOREACH(fp_list
, char *, fp
, tor_free(fp
));
1535 smartlist_free(fp_list
);
1536 *answer
= smartlist_join_strings(status_list
, "", 0, NULL
);
1537 SMARTLIST_FOREACH(status_list
, char *, s
, tor_free(s
));
1538 smartlist_free(status_list
);
1540 } else if (!strcmp(question
, "dir/status-vote/current/consensus")) { /* v3 */
1541 if (directory_caches_dir_info(get_options())) {
1542 const cached_dir_t
*consensus
= dirserv_get_consensus("ns");
1544 *answer
= tor_strdup(consensus
->dir
);
1546 if (!*answer
) { /* try loading it from disk */
1547 char *filename
= get_datadir_fname("cached-consensus");
1548 *answer
= read_file_to_str(filename
, RFTS_IGNORE_MISSING
, NULL
);
1551 } else if (!strcmp(question
, "network-status")) { /* v1 */
1552 routerlist_t
*routerlist
= router_get_routerlist();
1553 if (!routerlist
|| !routerlist
->routers
||
1554 list_server_status_v1(routerlist
->routers
, answer
, 1) < 0) {
1557 } else if (!strcmpstart(question
, "extra-info/digest/")) {
1558 question
+= strlen("extra-info/digest/");
1559 if (strlen(question
) == HEX_DIGEST_LEN
) {
1561 signed_descriptor_t
*sd
= NULL
;
1562 if (base16_decode(d
, sizeof(d
), question
, strlen(question
))==0) {
1563 /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
1564 * but I don't want to risk affecting other parts of the code,
1565 * especially since the rules for using our own extrainfo (including
1566 * when it might be freed) are different from those for using one
1567 * we have downloaded. */
1568 if (router_extrainfo_digest_is_me(d
))
1569 sd
= &(router_get_my_extrainfo()->cache_info
);
1571 sd
= extrainfo_get_by_descriptor_digest(d
);
1574 const char *body
= signed_descriptor_get_body(sd
);
1576 *answer
= tor_strndup(body
, sd
->signed_descriptor_len
);
1584 /** Implementation helper for GETINFO: knows how to generate summaries of the
1585 * current states of things we send events about. */
1587 getinfo_helper_events(control_connection_t
*control_conn
,
1588 const char *question
, char **answer
,
1589 const char **errmsg
)
1591 (void) control_conn
;
1592 if (!strcmp(question
, "circuit-status")) {
1594 smartlist_t
*status
= smartlist_create();
1595 for (circ
= _circuit_get_global_list(); circ
; circ
= circ
->next
) {
1599 const char *purpose
;
1600 if (! CIRCUIT_IS_ORIGIN(circ
) || circ
->marked_for_close
)
1603 path
= circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ
));
1605 if (circ
->state
== CIRCUIT_STATE_OPEN
)
1607 else if (strlen(path
))
1612 purpose
= circuit_purpose_to_controller_string(circ
->purpose
);
1613 slen
= strlen(path
)+strlen(state
)+strlen(purpose
)+30;
1614 s
= tor_malloc(slen
+1);
1615 tor_snprintf(s
, slen
, "%lu %s%s%s PURPOSE=%s",
1616 (unsigned long)TO_ORIGIN_CIRCUIT(circ
)->global_identifier
,
1617 state
, *path
? " " : "", path
, purpose
);
1618 smartlist_add(status
, s
);
1621 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1622 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1623 smartlist_free(status
);
1624 } else if (!strcmp(question
, "stream-status")) {
1625 smartlist_t
*conns
= get_connection_array();
1626 smartlist_t
*status
= smartlist_create();
1628 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
1630 edge_connection_t
*conn
;
1634 origin_circuit_t
*origin_circ
= NULL
;
1635 if (base_conn
->type
!= CONN_TYPE_AP
||
1636 base_conn
->marked_for_close
||
1637 base_conn
->state
== AP_CONN_STATE_SOCKS_WAIT
||
1638 base_conn
->state
== AP_CONN_STATE_NATD_WAIT
)
1640 conn
= TO_EDGE_CONN(base_conn
);
1641 switch (conn
->_base
.state
)
1643 case AP_CONN_STATE_CONTROLLER_WAIT
:
1644 case AP_CONN_STATE_CIRCUIT_WAIT
:
1645 if (conn
->socks_request
&&
1646 SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
))
1647 state
= "NEWRESOLVE";
1651 case AP_CONN_STATE_RENDDESC_WAIT
:
1652 case AP_CONN_STATE_CONNECT_WAIT
:
1653 state
= "SENTCONNECT"; break;
1654 case AP_CONN_STATE_RESOLVE_WAIT
:
1655 state
= "SENTRESOLVE"; break;
1656 case AP_CONN_STATE_OPEN
:
1657 state
= "SUCCEEDED"; break;
1659 log_warn(LD_BUG
, "Asked for stream in unknown state %d",
1663 circ
= circuit_get_by_edge_conn(conn
);
1664 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
1665 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
1666 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
1667 slen
= strlen(buf
)+strlen(state
)+32;
1668 s
= tor_malloc(slen
+1);
1669 tor_snprintf(s
, slen
, "%lu %s %lu %s",
1670 (unsigned long) conn
->_base
.global_identifier
,state
,
1672 (unsigned long)origin_circ
->global_identifier
: 0ul,
1674 smartlist_add(status
, s
);
1675 } SMARTLIST_FOREACH_END(base_conn
);
1676 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1677 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1678 smartlist_free(status
);
1679 } else if (!strcmp(question
, "orconn-status")) {
1680 smartlist_t
*conns
= get_connection_array();
1681 smartlist_t
*status
= smartlist_create();
1682 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
1687 or_connection_t
*conn
;
1688 if (base_conn
->type
!= CONN_TYPE_OR
|| base_conn
->marked_for_close
)
1690 conn
= TO_OR_CONN(base_conn
);
1691 if (conn
->_base
.state
== OR_CONN_STATE_OPEN
)
1692 state
= "CONNECTED";
1693 else if (conn
->nickname
)
1697 orconn_target_get_name(name
, sizeof(name
), conn
);
1698 slen
= strlen(name
)+strlen(state
)+2;
1699 s
= tor_malloc(slen
+1);
1700 tor_snprintf(s
, slen
, "%s %s", name
, state
);
1701 smartlist_add(status
, s
);
1702 } SMARTLIST_FOREACH_END(base_conn
);
1703 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1704 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1705 smartlist_free(status
);
1706 } else if (!strcmpstart(question
, "address-mappings/")) {
1707 time_t min_e
, max_e
;
1708 smartlist_t
*mappings
;
1709 question
+= strlen("address-mappings/");
1710 if (!strcmp(question
, "all")) {
1711 min_e
= 0; max_e
= TIME_MAX
;
1712 } else if (!strcmp(question
, "cache")) {
1713 min_e
= 2; max_e
= TIME_MAX
;
1714 } else if (!strcmp(question
, "config")) {
1715 min_e
= 0; max_e
= 0;
1716 } else if (!strcmp(question
, "control")) {
1717 min_e
= 1; max_e
= 1;
1721 mappings
= smartlist_create();
1722 addressmap_get_mappings(mappings
, min_e
, max_e
, 1);
1723 *answer
= smartlist_join_strings(mappings
, "\r\n", 0, NULL
);
1724 SMARTLIST_FOREACH(mappings
, char *, cp
, tor_free(cp
));
1725 smartlist_free(mappings
);
1726 } else if (!strcmpstart(question
, "status/")) {
1727 /* Note that status/ is not a catch-all for events; there's only supposed
1728 * to be a status GETINFO if there's a corresponding STATUS event. */
1729 if (!strcmp(question
, "status/circuit-established")) {
1730 *answer
= tor_strdup(can_complete_circuit
? "1" : "0");
1731 } else if (!strcmp(question
, "status/enough-dir-info")) {
1732 *answer
= tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
1733 } else if (!strcmp(question
, "status/good-server-descriptor") ||
1734 !strcmp(question
, "status/accepted-server-descriptor")) {
1735 /* They're equivalent for now, until we can figure out how to make
1736 * good-server-descriptor be what we want. See comment in
1737 * control-spec.txt. */
1738 *answer
= tor_strdup(directories_have_accepted_server_descriptor()
1740 } else if (!strcmp(question
, "status/reachability-succeeded/or")) {
1741 *answer
= tor_strdup(check_whether_orport_reachable() ? "1" : "0");
1742 } else if (!strcmp(question
, "status/reachability-succeeded/dir")) {
1743 *answer
= tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
1744 } else if (!strcmp(question
, "status/reachability-succeeded")) {
1745 *answer
= tor_malloc(16);
1746 tor_snprintf(*answer
, 16, "OR=%d DIR=%d",
1747 check_whether_orport_reachable() ? 1 : 0,
1748 check_whether_dirport_reachable() ? 1 : 0);
1749 } else if (!strcmp(question
, "status/bootstrap-phase")) {
1750 *answer
= tor_strdup(last_sent_bootstrap_message
);
1751 } else if (!strcmpstart(question
, "status/version/")) {
1752 int is_server
= server_mode(get_options());
1753 networkstatus_t
*c
= networkstatus_get_latest_consensus();
1754 version_status_t status
;
1755 const char *recommended
;
1757 recommended
= is_server
? c
->server_versions
: c
->client_versions
;
1758 status
= tor_version_is_obsolete(VERSION
, recommended
);
1761 status
= VS_UNKNOWN
;
1764 if (!strcmp(question
, "status/version/recommended")) {
1765 *answer
= tor_strdup(recommended
);
1768 if (!strcmp(question
, "status/version/current")) {
1771 case VS_RECOMMENDED
: *answer
= tor_strdup("recommended"); break;
1772 case VS_OLD
: *answer
= tor_strdup("obsolete"); break;
1773 case VS_NEW
: *answer
= tor_strdup("new"); break;
1774 case VS_NEW_IN_SERIES
: *answer
= tor_strdup("new in series"); break;
1775 case VS_UNRECOMMENDED
: *answer
= tor_strdup("unrecommended"); break;
1776 case VS_EMPTY
: *answer
= tor_strdup("none recommended"); break;
1777 case VS_UNKNOWN
: *answer
= tor_strdup("unknown"); break;
1778 default: tor_fragile_assert();
1780 } else if (!strcmp(question
, "status/version/num-versioning") ||
1781 !strcmp(question
, "status/version/num-concurring")) {
1783 tor_snprintf(s
, sizeof(s
), "%d", get_n_authorities(V3_AUTHORITY
));
1784 *answer
= tor_strdup(s
);
1785 log_warn(LD_GENERAL
, "%s is deprecated; it no longer gives useful "
1786 "information", question
);
1788 } else if (!strcmp(question
, "status/clients-seen")) {
1789 char *bridge_stats
= geoip_get_bridge_stats_controller(time(NULL
));
1790 if (!bridge_stats
) {
1791 *errmsg
= "No bridge-client stats available";
1794 *answer
= bridge_stats
;
1802 /** Callback function for GETINFO: on a given control connection, try to
1803 * answer the question <b>q</b> and store the newly-allocated answer in
1804 * *<b>a</b>. If an internal error occurs, return -1 and optionally set
1805 * *<b>error_out</b> to point to an error message to be delivered to the
1806 * controller. On success, _or if the key is not recognized_, return 0. Do not
1807 * set <b>a</b> if the key is not recognized.
1809 typedef int (*getinfo_helper_t
)(control_connection_t
*,
1810 const char *q
, char **a
,
1811 const char **error_out
);
1813 /** A single item for the GETINFO question-to-answer-function table. */
1814 typedef struct getinfo_item_t
{
1815 const char *varname
; /**< The value (or prefix) of the question. */
1816 getinfo_helper_t fn
; /**< The function that knows the answer: NULL if
1817 * this entry is documentation-only. */
1818 const char *desc
; /**< Description of the variable. */
1819 int is_prefix
; /** Must varname match exactly, or must it be a prefix? */
1822 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
1823 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
1824 #define DOC(name, desc) { name, NULL, desc, 0 }
1826 /** Table mapping questions accepted by GETINFO to the functions that know how
1827 * to answer them. */
1828 static const getinfo_item_t getinfo_items
[] = {
1829 ITEM("version", misc
, "The current version of Tor."),
1830 ITEM("config-file", misc
, "Current location of the \"torrc\" file."),
1831 ITEM("config-text", misc
,
1832 "Return the string that would be written by a saveconf command."),
1833 ITEM("accounting/bytes", accounting
,
1834 "Number of bytes read/written so far in the accounting interval."),
1835 ITEM("accounting/bytes-left", accounting
,
1836 "Number of bytes left to write/read so far in the accounting interval."),
1837 ITEM("accounting/enabled", accounting
, "Is accounting currently enabled?"),
1838 ITEM("accounting/hibernating", accounting
, "Are we hibernating or awake?"),
1839 ITEM("accounting/interval-start", accounting
,
1840 "Time when the accounting period starts."),
1841 ITEM("accounting/interval-end", accounting
,
1842 "Time when the accounting period ends."),
1843 ITEM("accounting/interval-wake", accounting
,
1844 "Time to wake up in this accounting period."),
1845 ITEM("helper-nodes", entry_guards
, NULL
), /* deprecated */
1846 ITEM("entry-guards", entry_guards
,
1847 "Which nodes are we using as entry guards?"),
1848 ITEM("fingerprint", misc
, NULL
),
1849 PREFIX("config/", config
, "Current configuration values."),
1851 "List of configuration options, types, and documentation."),
1852 ITEM("info/names", misc
,
1853 "List of GETINFO options, types, and documentation."),
1854 ITEM("events/names", misc
,
1855 "Events that the controller can ask for with SETEVENTS."),
1856 ITEM("features/names", misc
, "What arguments can USEFEATURE take?"),
1857 PREFIX("desc/id/", dir
, "Router descriptors by ID."),
1858 PREFIX("desc/name/", dir
, "Router descriptors by nickname."),
1859 ITEM("desc/all-recent", dir
,
1860 "All non-expired, non-superseded router descriptors."),
1861 ITEM("desc/all-recent-extrainfo-hack", dir
, NULL
), /* Hack. */
1862 PREFIX("extra-info/digest/", dir
, "Extra-info documents by digest."),
1863 ITEM("ns/all", networkstatus
,
1864 "Brief summary of router status (v2 directory format)"),
1865 PREFIX("ns/id/", networkstatus
,
1866 "Brief summary of router status by ID (v2 directory format)."),
1867 PREFIX("ns/name/", networkstatus
,
1868 "Brief summary of router status by nickname (v2 directory format)."),
1869 PREFIX("ns/purpose/", networkstatus
,
1870 "Brief summary of router status by purpose (v2 directory format)."),
1872 ITEM("network-status", dir
,
1873 "Brief summary of router status (v1 directory format)"),
1874 ITEM("circuit-status", events
, "List of current circuits originating here."),
1875 ITEM("stream-status", events
,"List of current streams."),
1876 ITEM("orconn-status", events
, "A list of current OR connections."),
1877 PREFIX("address-mappings/", events
, NULL
),
1878 DOC("address-mappings/all", "Current address mappings."),
1879 DOC("address-mappings/cache", "Current cached DNS replies."),
1880 DOC("address-mappings/config",
1881 "Current address mappings from configuration."),
1882 DOC("address-mappings/control", "Current address mappings from controller."),
1883 PREFIX("status/", events
, NULL
),
1884 DOC("status/circuit-established",
1885 "Whether we think client functionality is working."),
1886 DOC("status/enough-dir-info",
1887 "Whether we have enough up-to-date directory information to build "
1889 DOC("status/bootstrap-phase",
1890 "The last bootstrap phase status event that Tor sent."),
1891 DOC("status/clients-seen",
1892 "Breakdown of client countries seen by a bridge."),
1893 DOC("status/version/recommended", "List of currently recommended versions."),
1894 DOC("status/version/current", "Status of the current version."),
1895 DOC("status/version/num-versioning", "Number of versioning authorities."),
1896 DOC("status/version/num-concurring",
1897 "Number of versioning authorities agreeing on the status of the "
1899 ITEM("address", misc
, "IP address of this Tor host, if we can guess it."),
1900 ITEM("dir-usage", misc
, "Breakdown of bytes transferred over DirPort."),
1901 PREFIX("desc-annotations/id/", dir
, "Router annotations by hexdigest."),
1902 PREFIX("dir/server/", dir
,"Router descriptors as retrieved from a DirPort."),
1903 PREFIX("dir/status/", dir
,
1904 "v2 networkstatus docs as retrieved from a DirPort."),
1905 ITEM("dir/status-vote/current/consensus", dir
,
1906 "v3 Networkstatus consensus as retrieved from a DirPort."),
1907 PREFIX("exit-policy/default", policies
,
1908 "The default value appended to the configured exit policy."),
1909 PREFIX("ip-to-country/", geoip
, "Perform a GEOIP lookup"),
1910 { NULL
, NULL
, NULL
, 0 }
1913 /** Allocate and return a list of recognized GETINFO options. */
1915 list_getinfo_options(void)
1919 smartlist_t
*lines
= smartlist_create();
1921 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
1922 if (!getinfo_items
[i
].desc
)
1925 tor_asprintf(&buf
, "%s%s -- %s\n",
1926 getinfo_items
[i
].varname
,
1927 getinfo_items
[i
].is_prefix
? "*" : "",
1928 getinfo_items
[i
].desc
);
1929 smartlist_add(lines
, buf
);
1931 smartlist_sort_strings(lines
);
1933 ans
= smartlist_join_strings(lines
, "", 0, NULL
);
1934 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
1935 smartlist_free(lines
);
1940 /** Lookup the 'getinfo' entry <b>question</b>, and return
1941 * the answer in <b>*answer</b> (or NULL if key not recognized).
1942 * Return 0 if success or unrecognized, or -1 if recognized but
1943 * internal error. */
1945 handle_getinfo_helper(control_connection_t
*control_conn
,
1946 const char *question
, char **answer
,
1947 const char **err_out
)
1950 *answer
= NULL
; /* unrecognized key by default */
1952 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
1954 if (getinfo_items
[i
].is_prefix
)
1955 match
= !strcmpstart(question
, getinfo_items
[i
].varname
);
1957 match
= !strcmp(question
, getinfo_items
[i
].varname
);
1959 tor_assert(getinfo_items
[i
].fn
);
1960 return getinfo_items
[i
].fn(control_conn
, question
, answer
, err_out
);
1964 return 0; /* unrecognized */
1967 /** Called when we receive a GETINFO command. Try to fetch all requested
1968 * information, and reply with information or error message. */
1970 handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
1973 smartlist_t
*questions
= smartlist_create();
1974 smartlist_t
*answers
= smartlist_create();
1975 smartlist_t
*unrecognized
= smartlist_create();
1976 char *msg
= NULL
, *ans
= NULL
;
1978 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
1980 smartlist_split_string(questions
, body
, " ",
1981 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1982 SMARTLIST_FOREACH_BEGIN(questions
, const char *, q
) {
1983 const char *errmsg
= NULL
;
1984 if (handle_getinfo_helper(conn
, q
, &ans
, &errmsg
) < 0) {
1986 errmsg
= "Internal error";
1987 connection_printf_to_buf(conn
, "551 %s\r\n", errmsg
);
1991 smartlist_add(unrecognized
, (char*)q
);
1993 smartlist_add(answers
, tor_strdup(q
));
1994 smartlist_add(answers
, ans
);
1996 } SMARTLIST_FOREACH_END(q
);
1997 if (smartlist_len(unrecognized
)) {
1998 for (i
=0; i
< smartlist_len(unrecognized
)-1; ++i
)
1999 connection_printf_to_buf(conn
,
2000 "552-Unrecognized key \"%s\"\r\n",
2001 (char*)smartlist_get(unrecognized
, i
));
2002 connection_printf_to_buf(conn
,
2003 "552 Unrecognized key \"%s\"\r\n",
2004 (char*)smartlist_get(unrecognized
, i
));
2008 for (i
= 0; i
< smartlist_len(answers
); i
+= 2) {
2009 char *k
= smartlist_get(answers
, i
);
2010 char *v
= smartlist_get(answers
, i
+1);
2011 if (!strchr(v
, '\n') && !strchr(v
, '\r')) {
2012 connection_printf_to_buf(conn
, "250-%s=", k
);
2013 connection_write_str_to_buf(v
, conn
);
2014 connection_write_str_to_buf("\r\n", conn
);
2018 esc_len
= write_escaped_data(v
, strlen(v
), &esc
);
2019 connection_printf_to_buf(conn
, "250+%s=\r\n", k
);
2020 connection_write_to_buf(esc
, esc_len
, TO_CONN(conn
));
2024 connection_write_str_to_buf("250 OK\r\n", conn
);
2027 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
2028 smartlist_free(answers
);
2029 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
2030 smartlist_free(questions
);
2031 smartlist_free(unrecognized
);
2037 /** Given a string, convert it to a circuit purpose. */
2039 circuit_purpose_from_string(const char *string
)
2041 if (!strcasecmpstart(string
, "purpose="))
2042 string
+= strlen("purpose=");
2044 if (!strcasecmp(string
, "general"))
2045 return CIRCUIT_PURPOSE_C_GENERAL
;
2046 else if (!strcasecmp(string
, "controller"))
2047 return CIRCUIT_PURPOSE_CONTROLLER
;
2049 return CIRCUIT_PURPOSE_UNKNOWN
;
2052 /** Return a newly allocated smartlist containing the arguments to the command
2053 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
2054 * or if <b>max_args</b> is nonnegative and there are more than
2055 * <b>max_args</b> arguments, send a 512 error to the controller, using
2056 * <b>command</b> as the command name in the error message. */
2057 static smartlist_t
*
2058 getargs_helper(const char *command
, control_connection_t
*conn
,
2059 const char *body
, int min_args
, int max_args
)
2061 smartlist_t
*args
= smartlist_create();
2062 smartlist_split_string(args
, body
, " ",
2063 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2064 if (smartlist_len(args
) < min_args
) {
2065 connection_printf_to_buf(conn
, "512 Missing argument to %s\r\n",command
);
2067 } else if (max_args
>= 0 && smartlist_len(args
) > max_args
) {
2068 connection_printf_to_buf(conn
, "512 Too many arguments to %s\r\n",command
);
2073 SMARTLIST_FOREACH(args
, char *, s
, tor_free(s
));
2074 smartlist_free(args
);
2078 /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
2079 * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
2080 * such element exists. */
2082 find_element_starting_with(smartlist_t
*sl
, int start_at
, const char *prefix
)
2085 for (i
= start_at
; i
< smartlist_len(sl
); ++i
) {
2086 const char *elt
= smartlist_get(sl
, i
);
2087 if (!strcasecmpstart(elt
, prefix
))
2093 /** Helper. Return true iff s is an argument that we should treat as a
2094 * key-value pair. */
2096 is_keyval_pair(const char *s
)
2098 /* An argument is a key-value pair if it has an =, and it isn't of the form
2099 * $fingeprint=name */
2100 return strchr(s
, '=') && s
[0] != '$';
2103 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
2104 * circuit, and report success or failure. */
2106 handle_control_extendcircuit(control_connection_t
*conn
, uint32_t len
,
2109 smartlist_t
*router_nicknames
=NULL
, *routers
=NULL
;
2110 origin_circuit_t
*circ
= NULL
;
2112 uint8_t intended_purpose
= CIRCUIT_PURPOSE_C_GENERAL
;
2116 router_nicknames
= smartlist_create();
2118 args
= getargs_helper("EXTENDCIRCUIT", conn
, body
, 1, -1);
2122 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,0));
2125 const char *purp
= find_element_starting_with(args
, 1, "PURPOSE=");
2128 intended_purpose
= circuit_purpose_from_string(purp
);
2129 if (intended_purpose
== CIRCUIT_PURPOSE_UNKNOWN
) {
2130 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
2131 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2132 smartlist_free(args
);
2137 if ((smartlist_len(args
) == 1) ||
2138 (smartlist_len(args
) >= 2 && is_keyval_pair(smartlist_get(args
, 1)))) {
2139 // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
2140 circ
= circuit_launch_by_router(intended_purpose
, NULL
,
2141 CIRCLAUNCH_NEED_CAPACITY
);
2143 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
2145 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
2146 (unsigned long)circ
->global_identifier
);
2148 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2149 smartlist_free(args
);
2152 // "EXTENDCIRCUIT 0 router1,router2" ||
2153 // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
2156 if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
,0)))) {
2157 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2158 (char*)smartlist_get(args
, 0));
2159 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2160 smartlist_free(args
);
2164 smartlist_split_string(router_nicknames
, smartlist_get(args
,1), ",", 0, 0);
2166 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2167 smartlist_free(args
);
2169 routers
= smartlist_create();
2170 SMARTLIST_FOREACH(router_nicknames
, const char *, n
,
2172 routerinfo_t
*r
= router_get_by_nickname(n
, 1);
2174 connection_printf_to_buf(conn
, "552 No such router \"%s\"\r\n", n
);
2177 smartlist_add(routers
, r
);
2179 if (!smartlist_len(routers
)) {
2180 connection_write_str_to_buf("512 No router names provided\r\n", conn
);
2185 /* start a new circuit */
2186 circ
= origin_circuit_init(intended_purpose
, 0);
2189 /* now circ refers to something that is ready to be extended */
2190 SMARTLIST_FOREACH(routers
, routerinfo_t
*, r
,
2192 extend_info_t
*info
= extend_info_from_router(r
);
2193 circuit_append_new_exit(circ
, info
);
2194 extend_info_free(info
);
2197 /* now that we've populated the cpath, start extending */
2200 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
2201 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
2202 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
2206 if (circ
->_base
.state
== CIRCUIT_STATE_OPEN
) {
2208 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
2209 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
2210 log_info(LD_CONTROL
,
2211 "send_next_onion_skin failed; circuit marked for closing.");
2212 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
2213 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn
);
2219 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
2220 (unsigned long)circ
->global_identifier
);
2221 if (zero_circ
) /* send a 'launched' event, for completeness */
2222 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
2224 SMARTLIST_FOREACH(router_nicknames
, char *, n
, tor_free(n
));
2225 smartlist_free(router_nicknames
);
2226 smartlist_free(routers
);
2230 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
2231 * circuit and it's a valid purpose, change it. */
2233 handle_control_setcircuitpurpose(control_connection_t
*conn
,
2234 uint32_t len
, const char *body
)
2236 origin_circuit_t
*circ
= NULL
;
2237 uint8_t new_purpose
;
2239 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
2241 args
= getargs_helper("SETCIRCUITPURPOSE", conn
, body
, 2, -1);
2245 if (!(circ
= get_circ(smartlist_get(args
,0)))) {
2246 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2247 (char*)smartlist_get(args
, 0));
2252 const char *purp
= find_element_starting_with(args
,1,"PURPOSE=");
2253 new_purpose
= circuit_purpose_from_string(purp
);
2254 if (new_purpose
== CIRCUIT_PURPOSE_UNKNOWN
) {
2255 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
2260 circ
->_base
.purpose
= new_purpose
;
2261 connection_write_str_to_buf("250 OK\r\n", conn
);
2265 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2266 smartlist_free(args
);
2271 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
2272 * stream, and report success or failure. */
2274 handle_control_attachstream(control_connection_t
*conn
, uint32_t len
,
2277 edge_connection_t
*ap_conn
= NULL
;
2278 origin_circuit_t
*circ
= NULL
;
2281 crypt_path_t
*cpath
=NULL
;
2282 int hop
=0, hop_line_ok
=1;
2285 args
= getargs_helper("ATTACHSTREAM", conn
, body
, 2, -1);
2289 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,1));
2291 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))) {
2292 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2293 (char*)smartlist_get(args
, 0));
2294 } else if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
, 1)))) {
2295 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2296 (char*)smartlist_get(args
, 1));
2298 const char *hopstring
= find_element_starting_with(args
,2,"HOP=");
2300 hopstring
+= strlen("HOP=");
2301 hop
= (int) tor_parse_ulong(hopstring
, 10, 0, INT_MAX
,
2302 &hop_line_ok
, NULL
);
2303 if (!hop_line_ok
) { /* broken hop line */
2304 connection_printf_to_buf(conn
, "552 Bad value hop=%s\r\n", hopstring
);
2308 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2309 smartlist_free(args
);
2310 if (!ap_conn
|| (!zero_circ
&& !circ
) || !hop_line_ok
)
2313 if (ap_conn
->_base
.state
!= AP_CONN_STATE_CONTROLLER_WAIT
&&
2314 ap_conn
->_base
.state
!= AP_CONN_STATE_CONNECT_WAIT
&&
2315 ap_conn
->_base
.state
!= AP_CONN_STATE_RESOLVE_WAIT
) {
2316 connection_write_str_to_buf(
2317 "555 Connection is not managed by controller.\r\n",
2322 /* Do we need to detach it first? */
2323 if (ap_conn
->_base
.state
!= AP_CONN_STATE_CONTROLLER_WAIT
) {
2324 circuit_t
*tmpcirc
= circuit_get_by_edge_conn(ap_conn
);
2325 connection_edge_end(ap_conn
, END_STREAM_REASON_TIMEOUT
);
2326 /* Un-mark it as ending, since we're going to reuse it. */
2327 ap_conn
->edge_has_sent_end
= 0;
2328 ap_conn
->end_reason
= 0;
2330 circuit_detach_stream(tmpcirc
,ap_conn
);
2331 ap_conn
->_base
.state
= AP_CONN_STATE_CONTROLLER_WAIT
;
2334 if (circ
&& (circ
->_base
.state
!= CIRCUIT_STATE_OPEN
)) {
2335 connection_write_str_to_buf(
2336 "551 Can't attach stream to non-open origin circuit\r\n",
2340 /* Is this a single hop circuit? */
2341 if (circ
&& (circuit_get_cpath_len(circ
)<2 || hop
==1)) {
2342 routerinfo_t
*r
= NULL
;
2344 if (circ
->build_state
&&
2345 circ
->build_state
->chosen_exit
&&
2346 !tor_digest_is_zero(circ
->build_state
->chosen_exit
->identity_digest
)) {
2347 exit_digest
= circ
->build_state
->chosen_exit
->identity_digest
;
2348 r
= router_get_by_digest(exit_digest
);
2350 /* Do both the client and relay allow one-hop exit circuits? */
2351 if (!r
|| !r
->allow_single_hop_exits
||
2352 !get_options()->AllowSingleHopCircuits
) {
2353 connection_write_str_to_buf(
2354 "551 Can't attach stream to this one-hop circuit.\r\n", conn
);
2357 ap_conn
->chosen_exit_name
= tor_strdup(hex_str(exit_digest
, DIGEST_LEN
));
2360 if (circ
&& hop
>0) {
2361 /* find this hop in the circuit, and set cpath */
2362 cpath
= circuit_get_cpath_hop(circ
, hop
);
2364 connection_printf_to_buf(conn
,
2365 "551 Circuit doesn't have %d hops.\r\n", hop
);
2369 if (connection_ap_handshake_rewrite_and_attach(ap_conn
, circ
, cpath
) < 0) {
2370 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn
);
2373 send_control_done(conn
);
2377 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
2378 * descriptor, and report success or failure. */
2380 handle_control_postdescriptor(control_connection_t
*conn
, uint32_t len
,
2384 const char *msg
=NULL
;
2385 uint8_t purpose
= ROUTER_PURPOSE_GENERAL
;
2386 int cache
= 0; /* eventually, we may switch this to 1 */
2388 char *cp
= memchr(body
, '\n', len
);
2389 smartlist_t
*args
= smartlist_create();
2393 smartlist_split_string(args
, body
, " ",
2394 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2395 SMARTLIST_FOREACH(args
, char *, option
,
2397 if (!strcasecmpstart(option
, "purpose=")) {
2398 option
+= strlen("purpose=");
2399 purpose
= router_purpose_from_string(option
);
2400 if (purpose
== ROUTER_PURPOSE_UNKNOWN
) {
2401 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n",
2405 } else if (!strcasecmpstart(option
, "cache=")) {
2406 option
+= strlen("cache=");
2407 if (!strcasecmp(option
, "no"))
2409 else if (!strcasecmp(option
, "yes"))
2412 connection_printf_to_buf(conn
, "552 Unknown cache request \"%s\"\r\n",
2416 } else { /* unrecognized argument? */
2417 connection_printf_to_buf(conn
,
2418 "512 Unexpected argument \"%s\" to postdescriptor\r\n", option
);
2423 read_escaped_data(cp
, len
-(cp
-body
), &desc
);
2425 switch (router_load_single_router(desc
, purpose
, cache
, &msg
)) {
2427 if (!msg
) msg
= "Could not parse descriptor";
2428 connection_printf_to_buf(conn
, "554 %s\r\n", msg
);
2431 if (!msg
) msg
= "Descriptor not added";
2432 connection_printf_to_buf(conn
, "251 %s\r\n",msg
);
2435 send_control_done(conn
);
2441 SMARTLIST_FOREACH(args
, char *, arg
, tor_free(arg
));
2442 smartlist_free(args
);
2446 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
2447 * address of the named AP stream, and report success or failure. */
2449 handle_control_redirectstream(control_connection_t
*conn
, uint32_t len
,
2452 edge_connection_t
*ap_conn
= NULL
;
2453 char *new_addr
= NULL
;
2454 uint16_t new_port
= 0;
2458 args
= getargs_helper("REDIRECTSTREAM", conn
, body
, 2, -1);
2462 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))
2463 || !ap_conn
->socks_request
) {
2464 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2465 (char*)smartlist_get(args
, 0));
2468 if (smartlist_len(args
) > 2) { /* they included a port too */
2469 new_port
= (uint16_t) tor_parse_ulong(smartlist_get(args
, 2),
2470 10, 1, 65535, &ok
, NULL
);
2473 connection_printf_to_buf(conn
, "512 Cannot parse port \"%s\"\r\n",
2474 (char*)smartlist_get(args
, 2));
2476 new_addr
= tor_strdup(smartlist_get(args
, 1));
2480 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2481 smartlist_free(args
);
2485 strlcpy(ap_conn
->socks_request
->address
, new_addr
,
2486 sizeof(ap_conn
->socks_request
->address
));
2488 ap_conn
->socks_request
->port
= new_port
;
2490 send_control_done(conn
);
2494 /** Called when we get a CLOSESTREAM command; try to close the named stream
2495 * and report success or failure. */
2497 handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
2500 edge_connection_t
*ap_conn
=NULL
;
2506 args
= getargs_helper("CLOSESTREAM", conn
, body
, 2, -1);
2510 else if (!(ap_conn
= get_stream(smartlist_get(args
, 0))))
2511 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2512 (char*)smartlist_get(args
, 0));
2514 reason
= (uint8_t) tor_parse_ulong(smartlist_get(args
,1), 10, 0, 255,
2517 connection_printf_to_buf(conn
, "552 Unrecognized reason \"%s\"\r\n",
2518 (char*)smartlist_get(args
, 1));
2522 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2523 smartlist_free(args
);
2527 connection_mark_unattached_ap(ap_conn
, reason
);
2528 send_control_done(conn
);
2532 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
2533 * and report success or failure. */
2535 handle_control_closecircuit(control_connection_t
*conn
, uint32_t len
,
2538 origin_circuit_t
*circ
= NULL
;
2543 args
= getargs_helper("CLOSECIRCUIT", conn
, body
, 1, -1);
2547 if (!(circ
=get_circ(smartlist_get(args
, 0))))
2548 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2549 (char*)smartlist_get(args
, 0));
2552 for (i
=1; i
< smartlist_len(args
); ++i
) {
2553 if (!strcasecmp(smartlist_get(args
, i
), "IfUnused"))
2556 log_info(LD_CONTROL
, "Skipping unknown option %s",
2557 (char*)smartlist_get(args
,i
));
2560 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2561 smartlist_free(args
);
2565 if (!safe
|| !circ
->p_streams
) {
2566 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_REQUESTED
);
2569 send_control_done(conn
);
2573 /** Called when we get a RESOLVE command: start trying to resolve
2574 * the listed addresses. */
2576 handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
2579 smartlist_t
*args
, *failed
;
2581 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
2583 if (!(conn
->event_mask
& ((uint32_t)1L<<EVENT_ADDRMAP
))) {
2584 log_warn(LD_CONTROL
, "Controller asked us to resolve an address, but "
2585 "isn't listening for ADDRMAP events. It probably won't see "
2588 args
= smartlist_create();
2589 smartlist_split_string(args
, body
, " ",
2590 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2592 const char *modearg
= find_element_starting_with(args
, 0, "mode=");
2593 if (modearg
&& !strcasecmp(modearg
, "mode=reverse"))
2596 failed
= smartlist_create();
2597 SMARTLIST_FOREACH(args
, const char *, arg
, {
2598 if (!is_keyval_pair(arg
)) {
2599 if (dnsserv_launch_request(arg
, is_reverse
)<0)
2600 smartlist_add(failed
, (char*)arg
);
2604 send_control_done(conn
);
2605 SMARTLIST_FOREACH(failed
, const char *, arg
, {
2606 control_event_address_mapped(arg
, arg
, time(NULL
),
2607 "Unable to launch resolve request");
2610 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2611 smartlist_free(args
);
2612 smartlist_free(failed
);
2616 /** Called when we get a PROTOCOLINFO command: send back a reply. */
2618 handle_control_protocolinfo(control_connection_t
*conn
, uint32_t len
,
2621 const char *bad_arg
= NULL
;
2625 conn
->have_sent_protocolinfo
= 1;
2626 args
= smartlist_create();
2627 smartlist_split_string(args
, body
, " ",
2628 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2629 SMARTLIST_FOREACH(args
, const char *, arg
, {
2631 tor_parse_long(arg
, 10, 0, LONG_MAX
, &ok
, NULL
);
2638 connection_printf_to_buf(conn
, "513 No such version %s\r\n",
2640 /* Don't tolerate bad arguments when not authenticated. */
2641 if (!STATE_IS_OPEN(TO_CONN(conn
)->state
))
2642 connection_mark_for_close(TO_CONN(conn
));
2645 or_options_t
*options
= get_options();
2646 int cookies
= options
->CookieAuthentication
;
2647 char *cfile
= get_cookie_file();
2648 char *esc_cfile
= esc_for_log(cfile
);
2651 int passwd
= (options
->HashedControlPassword
!= NULL
||
2652 options
->HashedControlSessionPassword
!= NULL
);
2653 smartlist_t
*mlist
= smartlist_create();
2655 smartlist_add(mlist
, (char*)"COOKIE");
2657 smartlist_add(mlist
, (char*)"HASHEDPASSWORD");
2658 if (!cookies
&& !passwd
)
2659 smartlist_add(mlist
, (char*)"NULL");
2660 methods
= smartlist_join_strings(mlist
, ",", 0, NULL
);
2661 smartlist_free(mlist
);
2664 connection_printf_to_buf(conn
,
2665 "250-PROTOCOLINFO 1\r\n"
2666 "250-AUTH METHODS=%s%s%s\r\n"
2667 "250-VERSION Tor=%s\r\n"
2670 cookies
?" COOKIEFILE=":"",
2671 cookies
?esc_cfile
:"",
2675 tor_free(esc_cfile
);
2678 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2679 smartlist_free(args
);
2683 /** Called when we get a USEFEATURE command: parse the feature list, and
2684 * set up the control_connection's options properly. */
2686 handle_control_usefeature(control_connection_t
*conn
,
2692 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
2693 args
= smartlist_create();
2694 smartlist_split_string(args
, body
, " ",
2695 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2696 SMARTLIST_FOREACH(args
, const char *, arg
, {
2697 if (!strcasecmp(arg
, "VERBOSE_NAMES"))
2699 else if (!strcasecmp(arg
, "EXTENDED_EVENTS"))
2702 connection_printf_to_buf(conn
, "552 Unrecognized feature \"%s\"\r\n",
2710 send_control_done(conn
);
2713 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2714 smartlist_free(args
);
2718 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
2720 connection_control_finished_flushing(control_connection_t
*conn
)
2724 connection_stop_writing(TO_CONN(conn
));
2728 /** Called when <b>conn</b> has gotten its socket closed. */
2730 connection_control_reached_eof(control_connection_t
*conn
)
2734 log_info(LD_CONTROL
,"Control connection reached EOF. Closing.");
2735 connection_mark_for_close(TO_CONN(conn
));
2739 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
2740 * stage of the protocol. */
2742 is_valid_initial_command(control_connection_t
*conn
, const char *cmd
)
2744 if (conn
->_base
.state
== CONTROL_CONN_STATE_OPEN
)
2746 if (!strcasecmp(cmd
, "PROTOCOLINFO"))
2747 return !conn
->have_sent_protocolinfo
;
2748 if (!strcasecmp(cmd
, "AUTHENTICATE") ||
2749 !strcasecmp(cmd
, "QUIT"))
2754 /** Do not accept any control command of more than 1MB in length. Anything
2755 * that needs to be anywhere near this long probably means that one of our
2756 * interfaces is broken. */
2757 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
2759 /** Called when data has arrived on a v1 control connection: Try to fetch
2760 * commands from conn->inbuf, and execute them.
2763 connection_control_process_inbuf(control_connection_t
*conn
)
2766 uint32_t cmd_data_len
;
2771 tor_assert(conn
->_base
.state
== CONTROL_CONN_STATE_OPEN
||
2772 conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH
);
2774 if (!conn
->incoming_cmd
) {
2775 conn
->incoming_cmd
= tor_malloc(1024);
2776 conn
->incoming_cmd_len
= 1024;
2777 conn
->incoming_cmd_cur_len
= 0;
2780 if (conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
2781 peek_buf_has_control0_command(conn
->_base
.inbuf
)) {
2782 /* Detect v0 commands and send a "no more v0" message. */
2785 set_uint16(buf
+2, htons(0x0000)); /* type == error */
2786 set_uint16(buf
+4, htons(0x0001)); /* code == internal error */
2787 strlcpy(buf
+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
2788 "and later; upgrade your controller.",
2790 body_len
= 2+strlen(buf
+6)+2; /* code, msg, nul. */
2791 set_uint16(buf
+0, htons(body_len
));
2792 connection_write_to_buf(buf
, 4+body_len
, TO_CONN(conn
));
2793 connection_mark_for_close(TO_CONN(conn
));
2794 conn
->_base
.hold_open_until_flushed
= 1;
2802 /* First, fetch a line. */
2804 data_len
= conn
->incoming_cmd_len
- conn
->incoming_cmd_cur_len
;
2805 r
= fetch_from_buf_line(conn
->_base
.inbuf
,
2806 conn
->incoming_cmd
+conn
->incoming_cmd_cur_len
,
2809 /* Line not all here yet. Wait. */
2812 if (data_len
+ conn
->incoming_cmd_cur_len
> MAX_COMMAND_LINE_LENGTH
) {
2813 connection_write_str_to_buf("500 Line too long.\r\n", conn
);
2814 connection_stop_reading(TO_CONN(conn
));
2815 connection_mark_for_close(TO_CONN(conn
));
2816 conn
->_base
.hold_open_until_flushed
= 1;
2818 while (conn
->incoming_cmd_len
< data_len
+conn
->incoming_cmd_cur_len
)
2819 conn
->incoming_cmd_len
*= 2;
2820 conn
->incoming_cmd
= tor_realloc(conn
->incoming_cmd
,
2821 conn
->incoming_cmd_len
);
2825 tor_assert(data_len
);
2827 last_idx
= conn
->incoming_cmd_cur_len
;
2828 conn
->incoming_cmd_cur_len
+= (int)data_len
;
2830 /* We have appended a line to incoming_cmd. Is the command done? */
2831 if (last_idx
== 0 && *conn
->incoming_cmd
!= '+')
2832 /* One line command, didn't start with '+'. */
2834 /* XXXX this code duplication is kind of dumb. */
2835 if (last_idx
+3 == conn
->incoming_cmd_cur_len
&&
2836 !memcmp(conn
->incoming_cmd
+ last_idx
, ".\r\n", 3)) {
2837 /* Just appended ".\r\n"; we're done. Remove it. */
2838 conn
->incoming_cmd
[last_idx
] = '\0';
2839 conn
->incoming_cmd_cur_len
-= 3;
2841 } else if (last_idx
+2 == conn
->incoming_cmd_cur_len
&&
2842 !memcmp(conn
->incoming_cmd
+ last_idx
, ".\n", 2)) {
2843 /* Just appended ".\n"; we're done. Remove it. */
2844 conn
->incoming_cmd
[last_idx
] = '\0';
2845 conn
->incoming_cmd_cur_len
-= 2;
2848 /* Otherwise, read another line. */
2850 data_len
= conn
->incoming_cmd_cur_len
;
2851 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
2855 while ((size_t)cmd_len
< data_len
2856 && !TOR_ISSPACE(conn
->incoming_cmd
[cmd_len
]))
2859 conn
->incoming_cmd
[cmd_len
]='\0';
2860 args
= conn
->incoming_cmd
+cmd_len
+1;
2861 tor_assert(data_len
>(size_t)cmd_len
);
2862 data_len
-= (cmd_len
+1); /* skip the command and NUL we added after it */
2863 while (*args
== ' ' || *args
== '\t') {
2868 /* If the connection is already closing, ignore further commands */
2869 if (TO_CONN(conn
)->marked_for_close
) {
2873 /* Otherwise, Quit is always valid. */
2874 if (!strcasecmp(conn
->incoming_cmd
, "QUIT")) {
2875 connection_write_str_to_buf("250 closing connection\r\n", conn
);
2876 connection_mark_for_close(TO_CONN(conn
));
2877 conn
->_base
.hold_open_until_flushed
= 1;
2881 if (conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
2882 !is_valid_initial_command(conn
, conn
->incoming_cmd
)) {
2883 connection_write_str_to_buf("514 Authentication required.\r\n", conn
);
2884 connection_mark_for_close(TO_CONN(conn
));
2888 if (data_len
>= UINT32_MAX
) {
2889 connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn
);
2890 connection_mark_for_close(TO_CONN(conn
));
2894 cmd_data_len
= (uint32_t)data_len
;
2895 if (!strcasecmp(conn
->incoming_cmd
, "SETCONF")) {
2896 if (handle_control_setconf(conn
, cmd_data_len
, args
))
2898 } else if (!strcasecmp(conn
->incoming_cmd
, "RESETCONF")) {
2899 if (handle_control_resetconf(conn
, cmd_data_len
, args
))
2901 } else if (!strcasecmp(conn
->incoming_cmd
, "GETCONF")) {
2902 if (handle_control_getconf(conn
, cmd_data_len
, args
))
2904 } else if (!strcasecmp(conn
->incoming_cmd
, "+LOADCONF")) {
2905 if (handle_control_loadconf(conn
, cmd_data_len
, args
))
2907 } else if (!strcasecmp(conn
->incoming_cmd
, "SETEVENTS")) {
2908 if (handle_control_setevents(conn
, cmd_data_len
, args
))
2910 } else if (!strcasecmp(conn
->incoming_cmd
, "AUTHENTICATE")) {
2911 if (handle_control_authenticate(conn
, cmd_data_len
, args
))
2913 } else if (!strcasecmp(conn
->incoming_cmd
, "SAVECONF")) {
2914 if (handle_control_saveconf(conn
, cmd_data_len
, args
))
2916 } else if (!strcasecmp(conn
->incoming_cmd
, "SIGNAL")) {
2917 if (handle_control_signal(conn
, cmd_data_len
, args
))
2919 } else if (!strcasecmp(conn
->incoming_cmd
, "MAPADDRESS")) {
2920 if (handle_control_mapaddress(conn
, cmd_data_len
, args
))
2922 } else if (!strcasecmp(conn
->incoming_cmd
, "GETINFO")) {
2923 if (handle_control_getinfo(conn
, cmd_data_len
, args
))
2925 } else if (!strcasecmp(conn
->incoming_cmd
, "EXTENDCIRCUIT")) {
2926 if (handle_control_extendcircuit(conn
, cmd_data_len
, args
))
2928 } else if (!strcasecmp(conn
->incoming_cmd
, "SETCIRCUITPURPOSE")) {
2929 if (handle_control_setcircuitpurpose(conn
, cmd_data_len
, args
))
2931 } else if (!strcasecmp(conn
->incoming_cmd
, "SETROUTERPURPOSE")) {
2932 connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn
);
2933 } else if (!strcasecmp(conn
->incoming_cmd
, "ATTACHSTREAM")) {
2934 if (handle_control_attachstream(conn
, cmd_data_len
, args
))
2936 } else if (!strcasecmp(conn
->incoming_cmd
, "+POSTDESCRIPTOR")) {
2937 if (handle_control_postdescriptor(conn
, cmd_data_len
, args
))
2939 } else if (!strcasecmp(conn
->incoming_cmd
, "REDIRECTSTREAM")) {
2940 if (handle_control_redirectstream(conn
, cmd_data_len
, args
))
2942 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSESTREAM")) {
2943 if (handle_control_closestream(conn
, cmd_data_len
, args
))
2945 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSECIRCUIT")) {
2946 if (handle_control_closecircuit(conn
, cmd_data_len
, args
))
2948 } else if (!strcasecmp(conn
->incoming_cmd
, "USEFEATURE")) {
2949 if (handle_control_usefeature(conn
, cmd_data_len
, args
))
2951 } else if (!strcasecmp(conn
->incoming_cmd
, "RESOLVE")) {
2952 if (handle_control_resolve(conn
, cmd_data_len
, args
))
2954 } else if (!strcasecmp(conn
->incoming_cmd
, "PROTOCOLINFO")) {
2955 if (handle_control_protocolinfo(conn
, cmd_data_len
, args
))
2958 connection_printf_to_buf(conn
, "510 Unrecognized command \"%s\"\r\n",
2959 conn
->incoming_cmd
);
2962 conn
->incoming_cmd_cur_len
= 0;
2966 /** Something has happened to circuit <b>circ</b>: tell any interested
2967 * control connections. */
2969 control_event_circuit_status(origin_circuit_t
*circ
, circuit_status_event_t tp
,
2973 char extended_buf
[96];
2974 int providing_reason
=0;
2975 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS
))
2981 case CIRC_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
2982 case CIRC_EVENT_BUILT
: status
= "BUILT"; break;
2983 case CIRC_EVENT_EXTENDED
: status
= "EXTENDED"; break;
2984 case CIRC_EVENT_FAILED
: status
= "FAILED"; break;
2985 case CIRC_EVENT_CLOSED
: status
= "CLOSED"; break;
2987 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
2991 tor_snprintf(extended_buf
, sizeof(extended_buf
), "PURPOSE=%s",
2992 circuit_purpose_to_controller_string(circ
->_base
.purpose
));
2994 if (tp
== CIRC_EVENT_FAILED
|| tp
== CIRC_EVENT_CLOSED
) {
2995 const char *reason_str
= circuit_end_reason_to_control_string(reason_code
);
2996 char *reason
= NULL
;
2997 size_t n
=strlen(extended_buf
);
3000 reason
= tor_malloc(16);
3001 tor_snprintf(reason
, 16, "UNKNOWN_%d", reason_code
);
3002 reason_str
= reason
;
3004 if (reason_code
> 0 && reason_code
& END_CIRC_REASON_FLAG_REMOTE
) {
3005 tor_snprintf(extended_buf
+n
, sizeof(extended_buf
)-n
,
3006 " REASON=DESTROYED REMOTE_REASON=%s", reason_str
);
3008 tor_snprintf(extended_buf
+n
, sizeof(extended_buf
)-n
,
3009 " REASON=%s", reason_str
);
3015 char *vpath
= circuit_list_path_for_controller(circ
);
3016 const char *sp
= strlen(vpath
) ? " " : "";
3017 send_control_event(EVENT_CIRCUIT_STATUS
, ALL_FORMATS
,
3018 "650 CIRC %lu %s%s%s %s\r\n",
3019 (unsigned long)circ
->global_identifier
,
3020 status
, sp
, vpath
, extended_buf
);
3027 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
3028 * <b>buf</b>, determine the address:port combination requested on
3029 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
3032 write_stream_target_to_buf(edge_connection_t
*conn
, char *buf
, size_t len
)
3035 if (conn
->chosen_exit_name
)
3036 if (tor_snprintf(buf2
, sizeof(buf2
), ".%s.exit", conn
->chosen_exit_name
)<0)
3038 if (!conn
->socks_request
)
3040 if (tor_snprintf(buf
, len
, "%s%s%s:%d",
3041 conn
->socks_request
->address
,
3042 conn
->chosen_exit_name
? buf2
: "",
3043 !conn
->chosen_exit_name
&&
3044 connection_edge_is_rendezvous_stream(conn
) ? ".onion" : "",
3045 conn
->socks_request
->port
)<0)
3050 /** Something has happened to the stream associated with AP connection
3051 * <b>conn</b>: tell any interested control connections. */
3053 control_event_stream_status(edge_connection_t
*conn
, stream_status_event_t tp
,
3056 char reason_buf
[64];
3057 char addrport_buf
[64];
3060 origin_circuit_t
*origin_circ
= NULL
;
3062 const char *purpose
= "";
3063 tor_assert(conn
->socks_request
);
3065 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS
))
3068 if (tp
== STREAM_EVENT_CLOSED
&&
3069 (reason_code
& END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
))
3072 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
3074 reason_buf
[0] = '\0';
3077 case STREAM_EVENT_SENT_CONNECT
: status
= "SENTCONNECT"; break;
3078 case STREAM_EVENT_SENT_RESOLVE
: status
= "SENTRESOLVE"; break;
3079 case STREAM_EVENT_SUCCEEDED
: status
= "SUCCEEDED"; break;
3080 case STREAM_EVENT_FAILED
: status
= "FAILED"; break;
3081 case STREAM_EVENT_CLOSED
: status
= "CLOSED"; break;
3082 case STREAM_EVENT_NEW
: status
= "NEW"; break;
3083 case STREAM_EVENT_NEW_RESOLVE
: status
= "NEWRESOLVE"; break;
3084 case STREAM_EVENT_FAILED_RETRIABLE
: status
= "DETACHED"; break;
3085 case STREAM_EVENT_REMAP
: status
= "REMAP"; break;
3087 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3090 if (reason_code
&& (tp
== STREAM_EVENT_FAILED
||
3091 tp
== STREAM_EVENT_CLOSED
||
3092 tp
== STREAM_EVENT_FAILED_RETRIABLE
)) {
3093 const char *reason_str
= stream_end_reason_to_control_string(reason_code
);
3097 tor_snprintf(r
, 16, " UNKNOWN_%d", reason_code
);
3100 if (reason_code
& END_STREAM_REASON_FLAG_REMOTE
)
3101 tor_snprintf(reason_buf
, sizeof(reason_buf
),
3102 " REASON=END REMOTE_REASON=%s", reason_str
);
3104 tor_snprintf(reason_buf
, sizeof(reason_buf
),
3105 " REASON=%s", reason_str
);
3107 } else if (reason_code
&& tp
== STREAM_EVENT_REMAP
) {
3108 switch (reason_code
) {
3109 case REMAP_STREAM_SOURCE_CACHE
:
3110 strlcpy(reason_buf
, " SOURCE=CACHE", sizeof(reason_buf
));
3112 case REMAP_STREAM_SOURCE_EXIT
:
3113 strlcpy(reason_buf
, " SOURCE=EXIT", sizeof(reason_buf
));
3116 tor_snprintf(reason_buf
, sizeof(reason_buf
), " REASON=UNKNOWN_%d",
3118 /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
3123 if (tp
== STREAM_EVENT_NEW
) {
3124 tor_snprintf(addrport_buf
,sizeof(addrport_buf
), " SOURCE_ADDR=%s:%d",
3125 TO_CONN(conn
)->address
, TO_CONN(conn
)->port
);
3127 addrport_buf
[0] = '\0';
3130 if (tp
== STREAM_EVENT_NEW_RESOLVE
) {
3131 purpose
= " PURPOSE=DNS_REQUEST";
3132 } else if (tp
== STREAM_EVENT_NEW
) {
3133 if (conn
->is_dns_request
||
3134 (conn
->socks_request
&&
3135 SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
)))
3136 purpose
= " PURPOSE=DNS_REQUEST";
3137 else if (conn
->use_begindir
) {
3138 connection_t
*linked
= TO_CONN(conn
)->linked_conn
;
3139 int linked_dir_purpose
= -1;
3140 if (linked
&& linked
->type
== CONN_TYPE_DIR
)
3141 linked_dir_purpose
= linked
->purpose
;
3142 if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose
))
3143 purpose
= " PURPOSE=DIR_UPLOAD";
3145 purpose
= " PURPOSE=DIR_FETCH";
3147 purpose
= " PURPOSE=USER";
3150 circ
= circuit_get_by_edge_conn(conn
);
3151 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
3152 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
3153 send_control_event(EVENT_STREAM_STATUS
, ALL_FORMATS
,
3154 "650 STREAM "U64_FORMAT
" %s %lu %s%s%s%s\r\n",
3155 U64_PRINTF_ARG(conn
->_base
.global_identifier
), status
,
3157 (unsigned long)origin_circ
->global_identifier
: 0ul,
3158 buf
, reason_buf
, addrport_buf
, purpose
);
3160 /* XXX need to specify its intended exit, etc? */
3165 /** Figure out the best name for the target router of an OR connection
3166 * <b>conn</b>, and write it into the <b>len</b>-character buffer
3169 orconn_target_get_name(char *name
, size_t len
, or_connection_t
*conn
)
3171 routerinfo_t
*ri
= router_get_by_digest(conn
->identity_digest
);
3173 tor_assert(len
> MAX_VERBOSE_NICKNAME_LEN
);
3174 router_get_verbose_nickname(name
, ri
);
3175 } else if (! tor_digest_is_zero(conn
->identity_digest
)) {
3177 base16_encode(name
+1, len
-1, conn
->identity_digest
,
3180 tor_snprintf(name
, len
, "%s:%d",
3181 conn
->_base
.address
, conn
->_base
.port
);
3185 /** Called when the status of an OR connection <b>conn</b> changes: tell any
3186 * interested control connections. <b>tp</b> is the new status for the
3187 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
3188 * may be the reason why.
3191 control_event_or_conn_status(or_connection_t
*conn
, or_conn_status_event_t tp
,
3197 char ncircs_buf
[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
3199 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS
))
3204 case OR_CONN_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
3205 case OR_CONN_EVENT_CONNECTED
: status
= "CONNECTED"; break;
3206 case OR_CONN_EVENT_FAILED
: status
= "FAILED"; break;
3207 case OR_CONN_EVENT_CLOSED
: status
= "CLOSED"; break;
3208 case OR_CONN_EVENT_NEW
: status
= "NEW"; break;
3210 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3213 ncircs
= circuit_count_pending_on_or_conn(conn
);
3214 ncircs
+= conn
->n_circuits
;
3215 if (ncircs
&& (tp
== OR_CONN_EVENT_FAILED
|| tp
== OR_CONN_EVENT_CLOSED
)) {
3216 tor_snprintf(ncircs_buf
, sizeof(ncircs_buf
), "%sNCIRCS=%d",
3217 reason
? " " : "", ncircs
);
3220 orconn_target_get_name(name
, sizeof(name
), conn
);
3221 send_control_event(EVENT_OR_CONN_STATUS
, ALL_FORMATS
,
3222 "650 ORCONN %s %s %s%s%s\r\n",
3224 reason
? "REASON=" : "",
3225 orconn_end_reason_to_control_string(reason
),
3232 * Print out STREAM_BW event for a single conn
3235 control_event_stream_bandwidth(edge_connection_t
*edge_conn
)
3237 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED
)) {
3238 if (!edge_conn
->n_read
&& !edge_conn
->n_written
)
3241 send_control_event(EVENT_STREAM_BANDWIDTH_USED
, ALL_FORMATS
,
3242 "650 STREAM_BW "U64_FORMAT
" %lu %lu\r\n",
3243 U64_PRINTF_ARG(edge_conn
->_base
.global_identifier
),
3244 (unsigned long)edge_conn
->n_read
,
3245 (unsigned long)edge_conn
->n_written
);
3247 edge_conn
->n_written
= edge_conn
->n_read
= 0;
3253 /** A second or more has elapsed: tell any interested control
3254 * connections how much bandwidth streams have used. */
3256 control_event_stream_bandwidth_used(void)
3258 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED
)) {
3259 smartlist_t
*conns
= get_connection_array();
3260 edge_connection_t
*edge_conn
;
3262 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
)
3264 if (conn
->type
!= CONN_TYPE_AP
)
3266 edge_conn
= TO_EDGE_CONN(conn
);
3267 if (!edge_conn
->n_read
&& !edge_conn
->n_written
)
3270 send_control_event(EVENT_STREAM_BANDWIDTH_USED
, ALL_FORMATS
,
3271 "650 STREAM_BW "U64_FORMAT
" %lu %lu\r\n",
3272 U64_PRINTF_ARG(edge_conn
->_base
.global_identifier
),
3273 (unsigned long)edge_conn
->n_read
,
3274 (unsigned long)edge_conn
->n_written
);
3276 edge_conn
->n_written
= edge_conn
->n_read
= 0;
3278 SMARTLIST_FOREACH_END(conn
);
3284 /** A second or more has elapsed: tell any interested control
3285 * connections how much bandwidth we used. */
3287 control_event_bandwidth_used(uint32_t n_read
, uint32_t n_written
)
3289 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED
)) {
3290 send_control_event(EVENT_BANDWIDTH_USED
, ALL_FORMATS
,
3291 "650 BW %lu %lu\r\n",
3292 (unsigned long)n_read
,
3293 (unsigned long)n_written
);
3299 /** Called when we are sending a log message to the controllers: suspend
3300 * sending further log messages to the controllers until we're done. Used by
3301 * CONN_LOG_PROTECT. */
3303 disable_control_logging(void)
3305 ++disable_log_messages
;
3308 /** We're done sending a log message to the controllers: re-enable controller
3309 * logging. Used by CONN_LOG_PROTECT. */
3311 enable_control_logging(void)
3313 if (--disable_log_messages
< 0)
3317 /** We got a log message: tell any interested control connections. */
3319 control_event_logmsg(int severity
, uint32_t domain
, const char *msg
)
3323 /* Don't even think of trying to add stuff to a buffer from a cpuworker
3325 if (! in_main_thread())
3328 if (disable_log_messages
)
3331 if (domain
== LD_BUG
&& EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
) &&
3332 severity
<= LOG_NOTICE
) {
3333 char *esc
= esc_for_log(msg
);
3334 ++disable_log_messages
;
3335 control_event_general_status(severity
, "BUG REASON=\"%s\"", esc
);
3336 --disable_log_messages
;
3340 event
= log_severity_to_event(severity
);
3341 if (event
>= 0 && EVENT_IS_INTERESTING(event
)) {
3344 if (strchr(msg
, '\n')) {
3346 b
= tor_strdup(msg
);
3347 for (cp
= b
; *cp
; ++cp
)
3348 if (*cp
== '\r' || *cp
== '\n')
3352 case LOG_DEBUG
: s
= "DEBUG"; break;
3353 case LOG_INFO
: s
= "INFO"; break;
3354 case LOG_NOTICE
: s
= "NOTICE"; break;
3355 case LOG_WARN
: s
= "WARN"; break;
3356 case LOG_ERR
: s
= "ERR"; break;
3357 default: s
= "UnknownLogSeverity"; break;
3359 ++disable_log_messages
;
3360 send_control_event(event
, ALL_FORMATS
, "650 %s %s\r\n", s
, b
?b
:msg
);
3361 --disable_log_messages
;
3366 /** Called whenever we receive new router descriptors: tell any
3367 * interested control connections. <b>routers</b> is a list of
3371 control_event_descriptors_changed(smartlist_t
*routers
)
3375 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC
))
3379 smartlist_t
*names
= smartlist_create();
3382 SMARTLIST_FOREACH(routers
, routerinfo_t
*, ri
, {
3383 char *b
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
3384 router_get_verbose_nickname(b
, ri
);
3385 smartlist_add(names
, b
);
3387 ids
= smartlist_join_strings(names
, " ", 0, &names_len
);
3388 names_len
= strlen(ids
)+32;
3389 msg
= tor_malloc(names_len
);
3390 tor_snprintf(msg
, names_len
, "650 NEWDESC %s\r\n", ids
);
3391 send_control_event_string(EVENT_NEW_DESC
, ALL_FORMATS
, msg
);
3394 SMARTLIST_FOREACH(names
, char *, cp
, tor_free(cp
));
3395 smartlist_free(names
);
3400 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
3401 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
3402 * <b>error</b> is non-NULL, it is an error code describing the failure
3403 * mode of the mapping.
3406 control_event_address_mapped(const char *from
, const char *to
, time_t expires
,
3409 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP
))
3412 if (expires
< 3 || expires
== TIME_MAX
)
3413 send_control_event(EVENT_ADDRMAP
, ALL_FORMATS
,
3414 "650 ADDRMAP %s %s NEVER %s\r\n", from
, to
,
3417 char buf
[ISO_TIME_LEN
+1];
3418 char buf2
[ISO_TIME_LEN
+1];
3419 format_local_iso_time(buf
,expires
);
3420 format_iso_time(buf2
,expires
);
3421 send_control_event(EVENT_ADDRMAP
, ALL_FORMATS
,
3422 "650 ADDRMAP %s %s \"%s\""
3423 " %s%sEXPIRES=\"%s\"\r\n",
3425 error
?error
:"", error
?" ":"",
3432 /** The authoritative dirserver has received a new descriptor that
3433 * has passed basic syntax checks and is properly self-signed.
3435 * Notify any interested party of the new descriptor and what has
3436 * been done with it, and also optionally give an explanation/reason. */
3438 control_event_or_authdir_new_descriptor(const char *action
,
3439 const char *desc
, size_t desclen
,
3442 char firstline
[1024];
3448 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS
))
3451 tor_snprintf(firstline
, sizeof(firstline
),
3452 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
3456 /* Escape the server descriptor properly */
3457 esclen
= write_escaped_data(desc
, desclen
, &esc
);
3459 totallen
= strlen(firstline
) + esclen
+ 1;
3460 buf
= tor_malloc(totallen
);
3461 strlcpy(buf
, firstline
, totallen
);
3462 strlcpy(buf
+strlen(firstline
), esc
, totallen
);
3463 send_control_event_string(EVENT_AUTHDIR_NEWDESCS
, ALL_FORMATS
,
3465 send_control_event_string(EVENT_AUTHDIR_NEWDESCS
, ALL_FORMATS
,
3473 /** Helper function for NS-style events. Constructs and sends an event
3474 * of type <b>event</b> with string <b>event_string</b> out of the set of
3475 * networkstatuses <b>statuses</b>. Currently it is used for NS events
3476 * and NEWCONSENSUS events. */
3478 control_event_networkstatus_changed_helper(smartlist_t
*statuses
,
3480 const char *event_string
)
3483 char *s
, *esc
= NULL
;
3484 if (!EVENT_IS_INTERESTING(event
) || !smartlist_len(statuses
))
3487 strs
= smartlist_create();
3488 smartlist_add(strs
, tor_strdup("650+"));
3489 smartlist_add(strs
, tor_strdup(event_string
));
3490 smartlist_add(strs
, tor_strdup("\r\n"));
3491 SMARTLIST_FOREACH(statuses
, routerstatus_t
*, rs
,
3493 s
= networkstatus_getinfo_helper_single(rs
);
3495 smartlist_add(strs
, s
);
3498 s
= smartlist_join_strings(strs
, "", 0, NULL
);
3499 write_escaped_data(s
, strlen(s
), &esc
);
3500 SMARTLIST_FOREACH(strs
, char *, cp
, tor_free(cp
));
3501 smartlist_free(strs
);
3503 send_control_event_string(event
, ALL_FORMATS
, esc
);
3504 send_control_event_string(event
, ALL_FORMATS
,
3511 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
3512 * an NS event to any controller that cares. */
3514 control_event_networkstatus_changed(smartlist_t
*statuses
)
3516 return control_event_networkstatus_changed_helper(statuses
, EVENT_NS
, "NS");
3519 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
3520 * event consisting of an NS-style line for each relay in the consensus. */
3522 control_event_newconsensus(const networkstatus_t
*consensus
)
3524 if (!control_event_is_interesting(EVENT_NEWCONSENSUS
))
3526 return control_event_networkstatus_changed_helper(
3527 consensus
->routerstatus_list
, EVENT_NEWCONSENSUS
, "NEWCONSENSUS");
3530 /** Called when we compute a new circuitbuildtimeout */
3532 control_event_buildtimeout_set(const circuit_build_times_t
*cbt
,
3533 buildtimeout_set_event_t type
)
3535 const char *type_string
= NULL
;
3536 double qnt
= circuit_build_times_quantile_cutoff();
3538 if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET
))
3542 case BUILDTIMEOUT_SET_EVENT_COMPUTED
:
3543 type_string
= "COMPUTED";
3545 case BUILDTIMEOUT_SET_EVENT_RESET
:
3546 type_string
= "RESET";
3549 case BUILDTIMEOUT_SET_EVENT_SUSPENDED
:
3550 type_string
= "SUSPENDED";
3553 case BUILDTIMEOUT_SET_EVENT_DISCARD
:
3554 type_string
= "DISCARD";
3557 case BUILDTIMEOUT_SET_EVENT_RESUME
:
3558 type_string
= "RESUME";
3561 type_string
= "UNKNOWN";
3565 send_control_event(EVENT_BUILDTIMEOUT_SET
, ALL_FORMATS
,
3566 "650 BUILDTIMEOUT_SET %s TOTAL_TIMES=%lu "
3567 "TIMEOUT_MS=%lu XM=%lu ALPHA=%lf CUTOFF_QUANTILE=%lf "
3568 "TIMEOUT_RATE=%lf CLOSE_MS=%lu CLOSE_RATE=%lf\r\n",
3569 type_string
, (unsigned long)cbt
->total_build_times
,
3570 (unsigned long)cbt
->timeout_ms
,
3571 (unsigned long)cbt
->Xm
, cbt
->alpha
, qnt
,
3572 circuit_build_times_timeout_rate(cbt
),
3573 (unsigned long)cbt
->close_ms
,
3574 circuit_build_times_close_rate(cbt
));
3579 /** Called when a single local_routerstatus_t has changed: Sends an NS event
3580 * to any controller that cares. */
3582 control_event_networkstatus_changed_single(routerstatus_t
*rs
)
3584 smartlist_t
*statuses
;
3587 if (!EVENT_IS_INTERESTING(EVENT_NS
))
3590 statuses
= smartlist_create();
3591 smartlist_add(statuses
, rs
);
3592 r
= control_event_networkstatus_changed(statuses
);
3593 smartlist_free(statuses
);
3597 /** Our own router descriptor has changed; tell any controllers that care.
3600 control_event_my_descriptor_changed(void)
3602 send_control_event(EVENT_DESCCHANGED
, ALL_FORMATS
, "650 DESCCHANGED\r\n");
3606 /** Helper: sends a status event where <b>type</b> is one of
3607 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
3608 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
3609 * string corresponding to <b>args</b>. */
3611 control_event_status(int type
, int severity
, const char *format
, va_list args
)
3613 char format_buf
[160];
3614 const char *status
, *sev
;
3617 case EVENT_STATUS_GENERAL
:
3618 status
= "STATUS_GENERAL";
3620 case EVENT_STATUS_CLIENT
:
3621 status
= "STATUS_CLIENT";
3623 case EVENT_STATUS_SERVER
:
3624 status
= "STATUS_SERVER";
3627 log_warn(LD_BUG
, "Unrecognized status type %d", type
);
3641 log_warn(LD_BUG
, "Unrecognized status severity %d", severity
);
3644 if (tor_snprintf(format_buf
, sizeof(format_buf
), "650 %s %s %s\r\n",
3645 status
, sev
, format
)<0) {
3646 log_warn(LD_BUG
, "Format string too long.");
3650 send_control_event_impl(type
, ALL_FORMATS
, format_buf
, args
);
3654 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
3655 * by formatting the arguments using the printf-style <b>format</b>. */
3657 control_event_general_status(int severity
, const char *format
, ...)
3661 if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
))
3664 va_start(ap
, format
);
3665 r
= control_event_status(EVENT_STATUS_GENERAL
, severity
, format
, ap
);
3670 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
3671 * by formatting the arguments using the printf-style <b>format</b>. */
3673 control_event_client_status(int severity
, const char *format
, ...)
3677 if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT
))
3680 va_start(ap
, format
);
3681 r
= control_event_status(EVENT_STATUS_CLIENT
, severity
, format
, ap
);
3686 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
3687 * by formatting the arguments using the printf-style <b>format</b>. */
3689 control_event_server_status(int severity
, const char *format
, ...)
3693 if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER
))
3696 va_start(ap
, format
);
3697 r
= control_event_status(EVENT_STATUS_SERVER
, severity
, format
, ap
);
3702 /** Called when the status of an entry guard with the given <b>nickname</b>
3703 * and identity <b>digest</b> has changed to <b>status</b>: tells any
3704 * controllers that care. */
3706 control_event_guard(const char *nickname
, const char *digest
,
3709 char hbuf
[HEX_DIGEST_LEN
+1];
3710 base16_encode(hbuf
, sizeof(hbuf
), digest
, DIGEST_LEN
);
3711 if (!EVENT_IS_INTERESTING(EVENT_GUARD
))
3715 char buf
[MAX_VERBOSE_NICKNAME_LEN
+1];
3716 routerinfo_t
*ri
= router_get_by_digest(digest
);
3718 router_get_verbose_nickname(buf
, ri
);
3720 tor_snprintf(buf
, sizeof(buf
), "$%s~%s", hbuf
, nickname
);
3722 send_control_event(EVENT_GUARD
, ALL_FORMATS
,
3723 "650 GUARD ENTRY %s %s\r\n", buf
, status
);
3728 /** Helper: Return a newly allocated string containing a path to the
3729 * file where we store our authentication cookie. */
3731 get_cookie_file(void)
3733 or_options_t
*options
= get_options();
3734 if (options
->CookieAuthFile
&& strlen(options
->CookieAuthFile
)) {
3735 return tor_strdup(options
->CookieAuthFile
);
3737 return get_datadir_fname("control_auth_cookie");
3741 /** Choose a random authentication cookie and write it to disk.
3742 * Anybody who can read the cookie from disk will be considered
3743 * authorized to use the control connection. Return -1 if we can't
3744 * write the file, or 0 on success. */
3746 init_cookie_authentication(int enabled
)
3750 authentication_cookie_is_set
= 0;
3754 /* We don't want to generate a new cookie every time we call
3755 * options_act(). One should be enough. */
3756 if (authentication_cookie_is_set
)
3757 return 0; /* all set */
3759 fname
= get_cookie_file();
3760 crypto_rand(authentication_cookie
, AUTHENTICATION_COOKIE_LEN
);
3761 authentication_cookie_is_set
= 1;
3762 if (write_bytes_to_file(fname
, authentication_cookie
,
3763 AUTHENTICATION_COOKIE_LEN
, 1)) {
3764 log_warn(LD_FS
,"Error writing authentication cookie to %s.",
3770 if (get_options()->CookieAuthFileGroupReadable
) {
3771 if (chmod(fname
, 0640)) {
3772 log_warn(LD_FS
,"Unable to make %s group-readable.", escaped(fname
));
3781 /** Convert the name of a bootstrapping phase <b>s</b> into strings
3782 * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
3784 bootstrap_status_to_string(bootstrap_status_t s
, const char **tag
,
3785 const char **summary
)
3788 case BOOTSTRAP_STATUS_UNDEF
:
3790 *summary
= "Undefined";
3792 case BOOTSTRAP_STATUS_STARTING
:
3794 *summary
= "Starting";
3796 case BOOTSTRAP_STATUS_CONN_DIR
:
3798 *summary
= "Connecting to directory server";
3800 case BOOTSTRAP_STATUS_HANDSHAKE
:
3801 *tag
= "status_handshake";
3802 *summary
= "Finishing handshake";
3804 case BOOTSTRAP_STATUS_HANDSHAKE_DIR
:
3805 *tag
= "handshake_dir";
3806 *summary
= "Finishing handshake with directory server";
3808 case BOOTSTRAP_STATUS_ONEHOP_CREATE
:
3809 *tag
= "onehop_create";
3810 *summary
= "Establishing an encrypted directory connection";
3812 case BOOTSTRAP_STATUS_REQUESTING_STATUS
:
3813 *tag
= "requesting_status";
3814 *summary
= "Asking for networkstatus consensus";
3816 case BOOTSTRAP_STATUS_LOADING_STATUS
:
3817 *tag
= "loading_status";
3818 *summary
= "Loading networkstatus consensus";
3820 case BOOTSTRAP_STATUS_LOADING_KEYS
:
3821 *tag
= "loading_keys";
3822 *summary
= "Loading authority key certs";
3824 case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS
:
3825 *tag
= "requesting_descriptors";
3826 *summary
= "Asking for relay descriptors";
3828 case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS
:
3829 *tag
= "loading_descriptors";
3830 *summary
= "Loading relay descriptors";
3832 case BOOTSTRAP_STATUS_CONN_OR
:
3834 *summary
= "Connecting to the Tor network";
3836 case BOOTSTRAP_STATUS_HANDSHAKE_OR
:
3837 *tag
= "handshake_or";
3838 *summary
= "Finishing handshake with first hop";
3840 case BOOTSTRAP_STATUS_CIRCUIT_CREATE
:
3841 *tag
= "circuit_create";
3842 *summary
= "Establishing a Tor circuit";
3844 case BOOTSTRAP_STATUS_DONE
:
3849 // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
3850 *tag
= *summary
= "unknown";
3856 /** What percentage through the bootstrap process are we? We remember
3857 * this so we can avoid sending redundant bootstrap status events, and
3858 * so we can guess context for the bootstrap messages which are
3859 * ambiguous. It starts at 'undef', but gets set to 'starting' while
3860 * Tor initializes. */
3861 static int bootstrap_percent
= BOOTSTRAP_STATUS_UNDEF
;
3863 /** How many problems have we had getting to the next bootstrapping phase?
3864 * These include failure to establish a connection to a Tor relay,
3865 * failures to finish the TLS handshake, failures to validate the
3866 * consensus document, etc. */
3867 static int bootstrap_problems
= 0;
3869 /* We only tell the controller once we've hit a threshold of problems
3870 * for the current phase. */
3871 #define BOOTSTRAP_PROBLEM_THRESHOLD 10
3873 /** Called when Tor has made progress at bootstrapping its directory
3874 * information and initial circuits.
3876 * <b>status</b> is the new status, that is, what task we will be doing
3877 * next. <b>percent</b> is zero if we just started this task, else it
3878 * represents progress on the task. */
3880 control_event_bootstrap(bootstrap_status_t status
, int progress
)
3882 const char *tag
, *summary
;
3883 char buf
[BOOTSTRAP_MSG_LEN
];
3885 if (bootstrap_percent
== BOOTSTRAP_STATUS_DONE
)
3886 return; /* already bootstrapped; nothing to be done here. */
3888 /* special case for handshaking status, since our TLS handshaking code
3889 * can't distinguish what the connection is going to be for. */
3890 if (status
== BOOTSTRAP_STATUS_HANDSHAKE
) {
3891 if (bootstrap_percent
< BOOTSTRAP_STATUS_CONN_OR
) {
3892 status
= BOOTSTRAP_STATUS_HANDSHAKE_DIR
;
3894 status
= BOOTSTRAP_STATUS_HANDSHAKE_OR
;
3898 if (status
> bootstrap_percent
||
3899 (progress
&& progress
> bootstrap_percent
)) {
3900 bootstrap_status_to_string(status
, &tag
, &summary
);
3901 log(status
? LOG_NOTICE
: LOG_INFO
, LD_CONTROL
,
3902 "Bootstrapped %d%%: %s.", progress
? progress
: status
, summary
);
3903 tor_snprintf(buf
, sizeof(buf
),
3904 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
3905 progress
? progress
: status
, tag
, summary
);
3906 tor_snprintf(last_sent_bootstrap_message
,
3907 sizeof(last_sent_bootstrap_message
),
3909 control_event_client_status(LOG_NOTICE
, "%s", buf
);
3910 if (status
> bootstrap_percent
) {
3911 bootstrap_percent
= status
; /* new milestone reached */
3913 if (progress
> bootstrap_percent
) {
3914 /* incremental progress within a milestone */
3915 bootstrap_percent
= progress
;
3916 bootstrap_problems
= 0; /* Progress! Reset our problem counter. */
3921 /** Called when Tor has failed to make bootstrapping progress in a way
3922 * that indicates a problem. <b>warn</b> gives a hint as to why, and
3923 * <b>reason</b> provides an "or_conn_end_reason" tag.
3926 control_event_bootstrap_problem(const char *warn
, int reason
)
3928 int status
= bootstrap_percent
;
3929 const char *tag
, *summary
;
3930 char buf
[BOOTSTRAP_MSG_LEN
];
3931 const char *recommendation
= "ignore";
3933 if (bootstrap_percent
== 100)
3934 return; /* already bootstrapped; nothing to be done here. */
3936 bootstrap_problems
++;
3938 if (bootstrap_problems
>= BOOTSTRAP_PROBLEM_THRESHOLD
)
3939 recommendation
= "warn";
3941 if (reason
== END_OR_CONN_REASON_NO_ROUTE
)
3942 recommendation
= "warn";
3944 if (get_options()->UseBridges
&&
3945 !any_bridge_descriptors_known() &&
3946 !any_pending_bridge_descriptor_fetches())
3947 recommendation
= "warn";
3949 while (status
>=0 && bootstrap_status_to_string(status
, &tag
, &summary
) < 0)
3950 status
--; /* find a recognized status string based on current progress */
3951 status
= bootstrap_percent
; /* set status back to the actual number */
3953 log_fn(!strcmp(recommendation
, "warn") ? LOG_WARN
: LOG_INFO
,
3954 LD_CONTROL
, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
3955 "count %d; recommendation %s)",
3956 status
, summary
, warn
,
3957 orconn_end_reason_to_control_string(reason
),
3958 bootstrap_problems
, recommendation
);
3959 tor_snprintf(buf
, sizeof(buf
),
3960 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
3961 "COUNT=%d RECOMMENDATION=%s",
3962 bootstrap_percent
, tag
, summary
, warn
,
3963 orconn_end_reason_to_control_string(reason
), bootstrap_problems
,
3965 tor_snprintf(last_sent_bootstrap_message
,
3966 sizeof(last_sent_bootstrap_message
),
3968 control_event_client_status(LOG_WARN
, "%s", buf
);
3971 /** We just generated a new summary of which countries we've seen clients
3972 * from recently. Send a copy to the controller in case it wants to
3973 * display it for the user. */
3975 control_event_clients_seen(const char *controller_str
)
3977 send_control_event(EVENT_CLIENTS_SEEN
, 0,
3978 "650 CLIENTS_SEEN %s\r\n", controller_str
);