1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2013, 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
14 #include "addressmap.h"
17 #include "channeltls.h"
18 #include "circuitbuild.h"
19 #include "circuitlist.h"
20 #include "circuitstats.h"
21 #include "circuituse.h"
23 #include "confparse.h"
24 #include "connection.h"
25 #include "connection_edge.h"
26 #include "connection_or.h"
28 #include "directory.h"
31 #include "entrynodes.h"
33 #include "hibernate.h"
35 #include "networkstatus.h"
41 #include "routerlist.h"
42 #include "routerparse.h"
46 #include <sys/resource.h>
51 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
52 * finished authentication and is accepting commands. */
53 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
55 /* Recognized asynchronous event types. It's okay to expand this list
56 * because it is used both as a list of v0 event types, and as indices
57 * into the bitfield to determine which controllers want which events.
59 #define EVENT_MIN_ 0x0001
60 #define EVENT_CIRCUIT_STATUS 0x0001
61 #define EVENT_STREAM_STATUS 0x0002
62 #define EVENT_OR_CONN_STATUS 0x0003
63 #define EVENT_BANDWIDTH_USED 0x0004
64 #define EVENT_CIRCUIT_STATUS_MINOR 0x0005
65 #define EVENT_NEW_DESC 0x0006
66 #define EVENT_DEBUG_MSG 0x0007
67 #define EVENT_INFO_MSG 0x0008
68 #define EVENT_NOTICE_MSG 0x0009
69 #define EVENT_WARN_MSG 0x000A
70 #define EVENT_ERR_MSG 0x000B
71 #define EVENT_ADDRMAP 0x000C
72 // #define EVENT_AUTHDIR_NEWDESCS 0x000D
73 #define EVENT_DESCCHANGED 0x000E
74 // #define EVENT_NS 0x000F
75 #define EVENT_STATUS_CLIENT 0x0010
76 #define EVENT_STATUS_SERVER 0x0011
77 #define EVENT_STATUS_GENERAL 0x0012
78 #define EVENT_GUARD 0x0013
79 #define EVENT_STREAM_BANDWIDTH_USED 0x0014
80 #define EVENT_CLIENTS_SEEN 0x0015
81 #define EVENT_NEWCONSENSUS 0x0016
82 #define EVENT_BUILDTIMEOUT_SET 0x0017
83 #define EVENT_SIGNAL 0x0018
84 #define EVENT_CONF_CHANGED 0x0019
85 #define EVENT_MAX_ 0x0019
86 /* If EVENT_MAX_ ever hits 0x0020, we need to make the mask wider. */
88 /** Bitfield: The bit 1<<e is set if <b>any</b> open control
89 * connection is interested in events of type <b>e</b>. We use this
90 * so that we can decide to skip generating event messages that nobody
91 * has interest in without having to walk over the global connection
94 typedef uint32_t event_mask_t
;
96 /** An event mask of all the events that any controller is interested in
98 static event_mask_t global_event_mask
= 0;
100 /** True iff we have disabled log messages from being sent to the controller */
101 static int disable_log_messages
= 0;
103 /** Macro: true if any control connection is interested in events of type
105 #define EVENT_IS_INTERESTING(e) \
106 (global_event_mask & (1<<(e)))
108 /** If we're using cookie-type authentication, how long should our cookies be?
110 #define AUTHENTICATION_COOKIE_LEN 32
112 /** If true, we've set authentication_cookie to a secret code and
113 * stored it to disk. */
114 static int authentication_cookie_is_set
= 0;
115 /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
116 * and which we're using to authenticate controllers. (If the controller can
117 * read it off disk, it has permission to connect.) */
118 static uint8_t *authentication_cookie
= NULL
;
120 #define SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT \
121 "Tor safe cookie authentication server-to-controller hash"
122 #define SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT \
123 "Tor safe cookie authentication controller-to-server hash"
124 #define SAFECOOKIE_SERVER_NONCE_LEN DIGEST256_LEN
126 /** A sufficiently large size to record the last bootstrap phase string. */
127 #define BOOTSTRAP_MSG_LEN 1024
129 /** What was the last bootstrap phase message we sent? We keep track
130 * of this so we can respond to getinfo status/bootstrap-phase queries. */
131 static char last_sent_bootstrap_message
[BOOTSTRAP_MSG_LEN
];
133 /** Flag for event_format_t. Indicates that we should use the one standard
136 #define ALL_FORMATS 1
138 /** Bit field of flags to select how to format a controller event. Recognized
139 * flag is ALL_FORMATS. */
140 typedef int event_format_t
;
142 static void connection_printf_to_buf(control_connection_t
*conn
,
143 const char *format
, ...)
145 static void send_control_event_impl(uint16_t event
, event_format_t which
,
146 const char *format
, va_list ap
)
148 static int control_event_status(int type
, int severity
, const char *format
,
152 static void send_control_done(control_connection_t
*conn
);
153 static void send_control_event(uint16_t event
, event_format_t which
,
154 const char *format
, ...)
156 static int handle_control_setconf(control_connection_t
*conn
, uint32_t len
,
158 static int handle_control_resetconf(control_connection_t
*conn
, uint32_t len
,
160 static int handle_control_getconf(control_connection_t
*conn
, uint32_t len
,
162 static int handle_control_loadconf(control_connection_t
*conn
, uint32_t len
,
164 static int handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
166 static int handle_control_authenticate(control_connection_t
*conn
,
169 static int handle_control_signal(control_connection_t
*conn
, uint32_t len
,
171 static int handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
173 static char *list_getinfo_options(void);
174 static int handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
176 static int handle_control_extendcircuit(control_connection_t
*conn
,
179 static int handle_control_setcircuitpurpose(control_connection_t
*conn
,
180 uint32_t len
, const char *body
);
181 static int handle_control_attachstream(control_connection_t
*conn
,
184 static int handle_control_postdescriptor(control_connection_t
*conn
,
187 static int handle_control_redirectstream(control_connection_t
*conn
,
190 static int handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
192 static int handle_control_closecircuit(control_connection_t
*conn
,
195 static int handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
197 static int handle_control_usefeature(control_connection_t
*conn
,
200 static int write_stream_target_to_buf(entry_connection_t
*conn
, char *buf
,
202 static void orconn_target_get_name(char *buf
, size_t len
,
203 or_connection_t
*conn
);
204 static char *get_cookie_file(void);
206 /** Given a control event code for a message event, return the corresponding
209 event_to_log_severity(int event
)
212 case EVENT_DEBUG_MSG
: return LOG_DEBUG
;
213 case EVENT_INFO_MSG
: return LOG_INFO
;
214 case EVENT_NOTICE_MSG
: return LOG_NOTICE
;
215 case EVENT_WARN_MSG
: return LOG_WARN
;
216 case EVENT_ERR_MSG
: return LOG_ERR
;
221 /** Given a log severity, return the corresponding control event code. */
223 log_severity_to_event(int severity
)
226 case LOG_DEBUG
: return EVENT_DEBUG_MSG
;
227 case LOG_INFO
: return EVENT_INFO_MSG
;
228 case LOG_NOTICE
: return EVENT_NOTICE_MSG
;
229 case LOG_WARN
: return EVENT_WARN_MSG
;
230 case LOG_ERR
: return EVENT_ERR_MSG
;
235 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
236 * connection's event_mask field. */
238 control_update_global_event_mask(void)
240 smartlist_t
*conns
= get_connection_array();
241 event_mask_t old_mask
, new_mask
;
242 old_mask
= global_event_mask
;
244 global_event_mask
= 0;
245 SMARTLIST_FOREACH(conns
, connection_t
*, _conn
,
247 if (_conn
->type
== CONN_TYPE_CONTROL
&&
248 STATE_IS_OPEN(_conn
->state
)) {
249 control_connection_t
*conn
= TO_CONTROL_CONN(_conn
);
250 global_event_mask
|= conn
->event_mask
;
254 new_mask
= global_event_mask
;
256 /* Handle the aftermath. Set up the log callback to tell us only what
257 * we want to hear...*/
258 control_adjust_event_log_severity();
260 /* ...then, if we've started logging stream bw, clear the appropriate
262 if (! (old_mask
& EVENT_STREAM_BANDWIDTH_USED
) &&
263 (new_mask
& EVENT_STREAM_BANDWIDTH_USED
)) {
264 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
266 if (conn
->type
== CONN_TYPE_AP
) {
267 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
268 edge_conn
->n_written
= edge_conn
->n_read
= 0;
274 /** Adjust the log severities that result in control_event_logmsg being called
275 * to match the severity of log messages that any controllers are interested
278 control_adjust_event_log_severity(void)
281 int min_log_event
=EVENT_ERR_MSG
, max_log_event
=EVENT_DEBUG_MSG
;
283 for (i
= EVENT_DEBUG_MSG
; i
<= EVENT_ERR_MSG
; ++i
) {
284 if (EVENT_IS_INTERESTING(i
)) {
289 for (i
= EVENT_ERR_MSG
; i
>= EVENT_DEBUG_MSG
; --i
) {
290 if (EVENT_IS_INTERESTING(i
)) {
295 if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
)) {
296 if (min_log_event
> EVENT_NOTICE_MSG
)
297 min_log_event
= EVENT_NOTICE_MSG
;
298 if (max_log_event
< EVENT_ERR_MSG
)
299 max_log_event
= EVENT_ERR_MSG
;
301 if (min_log_event
<= max_log_event
)
302 change_callback_log_severity(event_to_log_severity(min_log_event
),
303 event_to_log_severity(max_log_event
),
304 control_event_logmsg
);
306 change_callback_log_severity(LOG_ERR
, LOG_ERR
,
307 control_event_logmsg
);
310 /** Return true iff the event with code <b>c</b> is being sent to any current
311 * control connection. This is useful if the amount of work needed to prepare
312 * to call the appropriate control_event_...() function is high.
315 control_event_is_interesting(int event
)
317 return EVENT_IS_INTERESTING(event
);
320 /** Append a NUL-terminated string <b>s</b> to the end of
321 * <b>conn</b>-\>outbuf.
324 connection_write_str_to_buf(const char *s
, control_connection_t
*conn
)
326 size_t len
= strlen(s
);
327 connection_write_to_buf(s
, len
, TO_CONN(conn
));
330 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
331 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
332 * contents of <b>data</b> into *<b>out</b>, adding a period before any period
333 * that appears at the start of a line, and adding a period-CRLF line at
334 * the end. Replace all LF characters sequences with CRLF. Return the number
335 * of bytes in *<b>out</b>.
338 write_escaped_data(const char *data
, size_t len
, char **out
)
340 size_t sz_out
= len
+8;
342 const char *start
= data
, *end
;
345 for (i
=0; i
<(int)len
; ++i
) {
347 sz_out
+= 2; /* Maybe add a CR; maybe add a dot. */
349 *out
= outp
= tor_malloc(sz_out
+1);
354 if (data
> start
&& data
[-1] != '\r')
357 } else if (*data
== '.') {
367 if (outp
< *out
+2 || fast_memcmp(outp
-2, "\r\n", 2)) {
374 *outp
= '\0'; /* NUL-terminate just in case. */
375 tor_assert((outp
- *out
) <= (int)sz_out
);
379 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
380 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
381 * the contents of <b>data</b> into *<b>out</b>, removing any period
382 * that appears at the start of a line, and replacing all CRLF sequences
383 * with LF. Return the number of
384 * bytes in *<b>out</b>. */
386 read_escaped_data(const char *data
, size_t len
, char **out
)
392 *out
= outp
= tor_malloc(len
+1);
397 /* we're at the start of a line. */
400 next
= memchr(data
, '\n', end
-data
);
402 size_t n_to_copy
= next
-data
;
403 /* Don't copy a CR that precedes this LF. */
404 if (n_to_copy
&& *(next
-1) == '\r')
406 memcpy(outp
, data
, n_to_copy
);
408 data
= next
+1; /* This will point at the start of the next line,
409 * or the end of the string, or a period. */
411 memcpy(outp
, data
, end
-data
);
423 /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
424 * double-quoted string with escaped characters, return the length of that
425 * string (as encoded, including quotes). Otherwise return -1. */
427 get_escaped_string_length(const char *start
, size_t in_len_max
,
430 const char *cp
, *end
;
437 end
= start
+in_len_max
;
439 /* Calculate length. */
442 return -1; /* Too long. */
443 } else if (*cp
== '\\') {
445 return -1; /* Can't escape EOS. */
448 } else if (*cp
== '\"') {
457 return (int)(cp
- start
+1);
460 /** As decode_escaped_string, but does not decode the string: copies the
461 * entire thing, including quotation marks. */
463 extract_escaped_string(const char *start
, size_t in_len_max
,
464 char **out
, size_t *out_len
)
466 int length
= get_escaped_string_length(start
, in_len_max
, NULL
);
470 *out
= tor_strndup(start
, *out_len
);
474 /** Given a pointer to a string starting at <b>start</b> containing
475 * <b>in_len_max</b> characters, decode a string beginning with one double
476 * quote, containing any number of non-quote characters or characters escaped
477 * with a backslash, and ending with a final double quote. Place the resulting
478 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
479 * store its length in <b>out_len</b>. On success, return a pointer to the
480 * character immediately following the escaped string. On failure, return
483 decode_escaped_string(const char *start
, size_t in_len_max
,
484 char **out
, size_t *out_len
)
486 const char *cp
, *end
;
488 int len
, n_chars
= 0;
490 len
= get_escaped_string_length(start
, in_len_max
, &n_chars
);
494 end
= start
+len
-1; /* Index of last quote. */
495 tor_assert(*end
== '\"');
496 outp
= *out
= tor_malloc(len
+1);
506 tor_assert((outp
- *out
) == (int)*out_len
);
511 /** Acts like sprintf, but writes its formatted string to the end of
512 * <b>conn</b>-\>outbuf. */
514 connection_printf_to_buf(control_connection_t
*conn
, const char *format
, ...)
521 len
= tor_vasprintf(&buf
, format
, ap
);
525 log_err(LD_BUG
, "Unable to format string for controller.");
529 connection_write_to_buf(buf
, (size_t)len
, TO_CONN(conn
));
534 /** Write all of the open control ports to ControlPortWriteToFile */
536 control_ports_write_to_file(void)
540 const or_options_t
*options
= get_options();
542 if (!options
->ControlPortWriteToFile
)
545 lines
= smartlist_new();
547 SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t
*, conn
) {
548 if (conn
->type
!= CONN_TYPE_CONTROL_LISTENER
|| conn
->marked_for_close
)
551 if (conn
->socket_family
== AF_UNIX
) {
552 smartlist_add_asprintf(lines
, "UNIX_PORT=%s\n", conn
->address
);
556 smartlist_add_asprintf(lines
, "PORT=%s:%d\n", conn
->address
, conn
->port
);
557 } SMARTLIST_FOREACH_END(conn
);
559 joined
= smartlist_join_strings(lines
, "", 0, NULL
);
561 if (write_str_to_file(options
->ControlPortWriteToFile
, joined
, 0) < 0) {
562 log_warn(LD_CONTROL
, "Writing %s failed: %s",
563 options
->ControlPortWriteToFile
, strerror(errno
));
566 if (options
->ControlPortFileGroupReadable
) {
567 if (chmod(options
->ControlPortWriteToFile
, 0640)) {
568 log_warn(LD_FS
,"Unable to make %s group-readable.",
569 options
->ControlPortWriteToFile
);
574 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
575 smartlist_free(lines
);
578 /** Send a "DONE" message down the control connection <b>conn</b>. */
580 send_control_done(control_connection_t
*conn
)
582 connection_write_str_to_buf("250 OK\r\n", conn
);
585 /** Send an event to all v1 controllers that are listening for code
586 * <b>event</b>. The event's body is given by <b>msg</b>.
588 * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
589 * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
590 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
591 * to controllers that <em>have</em> enabled VERBOSE_NAMES.
593 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
594 * respect to the EXTENDED_EVENTS feature. */
596 send_control_event_string(uint16_t event
, event_format_t which
,
599 smartlist_t
*conns
= get_connection_array();
601 tor_assert(event
>= EVENT_MIN_
&& event
<= EVENT_MAX_
);
603 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
604 if (conn
->type
== CONN_TYPE_CONTROL
&&
605 !conn
->marked_for_close
&&
606 conn
->state
== CONTROL_CONN_STATE_OPEN
) {
607 control_connection_t
*control_conn
= TO_CONTROL_CONN(conn
);
609 if (control_conn
->event_mask
& (1<<event
)) {
611 connection_write_to_buf(msg
, strlen(msg
), TO_CONN(control_conn
));
612 if (event
== EVENT_ERR_MSG
)
614 else if (event
== EVENT_STATUS_GENERAL
)
615 is_err
= !strcmpstart(msg
, "STATUS_GENERAL ERR ");
616 else if (event
== EVENT_STATUS_CLIENT
)
617 is_err
= !strcmpstart(msg
, "STATUS_CLIENT ERR ");
618 else if (event
== EVENT_STATUS_SERVER
)
619 is_err
= !strcmpstart(msg
, "STATUS_SERVER ERR ");
621 connection_flush(TO_CONN(control_conn
));
624 } SMARTLIST_FOREACH_END(conn
);
627 /** Helper for send_control_event and control_event_status:
628 * Send an event to all v1 controllers that are listening for code
629 * <b>event</b>. The event's body is created by the printf-style format in
630 * <b>format</b>, and other arguments as provided. */
632 send_control_event_impl(uint16_t event
, event_format_t which
,
633 const char *format
, va_list ap
)
638 len
= tor_vasprintf(&buf
, format
, ap
);
640 log_warn(LD_BUG
, "Unable to format event for controller.");
644 send_control_event_string(event
, which
|ALL_FORMATS
, buf
);
649 /** Send an event to all v1 controllers that are listening for code
650 * <b>event</b>. The event's body is created by the printf-style format in
651 * <b>format</b>, and other arguments as provided. */
653 send_control_event(uint16_t event
, event_format_t which
,
654 const char *format
, ...)
657 va_start(ap
, format
);
658 send_control_event_impl(event
, which
, format
, ap
);
662 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
663 static origin_circuit_t
*
664 get_circ(const char *id
)
668 n_id
= (uint32_t) tor_parse_ulong(id
, 10, 0, UINT32_MAX
, &ok
, NULL
);
671 return circuit_get_by_global_id(n_id
);
674 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
675 static entry_connection_t
*
676 get_stream(const char *id
)
681 n_id
= tor_parse_uint64(id
, 10, 0, UINT64_MAX
, &ok
, NULL
);
684 conn
= connection_get_by_global_id(n_id
);
685 if (!conn
|| conn
->type
!= CONN_TYPE_AP
|| conn
->marked_for_close
)
687 return TO_ENTRY_CONN(conn
);
690 /** Helper for setconf and resetconf. Acts like setconf, except
691 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
695 control_setconf_helper(control_connection_t
*conn
, uint32_t len
, char *body
,
698 setopt_err_t opt_err
;
699 config_line_t
*lines
=NULL
;
701 char *errstring
= NULL
;
702 const int clear_first
= 1;
705 smartlist_t
*entries
= smartlist_new();
707 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
708 * separated by space. break it into a list of configuration entries. */
713 while (!TOR_ISSPACE(*eq
) && *eq
!= '=')
715 key
= tor_strndup(body
, eq
-body
);
721 char *val_start
= body
;
722 while (!TOR_ISSPACE(*body
))
724 val
= tor_strndup(val_start
, body
-val_start
);
725 val_len
= strlen(val
);
727 body
= (char*)extract_escaped_string(body
, (len
- (body
-start
)),
730 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn
);
731 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
732 smartlist_free(entries
);
737 tor_asprintf(&entry
, "%s %s", key
, val
);
743 smartlist_add(entries
, entry
);
744 while (TOR_ISSPACE(*body
))
748 smartlist_add(entries
, tor_strdup(""));
749 config
= smartlist_join_strings(entries
, "\n", 0, NULL
);
750 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
751 smartlist_free(entries
);
753 if (config_get_lines(config
, &lines
, 0) < 0) {
754 log_warn(LD_CONTROL
,"Controller gave us config lines we can't parse.");
755 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
762 opt_err
= options_trial_assign(lines
, use_defaults
, clear_first
, &errstring
);
766 case SETOPT_ERR_MISC
:
767 msg
= "552 Unrecognized option";
769 case SETOPT_ERR_PARSE
:
770 msg
= "513 Unacceptable option value";
772 case SETOPT_ERR_TRANSITION
:
773 msg
= "553 Transition not allowed";
775 case SETOPT_ERR_SETTING
:
777 msg
= "553 Unable to set option";
780 config_free_lines(lines
);
781 send_control_done(conn
);
785 "Controller gave us config lines that didn't validate: %s",
787 connection_printf_to_buf(conn
, "%s: %s\r\n", msg
, errstring
);
788 config_free_lines(lines
);
794 /** Called when we receive a SETCONF message: parse the body and try
795 * to update our configuration. Reply with a DONE or ERROR message.
796 * Modifies the contents of body.*/
798 handle_control_setconf(control_connection_t
*conn
, uint32_t len
, char *body
)
800 return control_setconf_helper(conn
, len
, body
, 0);
803 /** Called when we receive a RESETCONF message: parse the body and try
804 * to update our configuration. Reply with a DONE or ERROR message.
805 * Modifies the contents of body. */
807 handle_control_resetconf(control_connection_t
*conn
, uint32_t len
, char *body
)
809 return control_setconf_helper(conn
, len
, body
, 1);
812 /** Called when we receive a GETCONF message. Parse the request, and
813 * reply with a CONFVALUE or an ERROR message */
815 handle_control_getconf(control_connection_t
*conn
, uint32_t body_len
,
818 smartlist_t
*questions
= smartlist_new();
819 smartlist_t
*answers
= smartlist_new();
820 smartlist_t
*unrecognized
= smartlist_new();
823 const or_options_t
*options
= get_options();
826 (void) body_len
; /* body is NUL-terminated; so we can ignore len. */
827 smartlist_split_string(questions
, body
, " ",
828 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
829 SMARTLIST_FOREACH_BEGIN(questions
, const char *, q
) {
830 if (!option_is_recognized(q
)) {
831 smartlist_add(unrecognized
, (char*) q
);
833 config_line_t
*answer
= option_get_assignment(options
,q
);
835 const char *name
= option_get_canonical_name(q
);
836 smartlist_add_asprintf(answers
, "250-%s\r\n", name
);
841 smartlist_add_asprintf(answers
, "250-%s=%s\r\n",
842 answer
->key
, answer
->value
);
845 tor_free(answer
->key
);
846 tor_free(answer
->value
);
851 } SMARTLIST_FOREACH_END(q
);
853 if ((len
= smartlist_len(unrecognized
))) {
854 for (i
=0; i
< len
-1; ++i
)
855 connection_printf_to_buf(conn
,
856 "552-Unrecognized configuration key \"%s\"\r\n",
857 (char*)smartlist_get(unrecognized
, i
));
858 connection_printf_to_buf(conn
,
859 "552 Unrecognized configuration key \"%s\"\r\n",
860 (char*)smartlist_get(unrecognized
, len
-1));
861 } else if ((len
= smartlist_len(answers
))) {
862 char *tmp
= smartlist_get(answers
, len
-1);
863 tor_assert(strlen(tmp
)>4);
865 msg
= smartlist_join_strings(answers
, "", 0, &msg_len
);
866 connection_write_to_buf(msg
, msg_len
, TO_CONN(conn
));
868 connection_write_str_to_buf("250 OK\r\n", conn
);
871 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
872 smartlist_free(answers
);
873 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
874 smartlist_free(questions
);
875 smartlist_free(unrecognized
);
882 /** Called when we get a +LOADCONF message. */
884 handle_control_loadconf(control_connection_t
*conn
, uint32_t len
,
888 char *errstring
= NULL
;
889 const char *msg
= NULL
;
892 retval
= options_init_from_string(NULL
, body
, CMD_RUN_TOR
, NULL
, &errstring
);
894 if (retval
!= SETOPT_OK
)
896 "Controller gave us config file that didn't validate: %s",
900 case SETOPT_ERR_PARSE
:
901 msg
= "552 Invalid config file";
903 case SETOPT_ERR_TRANSITION
:
904 msg
= "553 Transition not allowed";
906 case SETOPT_ERR_SETTING
:
907 msg
= "553 Unable to set option";
909 case SETOPT_ERR_MISC
:
911 msg
= "550 Unable to load config";
918 connection_printf_to_buf(conn
, "%s: %s\r\n", msg
, errstring
);
920 connection_printf_to_buf(conn
, "%s\r\n", msg
);
922 send_control_done(conn
);
928 /** Helper structure: maps event values to their names. */
929 struct control_event_t
{
931 const char *event_name
;
933 /** Table mapping event values to their names. Used to implement SETEVENTS
934 * and GETINFO events/names, and to keep they in sync. */
935 static const struct control_event_t control_event_table
[] = {
936 { EVENT_CIRCUIT_STATUS
, "CIRC" },
937 { EVENT_CIRCUIT_STATUS_MINOR
, "CIRC_MINOR" },
938 { EVENT_STREAM_STATUS
, "STREAM" },
939 { EVENT_OR_CONN_STATUS
, "ORCONN" },
940 { EVENT_BANDWIDTH_USED
, "BW" },
941 { EVENT_DEBUG_MSG
, "DEBUG" },
942 { EVENT_INFO_MSG
, "INFO" },
943 { EVENT_NOTICE_MSG
, "NOTICE" },
944 { EVENT_WARN_MSG
, "WARN" },
945 { EVENT_ERR_MSG
, "ERR" },
946 { EVENT_NEW_DESC
, "NEWDESC" },
947 { EVENT_ADDRMAP
, "ADDRMAP" },
948 { EVENT_AUTHDIR_NEWDESCS
, "AUTHDIR_NEWDESCS" },
949 { EVENT_DESCCHANGED
, "DESCCHANGED" },
951 { EVENT_STATUS_GENERAL
, "STATUS_GENERAL" },
952 { EVENT_STATUS_CLIENT
, "STATUS_CLIENT" },
953 { EVENT_STATUS_SERVER
, "STATUS_SERVER" },
954 { EVENT_GUARD
, "GUARD" },
955 { EVENT_STREAM_BANDWIDTH_USED
, "STREAM_BW" },
956 { EVENT_CLIENTS_SEEN
, "CLIENTS_SEEN" },
957 { EVENT_NEWCONSENSUS
, "NEWCONSENSUS" },
958 { EVENT_BUILDTIMEOUT_SET
, "BUILDTIMEOUT_SET" },
959 { EVENT_SIGNAL
, "SIGNAL" },
960 { EVENT_CONF_CHANGED
, "CONF_CHANGED"},
964 /** Called when we get a SETEVENTS message: update conn->event_mask,
965 * and reply with DONE or ERROR. */
967 handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
971 uint32_t event_mask
= 0;
972 smartlist_t
*events
= smartlist_new();
976 smartlist_split_string(events
, body
, " ",
977 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
978 SMARTLIST_FOREACH_BEGIN(events
, const char *, ev
)
980 if (!strcasecmp(ev
, "EXTENDED")) {
984 for (i
= 0; control_event_table
[i
].event_name
!= NULL
; ++i
) {
985 if (!strcasecmp(ev
, control_event_table
[i
].event_name
)) {
986 event_code
= control_event_table
[i
].event_code
;
991 if (event_code
== -1) {
992 connection_printf_to_buf(conn
, "552 Unrecognized event \"%s\"\r\n",
994 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
995 smartlist_free(events
);
999 event_mask
|= (1 << event_code
);
1001 SMARTLIST_FOREACH_END(ev
);
1002 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
1003 smartlist_free(events
);
1005 conn
->event_mask
= event_mask
;
1007 control_update_global_event_mask();
1008 send_control_done(conn
);
1012 /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
1013 * Return a smartlist of acceptable passwords (unterminated strings of
1014 * length S2K_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on failure.
1017 decode_hashed_passwords(config_line_t
*passwords
)
1021 smartlist_t
*sl
= smartlist_new();
1023 tor_assert(passwords
);
1025 for (cl
= passwords
; cl
; cl
= cl
->next
) {
1026 const char *hashed
= cl
->value
;
1028 if (!strcmpstart(hashed
, "16:")) {
1029 if (base16_decode(decoded
, sizeof(decoded
), hashed
+3, strlen(hashed
+3))<0
1030 || strlen(hashed
+3) != (S2K_SPECIFIER_LEN
+DIGEST_LEN
)*2) {
1034 if (base64_decode(decoded
, sizeof(decoded
), hashed
, strlen(hashed
))
1035 != S2K_SPECIFIER_LEN
+DIGEST_LEN
) {
1039 smartlist_add(sl
, tor_memdup(decoded
, S2K_SPECIFIER_LEN
+DIGEST_LEN
));
1045 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
1050 /** Called when we get an AUTHENTICATE message. Check whether the
1051 * authentication is valid, and if so, update the connection's state to
1052 * OPEN. Reply with DONE or ERROR.
1055 handle_control_authenticate(control_connection_t
*conn
, uint32_t len
,
1058 int used_quoted_string
= 0;
1059 const or_options_t
*options
= get_options();
1060 const char *errstr
= NULL
;
1062 size_t password_len
;
1065 int bad_cookie
=0, bad_password
=0;
1066 smartlist_t
*sl
= NULL
;
1069 password
= tor_strdup("");
1071 } else if (TOR_ISXDIGIT(body
[0])) {
1073 while (TOR_ISXDIGIT(*cp
))
1075 i
= (int)(cp
- body
);
1078 password
= tor_malloc(password_len
+ 1);
1079 if (base16_decode(password
, password_len
+1, body
, i
)<0) {
1080 connection_write_str_to_buf(
1081 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1082 "password? If so, the standard requires that you put it in "
1083 "double quotes.\r\n", conn
);
1084 connection_mark_for_close(TO_CONN(conn
));
1089 if (!decode_escaped_string(body
, len
, &password
, &password_len
)) {
1090 connection_write_str_to_buf("551 Invalid quoted string. You need "
1091 "to put the password in double quotes.\r\n", conn
);
1092 connection_mark_for_close(TO_CONN(conn
));
1095 used_quoted_string
= 1;
1098 if (conn
->safecookie_client_hash
!= NULL
) {
1099 /* The controller has chosen safe cookie authentication; the only
1100 * acceptable authentication value is the controller-to-server
1103 tor_assert(authentication_cookie_is_set
);
1105 if (password_len
!= DIGEST256_LEN
) {
1106 log_warn(LD_CONTROL
,
1107 "Got safe cookie authentication response with wrong length "
1108 "(%d)", (int)password_len
);
1109 errstr
= "Wrong length for safe cookie response.";
1113 if (tor_memneq(conn
->safecookie_client_hash
, password
, DIGEST256_LEN
)) {
1114 log_warn(LD_CONTROL
,
1115 "Got incorrect safe cookie authentication response");
1116 errstr
= "Safe cookie response did not match expected value.";
1120 tor_free(conn
->safecookie_client_hash
);
1124 if (!options
->CookieAuthentication
&& !options
->HashedControlPassword
&&
1125 !options
->HashedControlSessionPassword
) {
1126 /* if Tor doesn't demand any stronger authentication, then
1127 * the controller can get in with anything. */
1131 if (options
->CookieAuthentication
) {
1132 int also_password
= options
->HashedControlPassword
!= NULL
||
1133 options
->HashedControlSessionPassword
!= NULL
;
1134 if (password_len
!= AUTHENTICATION_COOKIE_LEN
) {
1135 if (!also_password
) {
1136 log_warn(LD_CONTROL
, "Got authentication cookie with wrong length "
1137 "(%d)", (int)password_len
);
1138 errstr
= "Wrong length on authentication cookie.";
1142 } else if (tor_memneq(authentication_cookie
, password
, password_len
)) {
1143 if (!also_password
) {
1144 log_warn(LD_CONTROL
, "Got mismatched authentication cookie");
1145 errstr
= "Authentication cookie did not match expected value.";
1154 if (options
->HashedControlPassword
||
1155 options
->HashedControlSessionPassword
) {
1157 smartlist_t
*sl_tmp
;
1158 char received
[DIGEST_LEN
];
1159 int also_cookie
= options
->CookieAuthentication
;
1160 sl
= smartlist_new();
1161 if (options
->HashedControlPassword
) {
1162 sl_tmp
= decode_hashed_passwords(options
->HashedControlPassword
);
1166 smartlist_add_all(sl
, sl_tmp
);
1167 smartlist_free(sl_tmp
);
1170 if (options
->HashedControlSessionPassword
) {
1171 sl_tmp
= decode_hashed_passwords(options
->HashedControlSessionPassword
);
1175 smartlist_add_all(sl
, sl_tmp
);
1176 smartlist_free(sl_tmp
);
1181 log_warn(LD_CONTROL
,
1182 "Couldn't decode HashedControlPassword: invalid base16");
1183 errstr
="Couldn't decode HashedControlPassword value in configuration.";
1186 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1189 SMARTLIST_FOREACH(sl
, char *, expected
,
1191 secret_to_key(received
,DIGEST_LEN
,password
,password_len
,expected
);
1192 if (tor_memeq(expected
+S2K_SPECIFIER_LEN
, received
, DIGEST_LEN
))
1195 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1198 if (used_quoted_string
)
1199 errstr
= "Password did not match HashedControlPassword value from "
1202 errstr
= "Password did not match HashedControlPassword value from "
1203 "configuration. Maybe you tried a plain text password? "
1204 "If so, the standard requires that you put it in double quotes.";
1211 /** We only get here if both kinds of authentication failed. */
1212 tor_assert(bad_password
&& bad_cookie
);
1213 log_warn(LD_CONTROL
, "Bad password or authentication cookie on controller.");
1214 errstr
= "Password did not match HashedControlPassword *or* authentication "
1219 connection_printf_to_buf(conn
, "515 Authentication failed: %s\r\n",
1220 errstr
? errstr
: "Unknown reason.");
1221 connection_mark_for_close(TO_CONN(conn
));
1224 log_info(LD_CONTROL
, "Authenticated control connection ("TOR_SOCKET_T_FORMAT
1225 ")", conn
->base_
.s
);
1226 send_control_done(conn
);
1227 conn
->base_
.state
= CONTROL_CONN_STATE_OPEN
;
1229 if (sl
) { /* clean up */
1230 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1236 /** Called when we get a SAVECONF command. Try to flush the current options to
1237 * disk, and report success or failure. */
1239 handle_control_saveconf(control_connection_t
*conn
, uint32_t len
,
1244 if (options_save_current()<0) {
1245 connection_write_str_to_buf(
1246 "551 Unable to write configuration to disk.\r\n", conn
);
1248 send_control_done(conn
);
1255 const char *signal_name
;
1258 static const struct signal_t signal_table
[] = {
1259 { SIGHUP
, "RELOAD" },
1261 { SIGINT
, "SHUTDOWN" },
1262 { SIGUSR1
, "DUMP" },
1263 { SIGUSR1
, "USR1" },
1264 { SIGUSR2
, "DEBUG" },
1265 { SIGUSR2
, "USR2" },
1266 { SIGTERM
, "HALT" },
1267 { SIGTERM
, "TERM" },
1269 { SIGNEWNYM
, "NEWNYM" },
1270 { SIGCLEARDNSCACHE
, "CLEARDNSCACHE"},
1274 /** Called when we get a SIGNAL command. React to the provided signal, and
1275 * report success or failure. (If the signal results in a shutdown, success
1276 * may not be reported.) */
1278 handle_control_signal(control_connection_t
*conn
, uint32_t len
,
1288 while (body
[n
] && ! TOR_ISSPACE(body
[n
]))
1290 s
= tor_strndup(body
, n
);
1292 for (i
= 0; signal_table
[i
].signal_name
!= NULL
; ++i
) {
1293 if (!strcasecmp(s
, signal_table
[i
].signal_name
)) {
1294 sig
= signal_table
[i
].sig
;
1300 connection_printf_to_buf(conn
, "552 Unrecognized signal code \"%s\"\r\n",
1306 send_control_done(conn
);
1307 /* Flush the "done" first if the signal might make us shut down. */
1308 if (sig
== SIGTERM
|| sig
== SIGINT
)
1309 connection_flush(TO_CONN(conn
));
1311 process_signal(sig
);
1316 /** Called when we get a TAKEOWNERSHIP command. Mark this connection
1317 * as an owning connection, so that we will exit if the connection
1320 handle_control_takeownership(control_connection_t
*conn
, uint32_t len
,
1326 conn
->is_owning_control_connection
= 1;
1328 log_info(LD_CONTROL
, "Control connection %d has taken ownership of this "
1330 (int)(conn
->base_
.s
));
1332 send_control_done(conn
);
1336 /** Return true iff <b>addr</b> is unusable as a mapaddress target because of
1337 * containing funny characters. */
1339 address_is_invalid_mapaddress_target(const char *addr
)
1341 if (!strcmpstart(addr
, "*."))
1342 return address_is_invalid_destination(addr
+2, 1);
1344 return address_is_invalid_destination(addr
, 1);
1347 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1348 * and report success or failure. */
1350 handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
1358 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
1360 lines
= smartlist_new();
1361 elts
= smartlist_new();
1362 reply
= smartlist_new();
1363 smartlist_split_string(lines
, body
, " ",
1364 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1365 SMARTLIST_FOREACH_BEGIN(lines
, char *, line
) {
1367 smartlist_split_string(elts
, line
, "=", 0, 2);
1368 if (smartlist_len(elts
) == 2) {
1369 const char *from
= smartlist_get(elts
,0);
1370 const char *to
= smartlist_get(elts
,1);
1371 if (address_is_invalid_mapaddress_target(to
)) {
1372 smartlist_add_asprintf(reply
,
1373 "512-syntax error: invalid address '%s'", to
);
1374 log_warn(LD_CONTROL
,
1375 "Skipping invalid argument '%s' in MapAddress msg", to
);
1376 } else if (!strcmp(from
, ".") || !strcmp(from
, "0.0.0.0") ||
1377 !strcmp(from
, "::")) {
1379 !strcmp(from
,".") ? RESOLVED_TYPE_HOSTNAME
:
1380 (!strcmp(from
, "0.0.0.0") ? RESOLVED_TYPE_IPV4
: RESOLVED_TYPE_IPV6
);
1381 const char *address
= addressmap_register_virtual_address(
1382 type
, tor_strdup(to
));
1384 smartlist_add_asprintf(reply
,
1385 "451-resource exhausted: skipping '%s'", line
);
1386 log_warn(LD_CONTROL
,
1387 "Unable to allocate address for '%s' in MapAddress msg",
1388 safe_str_client(line
));
1390 smartlist_add_asprintf(reply
, "250-%s=%s", address
, to
);
1394 if (addressmap_register_auto(from
, to
, 1,
1395 ADDRMAPSRC_CONTROLLER
, &msg
) < 0) {
1396 smartlist_add_asprintf(reply
,
1397 "512-syntax error: invalid address mapping "
1398 " '%s': %s", line
, msg
);
1399 log_warn(LD_CONTROL
,
1400 "Skipping invalid argument '%s' in MapAddress msg: %s",
1403 smartlist_add_asprintf(reply
, "250-%s", line
);
1407 smartlist_add_asprintf(reply
, "512-syntax error: mapping '%s' is "
1408 "not of expected form 'foo=bar'.", line
);
1409 log_info(LD_CONTROL
, "Skipping MapAddress '%s': wrong "
1411 safe_str_client(line
));
1413 SMARTLIST_FOREACH(elts
, char *, cp
, tor_free(cp
));
1414 smartlist_clear(elts
);
1415 } SMARTLIST_FOREACH_END(line
);
1416 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
1417 smartlist_free(lines
);
1418 smartlist_free(elts
);
1420 if (smartlist_len(reply
)) {
1421 ((char*)smartlist_get(reply
,smartlist_len(reply
)-1))[3] = ' ';
1422 r
= smartlist_join_strings(reply
, "\r\n", 1, &sz
);
1423 connection_write_to_buf(r
, sz
, TO_CONN(conn
));
1426 const char *response
=
1427 "512 syntax error: not enough arguments to mapaddress.\r\n";
1428 connection_write_to_buf(response
, strlen(response
), TO_CONN(conn
));
1431 SMARTLIST_FOREACH(reply
, char *, cp
, tor_free(cp
));
1432 smartlist_free(reply
);
1436 /** Implementation helper for GETINFO: knows the answers for various
1437 * trivial-to-implement questions. */
1439 getinfo_helper_misc(control_connection_t
*conn
, const char *question
,
1440 char **answer
, const char **errmsg
)
1443 if (!strcmp(question
, "version")) {
1444 *answer
= tor_strdup(get_version());
1445 } else if (!strcmp(question
, "config-file")) {
1446 *answer
= tor_strdup(get_torrc_fname(0));
1447 } else if (!strcmp(question
, "config-defaults-file")) {
1448 *answer
= tor_strdup(get_torrc_fname(1));
1449 } else if (!strcmp(question
, "config-text")) {
1450 *answer
= options_dump(get_options(), 1);
1451 } else if (!strcmp(question
, "info/names")) {
1452 *answer
= list_getinfo_options();
1453 } else if (!strcmp(question
, "dormant")) {
1454 int dormant
= rep_hist_circbuilding_dormant(time(NULL
));
1455 *answer
= tor_strdup(dormant
? "1" : "0");
1456 } else if (!strcmp(question
, "events/names")) {
1458 smartlist_t
*event_names
= smartlist_new();
1460 for (i
= 0; control_event_table
[i
].event_name
!= NULL
; ++i
) {
1461 smartlist_add(event_names
, (char *)control_event_table
[i
].event_name
);
1464 *answer
= smartlist_join_strings(event_names
, " ", 0, NULL
);
1466 smartlist_free(event_names
);
1467 } else if (!strcmp(question
, "signal/names")) {
1468 smartlist_t
*signal_names
= smartlist_new();
1470 for (j
= 0; signal_table
[j
].signal_name
!= NULL
; ++j
) {
1471 smartlist_add(signal_names
, (char*)signal_table
[j
].signal_name
);
1474 *answer
= smartlist_join_strings(signal_names
, " ", 0, NULL
);
1476 smartlist_free(signal_names
);
1477 } else if (!strcmp(question
, "features/names")) {
1478 *answer
= tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1479 } else if (!strcmp(question
, "address")) {
1481 if (router_pick_published_address(get_options(), &addr
) < 0) {
1482 *errmsg
= "Address unknown";
1485 *answer
= tor_dup_ip(addr
);
1486 } else if (!strcmp(question
, "traffic/read")) {
1487 tor_asprintf(answer
, U64_FORMAT
, U64_PRINTF_ARG(get_bytes_read()));
1488 } else if (!strcmp(question
, "traffic/written")) {
1489 tor_asprintf(answer
, U64_FORMAT
, U64_PRINTF_ARG(get_bytes_written()));
1490 } else if (!strcmp(question
, "process/pid")) {
1499 tor_asprintf(answer
, "%d", myPid
);
1500 } else if (!strcmp(question
, "process/uid")) {
1502 *answer
= tor_strdup("-1");
1504 int myUid
= geteuid();
1505 tor_asprintf(answer
, "%d", myUid
);
1507 } else if (!strcmp(question
, "process/user")) {
1509 *answer
= tor_strdup("");
1511 int myUid
= geteuid();
1512 struct passwd
*myPwEntry
= getpwuid(myUid
);
1515 *answer
= tor_strdup(myPwEntry
->pw_name
);
1517 *answer
= tor_strdup("");
1520 } else if (!strcmp(question
, "process/descriptor-limit")) {
1522 set_max_file_descriptors(0, &max_fds
);
1523 tor_asprintf(answer
, "%d", max_fds
);
1524 } else if (!strcmp(question
, "dir-usage")) {
1525 *answer
= directory_dump_request_log();
1526 } else if (!strcmp(question
, "fingerprint")) {
1527 crypto_pk_t
*server_key
;
1528 if (!server_mode(get_options())) {
1529 *errmsg
= "Not running in server mode";
1532 server_key
= get_server_identity_key();
1533 *answer
= tor_malloc(HEX_DIGEST_LEN
+1);
1534 crypto_pk_get_fingerprint(server_key
, *answer
, 0);
1539 /** Awful hack: return a newly allocated string based on a routerinfo and
1540 * (possibly) an extrainfo, sticking the read-history and write-history from
1541 * <b>ei</b> into the resulting string. The thing you get back won't
1542 * necessarily have a valid signature.
1544 * New code should never use this; it's for backward compatibility.
1546 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1547 * not be NUL-terminated. */
1549 munge_extrainfo_into_routerinfo(const char *ri_body
,
1550 const signed_descriptor_t
*ri
,
1551 const signed_descriptor_t
*ei
)
1553 char *out
= NULL
, *outp
;
1555 const char *router_sig
;
1556 const char *ei_body
= signed_descriptor_get_body(ei
);
1557 size_t ri_len
= ri
->signed_descriptor_len
;
1558 size_t ei_len
= ei
->signed_descriptor_len
;
1562 outp
= out
= tor_malloc(ri_len
+ei_len
+1);
1563 if (!(router_sig
= tor_memstr(ri_body
, ri_len
, "\nrouter-signature")))
1566 memcpy(out
, ri_body
, router_sig
-ri_body
);
1567 outp
+= router_sig
-ri_body
;
1569 for (i
=0; i
< 2; ++i
) {
1570 const char *kwd
= i
?"\nwrite-history ":"\nread-history ";
1571 const char *cp
, *eol
;
1572 if (!(cp
= tor_memstr(ei_body
, ei_len
, kwd
)))
1575 if (!(eol
= memchr(cp
, '\n', ei_len
- (cp
-ei_body
))))
1577 memcpy(outp
, cp
, eol
-cp
+1);
1580 memcpy(outp
, router_sig
, ri_len
- (router_sig
-ri_body
));
1582 tor_assert(outp
-out
< (int)(ri_len
+ei_len
+1));
1587 return tor_strndup(ri_body
, ri
->signed_descriptor_len
);
1590 /** Implementation helper for GETINFO: answers requests for information about
1591 * which ports are bound. */
1593 getinfo_helper_listeners(control_connection_t
*control_conn
,
1594 const char *question
,
1595 char **answer
, const char **errmsg
)
1603 if (!strcmp(question
, "net/listeners/or"))
1604 type
= CONN_TYPE_OR_LISTENER
;
1605 else if (!strcmp(question
, "net/listeners/dir"))
1606 type
= CONN_TYPE_DIR_LISTENER
;
1607 else if (!strcmp(question
, "net/listeners/socks"))
1608 type
= CONN_TYPE_AP_LISTENER
;
1609 else if (!strcmp(question
, "net/listeners/trans"))
1610 type
= CONN_TYPE_AP_TRANS_LISTENER
;
1611 else if (!strcmp(question
, "net/listeners/natd"))
1612 type
= CONN_TYPE_AP_NATD_LISTENER
;
1613 else if (!strcmp(question
, "net/listeners/dns"))
1614 type
= CONN_TYPE_AP_DNS_LISTENER
;
1615 else if (!strcmp(question
, "net/listeners/control"))
1616 type
= CONN_TYPE_CONTROL_LISTENER
;
1618 return 0; /* unknown key */
1620 res
= smartlist_new();
1621 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t
*, conn
) {
1622 struct sockaddr_storage ss
;
1623 socklen_t ss_len
= sizeof(ss
);
1625 if (conn
->type
!= type
|| conn
->marked_for_close
|| !SOCKET_OK(conn
->s
))
1628 if (getsockname(conn
->s
, (struct sockaddr
*)&ss
, &ss_len
) < 0) {
1629 smartlist_add_asprintf(res
, "%s:%d", conn
->address
, (int)conn
->port
);
1631 char *tmp
= tor_sockaddr_to_str((struct sockaddr
*)&ss
);
1632 smartlist_add(res
, esc_for_log(tmp
));
1636 } SMARTLIST_FOREACH_END(conn
);
1638 *answer
= smartlist_join_strings(res
, " ", 0, NULL
);
1640 SMARTLIST_FOREACH(res
, char *, cp
, tor_free(cp
));
1641 smartlist_free(res
);
1645 /** Implementation helper for GETINFO: knows the answers for questions about
1646 * directory information. */
1648 getinfo_helper_dir(control_connection_t
*control_conn
,
1649 const char *question
, char **answer
,
1650 const char **errmsg
)
1653 const routerinfo_t
*ri
= NULL
;
1654 (void) control_conn
;
1655 if (!strcmpstart(question
, "desc/id/")) {
1656 node
= node_get_by_hex_id(question
+strlen("desc/id/"));
1660 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1662 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
1664 } else if (!strcmpstart(question
, "desc/name/")) {
1665 /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
1666 * warning goes to the user, not to the controller. */
1667 node
= node_get_by_nickname(question
+strlen("desc/name/"), 1);
1671 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1673 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
1675 } else if (!strcmp(question
, "desc/all-recent")) {
1676 routerlist_t
*routerlist
= router_get_routerlist();
1677 smartlist_t
*sl
= smartlist_new();
1678 if (routerlist
&& routerlist
->routers
) {
1679 SMARTLIST_FOREACH(routerlist
->routers
, const routerinfo_t
*, ri
,
1681 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1684 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
1687 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
1688 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
1690 } else if (!strcmp(question
, "desc/all-recent-extrainfo-hack")) {
1691 /* XXXX Remove this once Torstat asks for extrainfos. */
1692 routerlist_t
*routerlist
= router_get_routerlist();
1693 smartlist_t
*sl
= smartlist_new();
1694 if (routerlist
&& routerlist
->routers
) {
1695 SMARTLIST_FOREACH_BEGIN(routerlist
->routers
, const routerinfo_t
*, ri
) {
1696 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1697 signed_descriptor_t
*ei
= extrainfo_get_by_descriptor_digest(
1698 ri
->cache_info
.extra_info_digest
);
1700 smartlist_add(sl
, munge_extrainfo_into_routerinfo(body
,
1701 &ri
->cache_info
, ei
));
1704 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
1706 } SMARTLIST_FOREACH_END(ri
);
1708 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
1709 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
1711 } else if (!strcmpstart(question
, "md/id/")) {
1712 const node_t
*node
= node_get_by_hex_id(question
+strlen("md/id/"));
1713 const microdesc_t
*md
= NULL
;
1714 if (node
) md
= node
->md
;
1715 if (md
&& md
->body
) {
1716 *answer
= tor_strndup(md
->body
, md
->bodylen
);
1718 } else if (!strcmpstart(question
, "md/name/")) {
1719 /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
1720 * warning goes to the user, not to the controller. */
1721 const node_t
*node
= node_get_by_nickname(question
+strlen("md/name/"), 1);
1722 /* XXXX duplicated code */
1723 const microdesc_t
*md
= NULL
;
1724 if (node
) md
= node
->md
;
1725 if (md
&& md
->body
) {
1726 *answer
= tor_strndup(md
->body
, md
->bodylen
);
1728 } else if (!strcmpstart(question
, "desc-annotations/id/")) {
1729 node
= node_get_by_hex_id(question
+strlen("desc-annotations/id/"));
1733 const char *annotations
=
1734 signed_descriptor_get_annotations(&ri
->cache_info
);
1736 *answer
= tor_strndup(annotations
,
1737 ri
->cache_info
.annotations_len
);
1739 } else if (!strcmpstart(question
, "dir/server/")) {
1740 size_t answer_len
= 0;
1742 smartlist_t
*descs
= smartlist_new();
1746 tor_asprintf(&url
, "/tor/%s", question
+4);
1747 res
= dirserv_get_routerdescs(descs
, url
, &msg
);
1749 log_warn(LD_CONTROL
, "getinfo '%s': %s", question
, msg
);
1750 smartlist_free(descs
);
1755 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
1756 answer_len
+= sd
->signed_descriptor_len
);
1757 cp
= *answer
= tor_malloc(answer_len
+1);
1758 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
1760 memcpy(cp
, signed_descriptor_get_body(sd
),
1761 sd
->signed_descriptor_len
);
1762 cp
+= sd
->signed_descriptor_len
;
1766 smartlist_free(descs
);
1767 } else if (!strcmpstart(question
, "dir/status/")) {
1768 if (directory_permits_controller_requests(get_options())) {
1771 smartlist_t
*status_list
= smartlist_new();
1772 dirserv_get_networkstatus_v2(status_list
,
1773 question
+strlen("dir/status/"));
1774 SMARTLIST_FOREACH(status_list
, cached_dir_t
*, d
, len
+= d
->dir_len
);
1775 cp
= *answer
= tor_malloc(len
+1);
1776 SMARTLIST_FOREACH(status_list
, cached_dir_t
*, d
, {
1777 memcpy(cp
, d
->dir
, d
->dir_len
);
1781 smartlist_free(status_list
);
1783 smartlist_t
*fp_list
= smartlist_new();
1784 smartlist_t
*status_list
= smartlist_new();
1785 dirserv_get_networkstatus_v2_fingerprints(
1786 fp_list
, question
+strlen("dir/status/"));
1787 SMARTLIST_FOREACH(fp_list
, const char *, fp
, {
1789 char *fname
= networkstatus_get_cache_filename(fp
);
1790 s
= read_file_to_str(fname
, 0, NULL
);
1792 smartlist_add(status_list
, s
);
1795 SMARTLIST_FOREACH(fp_list
, char *, fp
, tor_free(fp
));
1796 smartlist_free(fp_list
);
1797 *answer
= smartlist_join_strings(status_list
, "", 0, NULL
);
1798 SMARTLIST_FOREACH(status_list
, char *, s
, tor_free(s
));
1799 smartlist_free(status_list
);
1801 } else if (!strcmp(question
, "dir/status-vote/current/consensus")) { /* v3 */
1802 if (directory_caches_dir_info(get_options())) {
1803 const cached_dir_t
*consensus
= dirserv_get_consensus("ns");
1805 *answer
= tor_strdup(consensus
->dir
);
1807 if (!*answer
) { /* try loading it from disk */
1808 char *filename
= get_datadir_fname("cached-consensus");
1809 *answer
= read_file_to_str(filename
, RFTS_IGNORE_MISSING
, NULL
);
1812 } else if (!strcmp(question
, "network-status")) { /* v1 */
1813 routerlist_t
*routerlist
= router_get_routerlist();
1814 if (!routerlist
|| !routerlist
->routers
||
1815 list_server_status_v1(routerlist
->routers
, answer
, 1) < 0) {
1818 } else if (!strcmpstart(question
, "extra-info/digest/")) {
1819 question
+= strlen("extra-info/digest/");
1820 if (strlen(question
) == HEX_DIGEST_LEN
) {
1822 signed_descriptor_t
*sd
= NULL
;
1823 if (base16_decode(d
, sizeof(d
), question
, strlen(question
))==0) {
1824 /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
1825 * but I don't want to risk affecting other parts of the code,
1826 * especially since the rules for using our own extrainfo (including
1827 * when it might be freed) are different from those for using one
1828 * we have downloaded. */
1829 if (router_extrainfo_digest_is_me(d
))
1830 sd
= &(router_get_my_extrainfo()->cache_info
);
1832 sd
= extrainfo_get_by_descriptor_digest(d
);
1835 const char *body
= signed_descriptor_get_body(sd
);
1837 *answer
= tor_strndup(body
, sd
->signed_descriptor_len
);
1845 /** Allocate and return a description of <b>circ</b>'s current status,
1846 * including its path (if any). */
1848 circuit_describe_status_for_controller(origin_circuit_t
*circ
)
1851 smartlist_t
*descparts
= smartlist_new();
1854 char *vpath
= circuit_list_path_for_controller(circ
);
1856 smartlist_add(descparts
, vpath
);
1858 tor_free(vpath
); /* empty path; don't put an extra space in the result */
1863 cpath_build_state_t
*build_state
= circ
->build_state
;
1864 smartlist_t
*flaglist
= smartlist_new();
1865 char *flaglist_joined
;
1867 if (build_state
->onehop_tunnel
)
1868 smartlist_add(flaglist
, (void *)"ONEHOP_TUNNEL");
1869 if (build_state
->is_internal
)
1870 smartlist_add(flaglist
, (void *)"IS_INTERNAL");
1871 if (build_state
->need_capacity
)
1872 smartlist_add(flaglist
, (void *)"NEED_CAPACITY");
1873 if (build_state
->need_uptime
)
1874 smartlist_add(flaglist
, (void *)"NEED_UPTIME");
1876 /* Only emit a BUILD_FLAGS argument if it will have a non-empty value. */
1877 if (smartlist_len(flaglist
)) {
1878 flaglist_joined
= smartlist_join_strings(flaglist
, ",", 0, NULL
);
1880 smartlist_add_asprintf(descparts
, "BUILD_FLAGS=%s", flaglist_joined
);
1882 tor_free(flaglist_joined
);
1885 smartlist_free(flaglist
);
1888 smartlist_add_asprintf(descparts
, "PURPOSE=%s",
1889 circuit_purpose_to_controller_string(circ
->base_
.purpose
));
1892 const char *hs_state
=
1893 circuit_purpose_to_controller_hs_state_string(circ
->base_
.purpose
);
1895 if (hs_state
!= NULL
) {
1896 smartlist_add_asprintf(descparts
, "HS_STATE=%s", hs_state
);
1900 if (circ
->rend_data
!= NULL
) {
1901 smartlist_add_asprintf(descparts
, "REND_QUERY=%s",
1902 circ
->rend_data
->onion_address
);
1906 char tbuf
[ISO_TIME_USEC_LEN
+1];
1907 format_iso_time_nospace_usec(tbuf
, &circ
->base_
.timestamp_created
);
1909 smartlist_add_asprintf(descparts
, "TIME_CREATED=%s", tbuf
);
1912 rv
= smartlist_join_strings(descparts
, " ", 0, NULL
);
1914 SMARTLIST_FOREACH(descparts
, char *, cp
, tor_free(cp
));
1915 smartlist_free(descparts
);
1920 /** Implementation helper for GETINFO: knows how to generate summaries of the
1921 * current states of things we send events about. */
1923 getinfo_helper_events(control_connection_t
*control_conn
,
1924 const char *question
, char **answer
,
1925 const char **errmsg
)
1927 (void) control_conn
;
1928 if (!strcmp(question
, "circuit-status")) {
1930 smartlist_t
*status
= smartlist_new();
1931 for (circ_
= circuit_get_global_list_(); circ_
; circ_
= circ_
->next
) {
1932 origin_circuit_t
*circ
;
1935 if (! CIRCUIT_IS_ORIGIN(circ_
) || circ_
->marked_for_close
)
1937 circ
= TO_ORIGIN_CIRCUIT(circ_
);
1939 if (circ
->base_
.state
== CIRCUIT_STATE_OPEN
)
1941 else if (circ
->cpath
)
1946 circdesc
= circuit_describe_status_for_controller(circ
);
1948 smartlist_add_asprintf(status
, "%lu %s%s%s",
1949 (unsigned long)circ
->global_identifier
,
1950 state
, *circdesc
? " " : "", circdesc
);
1953 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1954 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1955 smartlist_free(status
);
1956 } else if (!strcmp(question
, "stream-status")) {
1957 smartlist_t
*conns
= get_connection_array();
1958 smartlist_t
*status
= smartlist_new();
1960 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
1962 entry_connection_t
*conn
;
1964 origin_circuit_t
*origin_circ
= NULL
;
1965 if (base_conn
->type
!= CONN_TYPE_AP
||
1966 base_conn
->marked_for_close
||
1967 base_conn
->state
== AP_CONN_STATE_SOCKS_WAIT
||
1968 base_conn
->state
== AP_CONN_STATE_NATD_WAIT
)
1970 conn
= TO_ENTRY_CONN(base_conn
);
1971 switch (base_conn
->state
)
1973 case AP_CONN_STATE_CONTROLLER_WAIT
:
1974 case AP_CONN_STATE_CIRCUIT_WAIT
:
1975 if (conn
->socks_request
&&
1976 SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
))
1977 state
= "NEWRESOLVE";
1981 case AP_CONN_STATE_RENDDESC_WAIT
:
1982 case AP_CONN_STATE_CONNECT_WAIT
:
1983 state
= "SENTCONNECT"; break;
1984 case AP_CONN_STATE_RESOLVE_WAIT
:
1985 state
= "SENTRESOLVE"; break;
1986 case AP_CONN_STATE_OPEN
:
1987 state
= "SUCCEEDED"; break;
1989 log_warn(LD_BUG
, "Asked for stream in unknown state %d",
1993 circ
= circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn
));
1994 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
1995 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
1996 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
1997 smartlist_add_asprintf(status
, "%lu %s %lu %s",
1998 (unsigned long) base_conn
->global_identifier
,state
,
2000 (unsigned long)origin_circ
->global_identifier
: 0ul,
2002 } SMARTLIST_FOREACH_END(base_conn
);
2003 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
2004 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
2005 smartlist_free(status
);
2006 } else if (!strcmp(question
, "orconn-status")) {
2007 smartlist_t
*conns
= get_connection_array();
2008 smartlist_t
*status
= smartlist_new();
2009 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
2012 or_connection_t
*conn
;
2013 if (base_conn
->type
!= CONN_TYPE_OR
|| base_conn
->marked_for_close
)
2015 conn
= TO_OR_CONN(base_conn
);
2016 if (conn
->base_
.state
== OR_CONN_STATE_OPEN
)
2017 state
= "CONNECTED";
2018 else if (conn
->nickname
)
2022 orconn_target_get_name(name
, sizeof(name
), conn
);
2023 smartlist_add_asprintf(status
, "%s %s", name
, state
);
2024 } SMARTLIST_FOREACH_END(base_conn
);
2025 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
2026 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
2027 smartlist_free(status
);
2028 } else if (!strcmpstart(question
, "address-mappings/")) {
2029 time_t min_e
, max_e
;
2030 smartlist_t
*mappings
;
2031 question
+= strlen("address-mappings/");
2032 if (!strcmp(question
, "all")) {
2033 min_e
= 0; max_e
= TIME_MAX
;
2034 } else if (!strcmp(question
, "cache")) {
2035 min_e
= 2; max_e
= TIME_MAX
;
2036 } else if (!strcmp(question
, "config")) {
2037 min_e
= 0; max_e
= 0;
2038 } else if (!strcmp(question
, "control")) {
2039 min_e
= 1; max_e
= 1;
2043 mappings
= smartlist_new();
2044 addressmap_get_mappings(mappings
, min_e
, max_e
, 1);
2045 *answer
= smartlist_join_strings(mappings
, "\r\n", 0, NULL
);
2046 SMARTLIST_FOREACH(mappings
, char *, cp
, tor_free(cp
));
2047 smartlist_free(mappings
);
2048 } else if (!strcmpstart(question
, "status/")) {
2049 /* Note that status/ is not a catch-all for events; there's only supposed
2050 * to be a status GETINFO if there's a corresponding STATUS event. */
2051 if (!strcmp(question
, "status/circuit-established")) {
2052 *answer
= tor_strdup(can_complete_circuit
? "1" : "0");
2053 } else if (!strcmp(question
, "status/enough-dir-info")) {
2054 *answer
= tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
2055 } else if (!strcmp(question
, "status/good-server-descriptor") ||
2056 !strcmp(question
, "status/accepted-server-descriptor")) {
2057 /* They're equivalent for now, until we can figure out how to make
2058 * good-server-descriptor be what we want. See comment in
2059 * control-spec.txt. */
2060 *answer
= tor_strdup(directories_have_accepted_server_descriptor()
2062 } else if (!strcmp(question
, "status/reachability-succeeded/or")) {
2063 *answer
= tor_strdup(check_whether_orport_reachable() ? "1" : "0");
2064 } else if (!strcmp(question
, "status/reachability-succeeded/dir")) {
2065 *answer
= tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
2066 } else if (!strcmp(question
, "status/reachability-succeeded")) {
2067 tor_asprintf(answer
, "OR=%d DIR=%d",
2068 check_whether_orport_reachable() ? 1 : 0,
2069 check_whether_dirport_reachable() ? 1 : 0);
2070 } else if (!strcmp(question
, "status/bootstrap-phase")) {
2071 *answer
= tor_strdup(last_sent_bootstrap_message
);
2072 } else if (!strcmpstart(question
, "status/version/")) {
2073 int is_server
= server_mode(get_options());
2074 networkstatus_t
*c
= networkstatus_get_latest_consensus();
2075 version_status_t status
;
2076 const char *recommended
;
2078 recommended
= is_server
? c
->server_versions
: c
->client_versions
;
2079 status
= tor_version_is_obsolete(VERSION
, recommended
);
2082 status
= VS_UNKNOWN
;
2085 if (!strcmp(question
, "status/version/recommended")) {
2086 *answer
= tor_strdup(recommended
);
2089 if (!strcmp(question
, "status/version/current")) {
2092 case VS_RECOMMENDED
: *answer
= tor_strdup("recommended"); break;
2093 case VS_OLD
: *answer
= tor_strdup("obsolete"); break;
2094 case VS_NEW
: *answer
= tor_strdup("new"); break;
2095 case VS_NEW_IN_SERIES
: *answer
= tor_strdup("new in series"); break;
2096 case VS_UNRECOMMENDED
: *answer
= tor_strdup("unrecommended"); break;
2097 case VS_EMPTY
: *answer
= tor_strdup("none recommended"); break;
2098 case VS_UNKNOWN
: *answer
= tor_strdup("unknown"); break;
2099 default: tor_fragile_assert();
2101 } else if (!strcmp(question
, "status/version/num-versioning") ||
2102 !strcmp(question
, "status/version/num-concurring")) {
2103 tor_asprintf(answer
, "%d", get_n_authorities(V3_DIRINFO
));
2104 log_warn(LD_GENERAL
, "%s is deprecated; it no longer gives useful "
2105 "information", question
);
2107 } else if (!strcmp(question
, "status/clients-seen")) {
2108 char *bridge_stats
= geoip_get_bridge_stats_controller(time(NULL
));
2109 if (!bridge_stats
) {
2110 *errmsg
= "No bridge-client stats available";
2113 *answer
= bridge_stats
;
2121 /** Callback function for GETINFO: on a given control connection, try to
2122 * answer the question <b>q</b> and store the newly-allocated answer in
2123 * *<b>a</b>. If an internal error occurs, return -1 and optionally set
2124 * *<b>error_out</b> to point to an error message to be delivered to the
2125 * controller. On success, _or if the key is not recognized_, return 0. Do not
2126 * set <b>a</b> if the key is not recognized.
2128 typedef int (*getinfo_helper_t
)(control_connection_t
*,
2129 const char *q
, char **a
,
2130 const char **error_out
);
2132 /** A single item for the GETINFO question-to-answer-function table. */
2133 typedef struct getinfo_item_t
{
2134 const char *varname
; /**< The value (or prefix) of the question. */
2135 getinfo_helper_t fn
; /**< The function that knows the answer: NULL if
2136 * this entry is documentation-only. */
2137 const char *desc
; /**< Description of the variable. */
2138 int is_prefix
; /** Must varname match exactly, or must it be a prefix? */
2141 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
2142 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
2143 #define DOC(name, desc) { name, NULL, desc, 0 }
2145 /** Table mapping questions accepted by GETINFO to the functions that know how
2146 * to answer them. */
2147 static const getinfo_item_t getinfo_items
[] = {
2148 ITEM("version", misc
, "The current version of Tor."),
2149 ITEM("config-file", misc
, "Current location of the \"torrc\" file."),
2150 ITEM("config-defaults-file", misc
, "Current location of the defaults file."),
2151 ITEM("config-text", misc
,
2152 "Return the string that would be written by a saveconf command."),
2153 ITEM("accounting/bytes", accounting
,
2154 "Number of bytes read/written so far in the accounting interval."),
2155 ITEM("accounting/bytes-left", accounting
,
2156 "Number of bytes left to write/read so far in the accounting interval."),
2157 ITEM("accounting/enabled", accounting
, "Is accounting currently enabled?"),
2158 ITEM("accounting/hibernating", accounting
, "Are we hibernating or awake?"),
2159 ITEM("accounting/interval-start", accounting
,
2160 "Time when the accounting period starts."),
2161 ITEM("accounting/interval-end", accounting
,
2162 "Time when the accounting period ends."),
2163 ITEM("accounting/interval-wake", accounting
,
2164 "Time to wake up in this accounting period."),
2165 ITEM("helper-nodes", entry_guards
, NULL
), /* deprecated */
2166 ITEM("entry-guards", entry_guards
,
2167 "Which nodes are we using as entry guards?"),
2168 ITEM("fingerprint", misc
, NULL
),
2169 PREFIX("config/", config
, "Current configuration values."),
2171 "List of configuration options, types, and documentation."),
2172 DOC("config/defaults",
2173 "List of default values for configuration options. "
2174 "See also config/names"),
2175 ITEM("info/names", misc
,
2176 "List of GETINFO options, types, and documentation."),
2177 ITEM("events/names", misc
,
2178 "Events that the controller can ask for with SETEVENTS."),
2179 ITEM("signal/names", misc
, "Signal names recognized by the SIGNAL command"),
2180 ITEM("features/names", misc
, "What arguments can USEFEATURE take?"),
2181 PREFIX("desc/id/", dir
, "Router descriptors by ID."),
2182 PREFIX("desc/name/", dir
, "Router descriptors by nickname."),
2183 ITEM("desc/all-recent", dir
,
2184 "All non-expired, non-superseded router descriptors."),
2185 ITEM("desc/all-recent-extrainfo-hack", dir
, NULL
), /* Hack. */
2186 PREFIX("md/id/", dir
, "Microdescriptors by ID"),
2187 PREFIX("md/name/", dir
, "Microdescriptors by name"),
2188 PREFIX("extra-info/digest/", dir
, "Extra-info documents by digest."),
2189 PREFIX("net/listeners/", listeners
, "Bound addresses by type"),
2190 ITEM("ns/all", networkstatus
,
2191 "Brief summary of router status (v2 directory format)"),
2192 PREFIX("ns/id/", networkstatus
,
2193 "Brief summary of router status by ID (v2 directory format)."),
2194 PREFIX("ns/name/", networkstatus
,
2195 "Brief summary of router status by nickname (v2 directory format)."),
2196 PREFIX("ns/purpose/", networkstatus
,
2197 "Brief summary of router status by purpose (v2 directory format)."),
2198 ITEM("network-status", dir
,
2199 "Brief summary of router status (v1 directory format)"),
2200 ITEM("circuit-status", events
, "List of current circuits originating here."),
2201 ITEM("stream-status", events
,"List of current streams."),
2202 ITEM("orconn-status", events
, "A list of current OR connections."),
2203 ITEM("dormant", misc
,
2204 "Is Tor dormant (not building circuits because it's idle)?"),
2205 PREFIX("address-mappings/", events
, NULL
),
2206 DOC("address-mappings/all", "Current address mappings."),
2207 DOC("address-mappings/cache", "Current cached DNS replies."),
2208 DOC("address-mappings/config",
2209 "Current address mappings from configuration."),
2210 DOC("address-mappings/control", "Current address mappings from controller."),
2211 PREFIX("status/", events
, NULL
),
2212 DOC("status/circuit-established",
2213 "Whether we think client functionality is working."),
2214 DOC("status/enough-dir-info",
2215 "Whether we have enough up-to-date directory information to build "
2217 DOC("status/bootstrap-phase",
2218 "The last bootstrap phase status event that Tor sent."),
2219 DOC("status/clients-seen",
2220 "Breakdown of client countries seen by a bridge."),
2221 DOC("status/version/recommended", "List of currently recommended versions."),
2222 DOC("status/version/current", "Status of the current version."),
2223 DOC("status/version/num-versioning", "Number of versioning authorities."),
2224 DOC("status/version/num-concurring",
2225 "Number of versioning authorities agreeing on the status of the "
2227 ITEM("address", misc
, "IP address of this Tor host, if we can guess it."),
2228 ITEM("traffic/read", misc
,"Bytes read since the process was started."),
2229 ITEM("traffic/written", misc
,
2230 "Bytes written since the process was started."),
2231 ITEM("process/pid", misc
, "Process id belonging to the main tor process."),
2232 ITEM("process/uid", misc
, "User id running the tor process."),
2233 ITEM("process/user", misc
,
2234 "Username under which the tor process is running."),
2235 ITEM("process/descriptor-limit", misc
, "File descriptor limit."),
2236 ITEM("dir-usage", misc
, "Breakdown of bytes transferred over DirPort."),
2237 PREFIX("desc-annotations/id/", dir
, "Router annotations by hexdigest."),
2238 PREFIX("dir/server/", dir
,"Router descriptors as retrieved from a DirPort."),
2239 PREFIX("dir/status/", dir
,
2240 "v2 networkstatus docs as retrieved from a DirPort."),
2241 ITEM("dir/status-vote/current/consensus", dir
,
2242 "v3 Networkstatus consensus as retrieved from a DirPort."),
2243 ITEM("exit-policy/default", policies
,
2244 "The default value appended to the configured exit policy."),
2245 PREFIX("ip-to-country/", geoip
, "Perform a GEOIP lookup"),
2246 { NULL
, NULL
, NULL
, 0 }
2249 /** Allocate and return a list of recognized GETINFO options. */
2251 list_getinfo_options(void)
2254 smartlist_t
*lines
= smartlist_new();
2256 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
2257 if (!getinfo_items
[i
].desc
)
2260 smartlist_add_asprintf(lines
, "%s%s -- %s\n",
2261 getinfo_items
[i
].varname
,
2262 getinfo_items
[i
].is_prefix
? "*" : "",
2263 getinfo_items
[i
].desc
);
2265 smartlist_sort_strings(lines
);
2267 ans
= smartlist_join_strings(lines
, "", 0, NULL
);
2268 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
2269 smartlist_free(lines
);
2274 /** Lookup the 'getinfo' entry <b>question</b>, and return
2275 * the answer in <b>*answer</b> (or NULL if key not recognized).
2276 * Return 0 if success or unrecognized, or -1 if recognized but
2277 * internal error. */
2279 handle_getinfo_helper(control_connection_t
*control_conn
,
2280 const char *question
, char **answer
,
2281 const char **err_out
)
2284 *answer
= NULL
; /* unrecognized key by default */
2286 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
2288 if (getinfo_items
[i
].is_prefix
)
2289 match
= !strcmpstart(question
, getinfo_items
[i
].varname
);
2291 match
= !strcmp(question
, getinfo_items
[i
].varname
);
2293 tor_assert(getinfo_items
[i
].fn
);
2294 return getinfo_items
[i
].fn(control_conn
, question
, answer
, err_out
);
2298 return 0; /* unrecognized */
2301 /** Called when we receive a GETINFO command. Try to fetch all requested
2302 * information, and reply with information or error message. */
2304 handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
2307 smartlist_t
*questions
= smartlist_new();
2308 smartlist_t
*answers
= smartlist_new();
2309 smartlist_t
*unrecognized
= smartlist_new();
2310 char *msg
= NULL
, *ans
= NULL
;
2312 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
2314 smartlist_split_string(questions
, body
, " ",
2315 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2316 SMARTLIST_FOREACH_BEGIN(questions
, const char *, q
) {
2317 const char *errmsg
= NULL
;
2318 if (handle_getinfo_helper(conn
, q
, &ans
, &errmsg
) < 0) {
2320 errmsg
= "Internal error";
2321 connection_printf_to_buf(conn
, "551 %s\r\n", errmsg
);
2325 smartlist_add(unrecognized
, (char*)q
);
2327 smartlist_add(answers
, tor_strdup(q
));
2328 smartlist_add(answers
, ans
);
2330 } SMARTLIST_FOREACH_END(q
);
2331 if (smartlist_len(unrecognized
)) {
2332 for (i
=0; i
< smartlist_len(unrecognized
)-1; ++i
)
2333 connection_printf_to_buf(conn
,
2334 "552-Unrecognized key \"%s\"\r\n",
2335 (char*)smartlist_get(unrecognized
, i
));
2336 connection_printf_to_buf(conn
,
2337 "552 Unrecognized key \"%s\"\r\n",
2338 (char*)smartlist_get(unrecognized
, i
));
2342 for (i
= 0; i
< smartlist_len(answers
); i
+= 2) {
2343 char *k
= smartlist_get(answers
, i
);
2344 char *v
= smartlist_get(answers
, i
+1);
2345 if (!strchr(v
, '\n') && !strchr(v
, '\r')) {
2346 connection_printf_to_buf(conn
, "250-%s=", k
);
2347 connection_write_str_to_buf(v
, conn
);
2348 connection_write_str_to_buf("\r\n", conn
);
2352 esc_len
= write_escaped_data(v
, strlen(v
), &esc
);
2353 connection_printf_to_buf(conn
, "250+%s=\r\n", k
);
2354 connection_write_to_buf(esc
, esc_len
, TO_CONN(conn
));
2358 connection_write_str_to_buf("250 OK\r\n", conn
);
2361 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
2362 smartlist_free(answers
);
2363 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
2364 smartlist_free(questions
);
2365 smartlist_free(unrecognized
);
2371 /** Given a string, convert it to a circuit purpose. */
2373 circuit_purpose_from_string(const char *string
)
2375 if (!strcasecmpstart(string
, "purpose="))
2376 string
+= strlen("purpose=");
2378 if (!strcasecmp(string
, "general"))
2379 return CIRCUIT_PURPOSE_C_GENERAL
;
2380 else if (!strcasecmp(string
, "controller"))
2381 return CIRCUIT_PURPOSE_CONTROLLER
;
2383 return CIRCUIT_PURPOSE_UNKNOWN
;
2386 /** Return a newly allocated smartlist containing the arguments to the command
2387 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
2388 * or if <b>max_args</b> is nonnegative and there are more than
2389 * <b>max_args</b> arguments, send a 512 error to the controller, using
2390 * <b>command</b> as the command name in the error message. */
2391 static smartlist_t
*
2392 getargs_helper(const char *command
, control_connection_t
*conn
,
2393 const char *body
, int min_args
, int max_args
)
2395 smartlist_t
*args
= smartlist_new();
2396 smartlist_split_string(args
, body
, " ",
2397 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2398 if (smartlist_len(args
) < min_args
) {
2399 connection_printf_to_buf(conn
, "512 Missing argument to %s\r\n",command
);
2401 } else if (max_args
>= 0 && smartlist_len(args
) > max_args
) {
2402 connection_printf_to_buf(conn
, "512 Too many arguments to %s\r\n",command
);
2407 SMARTLIST_FOREACH(args
, char *, s
, tor_free(s
));
2408 smartlist_free(args
);
2412 /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
2413 * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
2414 * such element exists. */
2416 find_element_starting_with(smartlist_t
*sl
, int start_at
, const char *prefix
)
2419 for (i
= start_at
; i
< smartlist_len(sl
); ++i
) {
2420 const char *elt
= smartlist_get(sl
, i
);
2421 if (!strcasecmpstart(elt
, prefix
))
2427 /** Helper. Return true iff s is an argument that we should treat as a
2428 * key-value pair. */
2430 is_keyval_pair(const char *s
)
2432 /* An argument is a key-value pair if it has an =, and it isn't of the form
2433 * $fingeprint=name */
2434 return strchr(s
, '=') && s
[0] != '$';
2437 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
2438 * circuit, and report success or failure. */
2440 handle_control_extendcircuit(control_connection_t
*conn
, uint32_t len
,
2443 smartlist_t
*router_nicknames
=NULL
, *nodes
=NULL
;
2444 origin_circuit_t
*circ
= NULL
;
2446 uint8_t intended_purpose
= CIRCUIT_PURPOSE_C_GENERAL
;
2450 router_nicknames
= smartlist_new();
2452 args
= getargs_helper("EXTENDCIRCUIT", conn
, body
, 1, -1);
2456 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,0));
2459 const char *purp
= find_element_starting_with(args
, 1, "PURPOSE=");
2462 intended_purpose
= circuit_purpose_from_string(purp
);
2463 if (intended_purpose
== CIRCUIT_PURPOSE_UNKNOWN
) {
2464 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
2465 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2466 smartlist_free(args
);
2471 if ((smartlist_len(args
) == 1) ||
2472 (smartlist_len(args
) >= 2 && is_keyval_pair(smartlist_get(args
, 1)))) {
2473 // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
2474 circ
= circuit_launch(intended_purpose
, CIRCLAUNCH_NEED_CAPACITY
);
2476 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
2478 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
2479 (unsigned long)circ
->global_identifier
);
2481 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2482 smartlist_free(args
);
2485 // "EXTENDCIRCUIT 0 router1,router2" ||
2486 // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
2489 if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
,0)))) {
2490 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2491 (char*)smartlist_get(args
, 0));
2492 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2493 smartlist_free(args
);
2497 smartlist_split_string(router_nicknames
, smartlist_get(args
,1), ",", 0, 0);
2499 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2500 smartlist_free(args
);
2502 nodes
= smartlist_new();
2503 SMARTLIST_FOREACH_BEGIN(router_nicknames
, const char *, n
) {
2504 const node_t
*node
= node_get_by_nickname(n
, 1);
2506 connection_printf_to_buf(conn
, "552 No such router \"%s\"\r\n", n
);
2509 if (!node_has_descriptor(node
)) {
2510 connection_printf_to_buf(conn
, "552 descriptor for \"%s\"\r\n", n
);
2513 smartlist_add(nodes
, (void*)node
);
2514 } SMARTLIST_FOREACH_END(n
);
2515 if (!smartlist_len(nodes
)) {
2516 connection_write_str_to_buf("512 No router names provided\r\n", conn
);
2521 /* start a new circuit */
2522 circ
= origin_circuit_init(intended_purpose
, 0);
2525 /* now circ refers to something that is ready to be extended */
2526 SMARTLIST_FOREACH(nodes
, const node_t
*, node
,
2528 extend_info_t
*info
= extend_info_from_node(node
, 0);
2529 tor_assert(info
); /* True, since node_has_descriptor(node) == true */
2530 circuit_append_new_exit(circ
, info
);
2531 extend_info_free(info
);
2534 /* now that we've populated the cpath, start extending */
2537 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
2538 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
2539 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
2543 if (circ
->base_
.state
== CIRCUIT_STATE_OPEN
) {
2545 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
2546 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
2547 log_info(LD_CONTROL
,
2548 "send_next_onion_skin failed; circuit marked for closing.");
2549 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
2550 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn
);
2556 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
2557 (unsigned long)circ
->global_identifier
);
2558 if (zero_circ
) /* send a 'launched' event, for completeness */
2559 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
2561 SMARTLIST_FOREACH(router_nicknames
, char *, n
, tor_free(n
));
2562 smartlist_free(router_nicknames
);
2563 smartlist_free(nodes
);
2567 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
2568 * circuit and it's a valid purpose, change it. */
2570 handle_control_setcircuitpurpose(control_connection_t
*conn
,
2571 uint32_t len
, const char *body
)
2573 origin_circuit_t
*circ
= NULL
;
2574 uint8_t new_purpose
;
2576 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
2578 args
= getargs_helper("SETCIRCUITPURPOSE", conn
, body
, 2, -1);
2582 if (!(circ
= get_circ(smartlist_get(args
,0)))) {
2583 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2584 (char*)smartlist_get(args
, 0));
2589 const char *purp
= find_element_starting_with(args
,1,"PURPOSE=");
2591 connection_write_str_to_buf("552 No purpose given\r\n", conn
);
2594 new_purpose
= circuit_purpose_from_string(purp
);
2595 if (new_purpose
== CIRCUIT_PURPOSE_UNKNOWN
) {
2596 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
2601 circuit_change_purpose(TO_CIRCUIT(circ
), new_purpose
);
2602 connection_write_str_to_buf("250 OK\r\n", conn
);
2606 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2607 smartlist_free(args
);
2612 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
2613 * stream, and report success or failure. */
2615 handle_control_attachstream(control_connection_t
*conn
, uint32_t len
,
2618 entry_connection_t
*ap_conn
= NULL
;
2619 origin_circuit_t
*circ
= NULL
;
2622 crypt_path_t
*cpath
=NULL
;
2623 int hop
=0, hop_line_ok
=1;
2626 args
= getargs_helper("ATTACHSTREAM", conn
, body
, 2, -1);
2630 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,1));
2632 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))) {
2633 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2634 (char*)smartlist_get(args
, 0));
2635 } else if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
, 1)))) {
2636 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2637 (char*)smartlist_get(args
, 1));
2639 const char *hopstring
= find_element_starting_with(args
,2,"HOP=");
2641 hopstring
+= strlen("HOP=");
2642 hop
= (int) tor_parse_ulong(hopstring
, 10, 0, INT_MAX
,
2643 &hop_line_ok
, NULL
);
2644 if (!hop_line_ok
) { /* broken hop line */
2645 connection_printf_to_buf(conn
, "552 Bad value hop=%s\r\n", hopstring
);
2649 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2650 smartlist_free(args
);
2651 if (!ap_conn
|| (!zero_circ
&& !circ
) || !hop_line_ok
)
2654 if (ENTRY_TO_CONN(ap_conn
)->state
!= AP_CONN_STATE_CONTROLLER_WAIT
&&
2655 ENTRY_TO_CONN(ap_conn
)->state
!= AP_CONN_STATE_CONNECT_WAIT
&&
2656 ENTRY_TO_CONN(ap_conn
)->state
!= AP_CONN_STATE_RESOLVE_WAIT
) {
2657 connection_write_str_to_buf(
2658 "555 Connection is not managed by controller.\r\n",
2663 /* Do we need to detach it first? */
2664 if (ENTRY_TO_CONN(ap_conn
)->state
!= AP_CONN_STATE_CONTROLLER_WAIT
) {
2665 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(ap_conn
);
2666 circuit_t
*tmpcirc
= circuit_get_by_edge_conn(edge_conn
);
2667 connection_edge_end(edge_conn
, END_STREAM_REASON_TIMEOUT
);
2668 /* Un-mark it as ending, since we're going to reuse it. */
2669 edge_conn
->edge_has_sent_end
= 0;
2670 edge_conn
->end_reason
= 0;
2672 circuit_detach_stream(tmpcirc
, edge_conn
);
2673 TO_CONN(edge_conn
)->state
= AP_CONN_STATE_CONTROLLER_WAIT
;
2676 if (circ
&& (circ
->base_
.state
!= CIRCUIT_STATE_OPEN
)) {
2677 connection_write_str_to_buf(
2678 "551 Can't attach stream to non-open origin circuit\r\n",
2682 /* Is this a single hop circuit? */
2683 if (circ
&& (circuit_get_cpath_len(circ
)<2 || hop
==1)) {
2684 const node_t
*node
= NULL
;
2686 if (circ
->build_state
&&
2687 circ
->build_state
->chosen_exit
&&
2688 !tor_digest_is_zero(circ
->build_state
->chosen_exit
->identity_digest
)) {
2689 exit_digest
= circ
->build_state
->chosen_exit
->identity_digest
;
2690 node
= node_get_by_id(exit_digest
);
2692 /* Do both the client and relay allow one-hop exit circuits? */
2694 !node_allows_single_hop_exits(node
) ||
2695 !get_options()->AllowSingleHopCircuits
) {
2696 connection_write_str_to_buf(
2697 "551 Can't attach stream to this one-hop circuit.\r\n", conn
);
2700 ap_conn
->chosen_exit_name
= tor_strdup(hex_str(exit_digest
, DIGEST_LEN
));
2703 if (circ
&& hop
>0) {
2704 /* find this hop in the circuit, and set cpath */
2705 cpath
= circuit_get_cpath_hop(circ
, hop
);
2707 connection_printf_to_buf(conn
,
2708 "551 Circuit doesn't have %d hops.\r\n", hop
);
2712 if (connection_ap_handshake_rewrite_and_attach(ap_conn
, circ
, cpath
) < 0) {
2713 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn
);
2716 send_control_done(conn
);
2720 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
2721 * descriptor, and report success or failure. */
2723 handle_control_postdescriptor(control_connection_t
*conn
, uint32_t len
,
2727 const char *msg
=NULL
;
2728 uint8_t purpose
= ROUTER_PURPOSE_GENERAL
;
2729 int cache
= 0; /* eventually, we may switch this to 1 */
2731 char *cp
= memchr(body
, '\n', len
);
2732 smartlist_t
*args
= smartlist_new();
2736 smartlist_split_string(args
, body
, " ",
2737 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2738 SMARTLIST_FOREACH_BEGIN(args
, char *, option
) {
2739 if (!strcasecmpstart(option
, "purpose=")) {
2740 option
+= strlen("purpose=");
2741 purpose
= router_purpose_from_string(option
);
2742 if (purpose
== ROUTER_PURPOSE_UNKNOWN
) {
2743 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n",
2747 } else if (!strcasecmpstart(option
, "cache=")) {
2748 option
+= strlen("cache=");
2749 if (!strcasecmp(option
, "no"))
2751 else if (!strcasecmp(option
, "yes"))
2754 connection_printf_to_buf(conn
, "552 Unknown cache request \"%s\"\r\n",
2758 } else { /* unrecognized argument? */
2759 connection_printf_to_buf(conn
,
2760 "512 Unexpected argument \"%s\" to postdescriptor\r\n", option
);
2763 } SMARTLIST_FOREACH_END(option
);
2765 read_escaped_data(cp
, len
-(cp
-body
), &desc
);
2767 switch (router_load_single_router(desc
, purpose
, cache
, &msg
)) {
2769 if (!msg
) msg
= "Could not parse descriptor";
2770 connection_printf_to_buf(conn
, "554 %s\r\n", msg
);
2773 if (!msg
) msg
= "Descriptor not added";
2774 connection_printf_to_buf(conn
, "251 %s\r\n",msg
);
2777 send_control_done(conn
);
2783 SMARTLIST_FOREACH(args
, char *, arg
, tor_free(arg
));
2784 smartlist_free(args
);
2788 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
2789 * address of the named AP stream, and report success or failure. */
2791 handle_control_redirectstream(control_connection_t
*conn
, uint32_t len
,
2794 entry_connection_t
*ap_conn
= NULL
;
2795 char *new_addr
= NULL
;
2796 uint16_t new_port
= 0;
2800 args
= getargs_helper("REDIRECTSTREAM", conn
, body
, 2, -1);
2804 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))
2805 || !ap_conn
->socks_request
) {
2806 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2807 (char*)smartlist_get(args
, 0));
2810 if (smartlist_len(args
) > 2) { /* they included a port too */
2811 new_port
= (uint16_t) tor_parse_ulong(smartlist_get(args
, 2),
2812 10, 1, 65535, &ok
, NULL
);
2815 connection_printf_to_buf(conn
, "512 Cannot parse port \"%s\"\r\n",
2816 (char*)smartlist_get(args
, 2));
2818 new_addr
= tor_strdup(smartlist_get(args
, 1));
2822 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2823 smartlist_free(args
);
2827 strlcpy(ap_conn
->socks_request
->address
, new_addr
,
2828 sizeof(ap_conn
->socks_request
->address
));
2830 ap_conn
->socks_request
->port
= new_port
;
2832 send_control_done(conn
);
2836 /** Called when we get a CLOSESTREAM command; try to close the named stream
2837 * and report success or failure. */
2839 handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
2842 entry_connection_t
*ap_conn
=NULL
;
2848 args
= getargs_helper("CLOSESTREAM", conn
, body
, 2, -1);
2852 else if (!(ap_conn
= get_stream(smartlist_get(args
, 0))))
2853 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2854 (char*)smartlist_get(args
, 0));
2856 reason
= (uint8_t) tor_parse_ulong(smartlist_get(args
,1), 10, 0, 255,
2859 connection_printf_to_buf(conn
, "552 Unrecognized reason \"%s\"\r\n",
2860 (char*)smartlist_get(args
, 1));
2864 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2865 smartlist_free(args
);
2869 connection_mark_unattached_ap(ap_conn
, reason
);
2870 send_control_done(conn
);
2874 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
2875 * and report success or failure. */
2877 handle_control_closecircuit(control_connection_t
*conn
, uint32_t len
,
2880 origin_circuit_t
*circ
= NULL
;
2885 args
= getargs_helper("CLOSECIRCUIT", conn
, body
, 1, -1);
2889 if (!(circ
=get_circ(smartlist_get(args
, 0))))
2890 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2891 (char*)smartlist_get(args
, 0));
2894 for (i
=1; i
< smartlist_len(args
); ++i
) {
2895 if (!strcasecmp(smartlist_get(args
, i
), "IfUnused"))
2898 log_info(LD_CONTROL
, "Skipping unknown option %s",
2899 (char*)smartlist_get(args
,i
));
2902 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2903 smartlist_free(args
);
2907 if (!safe
|| !circ
->p_streams
) {
2908 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_REQUESTED
);
2911 send_control_done(conn
);
2915 /** Called when we get a RESOLVE command: start trying to resolve
2916 * the listed addresses. */
2918 handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
2921 smartlist_t
*args
, *failed
;
2923 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
2925 if (!(conn
->event_mask
& ((uint32_t)1L<<EVENT_ADDRMAP
))) {
2926 log_warn(LD_CONTROL
, "Controller asked us to resolve an address, but "
2927 "isn't listening for ADDRMAP events. It probably won't see "
2930 args
= smartlist_new();
2931 smartlist_split_string(args
, body
, " ",
2932 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2934 const char *modearg
= find_element_starting_with(args
, 0, "mode=");
2935 if (modearg
&& !strcasecmp(modearg
, "mode=reverse"))
2938 failed
= smartlist_new();
2939 SMARTLIST_FOREACH(args
, const char *, arg
, {
2940 if (!is_keyval_pair(arg
)) {
2941 if (dnsserv_launch_request(arg
, is_reverse
, conn
)<0)
2942 smartlist_add(failed
, (char*)arg
);
2946 send_control_done(conn
);
2947 SMARTLIST_FOREACH(failed
, const char *, arg
, {
2948 control_event_address_mapped(arg
, arg
, time(NULL
),
2952 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2953 smartlist_free(args
);
2954 smartlist_free(failed
);
2958 /** Called when we get a PROTOCOLINFO command: send back a reply. */
2960 handle_control_protocolinfo(control_connection_t
*conn
, uint32_t len
,
2963 const char *bad_arg
= NULL
;
2967 conn
->have_sent_protocolinfo
= 1;
2968 args
= smartlist_new();
2969 smartlist_split_string(args
, body
, " ",
2970 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2971 SMARTLIST_FOREACH(args
, const char *, arg
, {
2973 tor_parse_long(arg
, 10, 0, LONG_MAX
, &ok
, NULL
);
2980 connection_printf_to_buf(conn
, "513 No such version %s\r\n",
2982 /* Don't tolerate bad arguments when not authenticated. */
2983 if (!STATE_IS_OPEN(TO_CONN(conn
)->state
))
2984 connection_mark_for_close(TO_CONN(conn
));
2987 const or_options_t
*options
= get_options();
2988 int cookies
= options
->CookieAuthentication
;
2989 char *cfile
= get_cookie_file();
2993 abs_cfile
= make_path_absolute(cfile
);
2994 esc_cfile
= esc_for_log(abs_cfile
);
2996 int passwd
= (options
->HashedControlPassword
!= NULL
||
2997 options
->HashedControlSessionPassword
!= NULL
);
2998 smartlist_t
*mlist
= smartlist_new();
3000 smartlist_add(mlist
, (char*)"COOKIE");
3001 smartlist_add(mlist
, (char*)"SAFECOOKIE");
3004 smartlist_add(mlist
, (char*)"HASHEDPASSWORD");
3005 if (!cookies
&& !passwd
)
3006 smartlist_add(mlist
, (char*)"NULL");
3007 methods
= smartlist_join_strings(mlist
, ",", 0, NULL
);
3008 smartlist_free(mlist
);
3011 connection_printf_to_buf(conn
,
3012 "250-PROTOCOLINFO 1\r\n"
3013 "250-AUTH METHODS=%s%s%s\r\n"
3014 "250-VERSION Tor=%s\r\n"
3017 cookies
?" COOKIEFILE=":"",
3018 cookies
?esc_cfile
:"",
3022 tor_free(abs_cfile
);
3023 tor_free(esc_cfile
);
3026 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3027 smartlist_free(args
);
3031 /** Called when we get an AUTHCHALLENGE command. */
3033 handle_control_authchallenge(control_connection_t
*conn
, uint32_t len
,
3036 const char *cp
= body
;
3038 size_t client_nonce_len
;
3039 char server_hash
[DIGEST256_LEN
];
3040 char server_hash_encoded
[HEX_DIGEST256_LEN
+1];
3041 char server_nonce
[SAFECOOKIE_SERVER_NONCE_LEN
];
3042 char server_nonce_encoded
[(2*SAFECOOKIE_SERVER_NONCE_LEN
) + 1];
3044 cp
+= strspn(cp
, " \t\n\r");
3045 if (!strcasecmpstart(cp
, "SAFECOOKIE")) {
3046 cp
+= strlen("SAFECOOKIE");
3048 connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
3049 "authentication\r\n", conn
);
3050 connection_mark_for_close(TO_CONN(conn
));
3054 if (!authentication_cookie_is_set
) {
3055 connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
3057 connection_mark_for_close(TO_CONN(conn
));
3061 cp
+= strspn(cp
, " \t\n\r");
3064 decode_escaped_string(cp
, len
- (cp
- body
),
3065 &client_nonce
, &client_nonce_len
);
3066 if (newcp
== NULL
) {
3067 connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
3069 connection_mark_for_close(TO_CONN(conn
));
3074 size_t client_nonce_encoded_len
= strspn(cp
, "0123456789ABCDEFabcdef");
3076 client_nonce_len
= client_nonce_encoded_len
/ 2;
3077 client_nonce
= tor_malloc_zero(client_nonce_len
);
3079 if (base16_decode(client_nonce
, client_nonce_len
,
3080 cp
, client_nonce_encoded_len
) < 0) {
3081 connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
3083 connection_mark_for_close(TO_CONN(conn
));
3084 tor_free(client_nonce
);
3088 cp
+= client_nonce_encoded_len
;
3091 cp
+= strspn(cp
, " \t\n\r");
3094 connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
3096 connection_mark_for_close(TO_CONN(conn
));
3097 tor_free(client_nonce
);
3101 tor_assert(!crypto_rand(server_nonce
, SAFECOOKIE_SERVER_NONCE_LEN
));
3103 /* Now compute and send the server-to-controller response, and the
3104 * server's nonce. */
3105 tor_assert(authentication_cookie
!= NULL
);
3108 size_t tmp_len
= (AUTHENTICATION_COOKIE_LEN
+
3110 SAFECOOKIE_SERVER_NONCE_LEN
);
3111 char *tmp
= tor_malloc_zero(tmp_len
);
3112 char *client_hash
= tor_malloc_zero(DIGEST256_LEN
);
3113 memcpy(tmp
, authentication_cookie
, AUTHENTICATION_COOKIE_LEN
);
3114 memcpy(tmp
+ AUTHENTICATION_COOKIE_LEN
, client_nonce
, client_nonce_len
);
3115 memcpy(tmp
+ AUTHENTICATION_COOKIE_LEN
+ client_nonce_len
,
3116 server_nonce
, SAFECOOKIE_SERVER_NONCE_LEN
);
3118 crypto_hmac_sha256(server_hash
,
3119 SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT
,
3120 strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT
),
3124 crypto_hmac_sha256(client_hash
,
3125 SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT
,
3126 strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT
),
3130 conn
->safecookie_client_hash
= client_hash
;
3135 base16_encode(server_hash_encoded
, sizeof(server_hash_encoded
),
3136 server_hash
, sizeof(server_hash
));
3137 base16_encode(server_nonce_encoded
, sizeof(server_nonce_encoded
),
3138 server_nonce
, sizeof(server_nonce
));
3140 connection_printf_to_buf(conn
,
3141 "250 AUTHCHALLENGE SERVERHASH=%s "
3142 "SERVERNONCE=%s\r\n",
3143 server_hash_encoded
,
3144 server_nonce_encoded
);
3146 tor_free(client_nonce
);
3150 /** Called when we get a USEFEATURE command: parse the feature list, and
3151 * set up the control_connection's options properly. */
3153 handle_control_usefeature(control_connection_t
*conn
,
3159 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
3160 args
= smartlist_new();
3161 smartlist_split_string(args
, body
, " ",
3162 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3163 SMARTLIST_FOREACH_BEGIN(args
, const char *, arg
) {
3164 if (!strcasecmp(arg
, "VERBOSE_NAMES"))
3166 else if (!strcasecmp(arg
, "EXTENDED_EVENTS"))
3169 connection_printf_to_buf(conn
, "552 Unrecognized feature \"%s\"\r\n",
3174 } SMARTLIST_FOREACH_END(arg
);
3177 send_control_done(conn
);
3180 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3181 smartlist_free(args
);
3185 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
3187 connection_control_finished_flushing(control_connection_t
*conn
)
3193 /** Called when <b>conn</b> has gotten its socket closed. */
3195 connection_control_reached_eof(control_connection_t
*conn
)
3199 log_info(LD_CONTROL
,"Control connection reached EOF. Closing.");
3200 connection_mark_for_close(TO_CONN(conn
));
3204 /** Shut down this Tor instance in the same way that SIGINT would, but
3205 * with a log message appropriate for the loss of an owning controller. */
3207 lost_owning_controller(const char *owner_type
, const char *loss_manner
)
3209 int shutdown_slowly
= server_mode(get_options());
3211 log_notice(LD_CONTROL
, "Owning controller %s has %s -- %s.",
3212 owner_type
, loss_manner
,
3213 shutdown_slowly
? "shutting down" : "exiting now");
3215 /* XXXX Perhaps this chunk of code should be a separate function,
3216 * called here and by process_signal(SIGINT). */
3218 if (!shutdown_slowly
) {
3222 /* XXXX This will close all listening sockets except control-port
3223 * listeners. Perhaps we should close those too. */
3224 hibernate_begin_shutdown();
3227 /** Called when <b>conn</b> is being freed. */
3229 connection_control_closed(control_connection_t
*conn
)
3233 conn
->event_mask
= 0;
3234 control_update_global_event_mask();
3236 if (conn
->is_owning_control_connection
) {
3237 lost_owning_controller("connection", "closed");
3241 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
3242 * stage of the protocol. */
3244 is_valid_initial_command(control_connection_t
*conn
, const char *cmd
)
3246 if (conn
->base_
.state
== CONTROL_CONN_STATE_OPEN
)
3248 if (!strcasecmp(cmd
, "PROTOCOLINFO"))
3249 return (!conn
->have_sent_protocolinfo
&&
3250 conn
->safecookie_client_hash
== NULL
);
3251 if (!strcasecmp(cmd
, "AUTHCHALLENGE"))
3252 return (conn
->safecookie_client_hash
== NULL
);
3253 if (!strcasecmp(cmd
, "AUTHENTICATE") ||
3254 !strcasecmp(cmd
, "QUIT"))
3259 /** Do not accept any control command of more than 1MB in length. Anything
3260 * that needs to be anywhere near this long probably means that one of our
3261 * interfaces is broken. */
3262 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
3264 /** Wrapper around peek_(evbuffer|buf)_has_control0 command: presents the same
3265 * interface as those underlying functions, but takes a connection_t intead of
3266 * an evbuffer or a buf_t.
3269 peek_connection_has_control0_command(connection_t
*conn
)
3271 IF_HAS_BUFFEREVENT(conn
, {
3272 struct evbuffer
*input
= bufferevent_get_input(conn
->bufev
);
3273 return peek_evbuffer_has_control0_command(input
);
3274 }) ELSE_IF_NO_BUFFEREVENT
{
3275 return peek_buf_has_control0_command(conn
->inbuf
);
3279 /** Called when data has arrived on a v1 control connection: Try to fetch
3280 * commands from conn->inbuf, and execute them.
3283 connection_control_process_inbuf(control_connection_t
*conn
)
3286 uint32_t cmd_data_len
;
3291 tor_assert(conn
->base_
.state
== CONTROL_CONN_STATE_OPEN
||
3292 conn
->base_
.state
== CONTROL_CONN_STATE_NEEDAUTH
);
3294 if (!conn
->incoming_cmd
) {
3295 conn
->incoming_cmd
= tor_malloc(1024);
3296 conn
->incoming_cmd_len
= 1024;
3297 conn
->incoming_cmd_cur_len
= 0;
3300 if (conn
->base_
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
3301 peek_connection_has_control0_command(TO_CONN(conn
))) {
3302 /* Detect v0 commands and send a "no more v0" message. */
3305 set_uint16(buf
+2, htons(0x0000)); /* type == error */
3306 set_uint16(buf
+4, htons(0x0001)); /* code == internal error */
3307 strlcpy(buf
+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
3308 "and later; upgrade your controller.",
3310 body_len
= 2+strlen(buf
+6)+2; /* code, msg, nul. */
3311 set_uint16(buf
+0, htons(body_len
));
3312 connection_write_to_buf(buf
, 4+body_len
, TO_CONN(conn
));
3314 connection_mark_and_flush(TO_CONN(conn
));
3322 /* First, fetch a line. */
3324 data_len
= conn
->incoming_cmd_len
- conn
->incoming_cmd_cur_len
;
3325 r
= connection_fetch_from_buf_line(TO_CONN(conn
),
3326 conn
->incoming_cmd
+conn
->incoming_cmd_cur_len
,
3329 /* Line not all here yet. Wait. */
3332 if (data_len
+ conn
->incoming_cmd_cur_len
> MAX_COMMAND_LINE_LENGTH
) {
3333 connection_write_str_to_buf("500 Line too long.\r\n", conn
);
3334 connection_stop_reading(TO_CONN(conn
));
3335 connection_mark_and_flush(TO_CONN(conn
));
3337 while (conn
->incoming_cmd_len
< data_len
+conn
->incoming_cmd_cur_len
)
3338 conn
->incoming_cmd_len
*= 2;
3339 conn
->incoming_cmd
= tor_realloc(conn
->incoming_cmd
,
3340 conn
->incoming_cmd_len
);
3344 tor_assert(data_len
);
3346 last_idx
= conn
->incoming_cmd_cur_len
;
3347 conn
->incoming_cmd_cur_len
+= (int)data_len
;
3349 /* We have appended a line to incoming_cmd. Is the command done? */
3350 if (last_idx
== 0 && *conn
->incoming_cmd
!= '+')
3351 /* One line command, didn't start with '+'. */
3353 /* XXXX this code duplication is kind of dumb. */
3354 if (last_idx
+3 == conn
->incoming_cmd_cur_len
&&
3355 tor_memeq(conn
->incoming_cmd
+ last_idx
, ".\r\n", 3)) {
3356 /* Just appended ".\r\n"; we're done. Remove it. */
3357 conn
->incoming_cmd
[last_idx
] = '\0';
3358 conn
->incoming_cmd_cur_len
-= 3;
3360 } else if (last_idx
+2 == conn
->incoming_cmd_cur_len
&&
3361 tor_memeq(conn
->incoming_cmd
+ last_idx
, ".\n", 2)) {
3362 /* Just appended ".\n"; we're done. Remove it. */
3363 conn
->incoming_cmd
[last_idx
] = '\0';
3364 conn
->incoming_cmd_cur_len
-= 2;
3367 /* Otherwise, read another line. */
3369 data_len
= conn
->incoming_cmd_cur_len
;
3370 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
3374 while ((size_t)cmd_len
< data_len
3375 && !TOR_ISSPACE(conn
->incoming_cmd
[cmd_len
]))
3378 conn
->incoming_cmd
[cmd_len
]='\0';
3379 args
= conn
->incoming_cmd
+cmd_len
+1;
3380 tor_assert(data_len
>(size_t)cmd_len
);
3381 data_len
-= (cmd_len
+1); /* skip the command and NUL we added after it */
3382 while (TOR_ISSPACE(*args
)) {
3387 /* If the connection is already closing, ignore further commands */
3388 if (TO_CONN(conn
)->marked_for_close
) {
3392 /* Otherwise, Quit is always valid. */
3393 if (!strcasecmp(conn
->incoming_cmd
, "QUIT")) {
3394 connection_write_str_to_buf("250 closing connection\r\n", conn
);
3395 connection_mark_and_flush(TO_CONN(conn
));
3399 if (conn
->base_
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
3400 !is_valid_initial_command(conn
, conn
->incoming_cmd
)) {
3401 connection_write_str_to_buf("514 Authentication required.\r\n", conn
);
3402 connection_mark_for_close(TO_CONN(conn
));
3406 if (data_len
>= UINT32_MAX
) {
3407 connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn
);
3408 connection_mark_for_close(TO_CONN(conn
));
3412 /* XXXX Why is this not implemented as a table like the GETINFO
3413 * items are? Even handling the plus signs at the beginnings of
3414 * commands wouldn't be very hard with proper macros. */
3415 cmd_data_len
= (uint32_t)data_len
;
3416 if (!strcasecmp(conn
->incoming_cmd
, "SETCONF")) {
3417 if (handle_control_setconf(conn
, cmd_data_len
, args
))
3419 } else if (!strcasecmp(conn
->incoming_cmd
, "RESETCONF")) {
3420 if (handle_control_resetconf(conn
, cmd_data_len
, args
))
3422 } else if (!strcasecmp(conn
->incoming_cmd
, "GETCONF")) {
3423 if (handle_control_getconf(conn
, cmd_data_len
, args
))
3425 } else if (!strcasecmp(conn
->incoming_cmd
, "+LOADCONF")) {
3426 if (handle_control_loadconf(conn
, cmd_data_len
, args
))
3428 } else if (!strcasecmp(conn
->incoming_cmd
, "SETEVENTS")) {
3429 if (handle_control_setevents(conn
, cmd_data_len
, args
))
3431 } else if (!strcasecmp(conn
->incoming_cmd
, "AUTHENTICATE")) {
3432 if (handle_control_authenticate(conn
, cmd_data_len
, args
))
3434 } else if (!strcasecmp(conn
->incoming_cmd
, "SAVECONF")) {
3435 if (handle_control_saveconf(conn
, cmd_data_len
, args
))
3437 } else if (!strcasecmp(conn
->incoming_cmd
, "SIGNAL")) {
3438 if (handle_control_signal(conn
, cmd_data_len
, args
))
3440 } else if (!strcasecmp(conn
->incoming_cmd
, "TAKEOWNERSHIP")) {
3441 if (handle_control_takeownership(conn
, cmd_data_len
, args
))
3443 } else if (!strcasecmp(conn
->incoming_cmd
, "MAPADDRESS")) {
3444 if (handle_control_mapaddress(conn
, cmd_data_len
, args
))
3446 } else if (!strcasecmp(conn
->incoming_cmd
, "GETINFO")) {
3447 if (handle_control_getinfo(conn
, cmd_data_len
, args
))
3449 } else if (!strcasecmp(conn
->incoming_cmd
, "EXTENDCIRCUIT")) {
3450 if (handle_control_extendcircuit(conn
, cmd_data_len
, args
))
3452 } else if (!strcasecmp(conn
->incoming_cmd
, "SETCIRCUITPURPOSE")) {
3453 if (handle_control_setcircuitpurpose(conn
, cmd_data_len
, args
))
3455 } else if (!strcasecmp(conn
->incoming_cmd
, "SETROUTERPURPOSE")) {
3456 connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn
);
3457 } else if (!strcasecmp(conn
->incoming_cmd
, "ATTACHSTREAM")) {
3458 if (handle_control_attachstream(conn
, cmd_data_len
, args
))
3460 } else if (!strcasecmp(conn
->incoming_cmd
, "+POSTDESCRIPTOR")) {
3461 if (handle_control_postdescriptor(conn
, cmd_data_len
, args
))
3463 } else if (!strcasecmp(conn
->incoming_cmd
, "REDIRECTSTREAM")) {
3464 if (handle_control_redirectstream(conn
, cmd_data_len
, args
))
3466 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSESTREAM")) {
3467 if (handle_control_closestream(conn
, cmd_data_len
, args
))
3469 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSECIRCUIT")) {
3470 if (handle_control_closecircuit(conn
, cmd_data_len
, args
))
3472 } else if (!strcasecmp(conn
->incoming_cmd
, "USEFEATURE")) {
3473 if (handle_control_usefeature(conn
, cmd_data_len
, args
))
3475 } else if (!strcasecmp(conn
->incoming_cmd
, "RESOLVE")) {
3476 if (handle_control_resolve(conn
, cmd_data_len
, args
))
3478 } else if (!strcasecmp(conn
->incoming_cmd
, "PROTOCOLINFO")) {
3479 if (handle_control_protocolinfo(conn
, cmd_data_len
, args
))
3481 } else if (!strcasecmp(conn
->incoming_cmd
, "AUTHCHALLENGE")) {
3482 if (handle_control_authchallenge(conn
, cmd_data_len
, args
))
3485 connection_printf_to_buf(conn
, "510 Unrecognized command \"%s\"\r\n",
3486 conn
->incoming_cmd
);
3489 conn
->incoming_cmd_cur_len
= 0;
3493 /** Something major has happened to circuit <b>circ</b>: tell any
3494 * interested control connections. */
3496 control_event_circuit_status(origin_circuit_t
*circ
, circuit_status_event_t tp
,
3500 char reasons
[64] = "";
3501 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS
))
3507 case CIRC_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
3508 case CIRC_EVENT_BUILT
: status
= "BUILT"; break;
3509 case CIRC_EVENT_EXTENDED
: status
= "EXTENDED"; break;
3510 case CIRC_EVENT_FAILED
: status
= "FAILED"; break;
3511 case CIRC_EVENT_CLOSED
: status
= "CLOSED"; break;
3513 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3514 tor_fragile_assert();
3518 if (tp
== CIRC_EVENT_FAILED
|| tp
== CIRC_EVENT_CLOSED
) {
3519 const char *reason_str
= circuit_end_reason_to_control_string(reason_code
);
3520 char unk_reason_buf
[16];
3522 tor_snprintf(unk_reason_buf
, 16, "UNKNOWN_%d", reason_code
);
3523 reason_str
= unk_reason_buf
;
3525 if (reason_code
> 0 && reason_code
& END_CIRC_REASON_FLAG_REMOTE
) {
3526 tor_snprintf(reasons
, sizeof(reasons
),
3527 " REASON=DESTROYED REMOTE_REASON=%s", reason_str
);
3529 tor_snprintf(reasons
, sizeof(reasons
),
3530 " REASON=%s", reason_str
);
3535 char *circdesc
= circuit_describe_status_for_controller(circ
);
3536 const char *sp
= strlen(circdesc
) ? " " : "";
3537 send_control_event(EVENT_CIRCUIT_STATUS
, ALL_FORMATS
,
3538 "650 CIRC %lu %s%s%s%s\r\n",
3539 (unsigned long)circ
->global_identifier
,
3549 /** Something minor has happened to circuit <b>circ</b>: tell any
3550 * interested control connections. */
3552 control_event_circuit_status_minor(origin_circuit_t
*circ
,
3553 circuit_status_minor_event_t e
,
3554 int purpose
, const struct timeval
*tv
)
3556 const char *event_desc
;
3557 char event_tail
[160] = "";
3558 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR
))
3564 case CIRC_MINOR_EVENT_PURPOSE_CHANGED
:
3565 event_desc
= "PURPOSE_CHANGED";
3568 /* event_tail can currently be up to 68 chars long */
3569 const char *hs_state_str
=
3570 circuit_purpose_to_controller_hs_state_string(purpose
);
3571 tor_snprintf(event_tail
, sizeof(event_tail
),
3572 " OLD_PURPOSE=%s%s%s",
3573 circuit_purpose_to_controller_string(purpose
),
3574 (hs_state_str
!= NULL
) ? " OLD_HS_STATE=" : "",
3575 (hs_state_str
!= NULL
) ? hs_state_str
: "");
3579 case CIRC_MINOR_EVENT_CANNIBALIZED
:
3580 event_desc
= "CANNIBALIZED";
3583 /* event_tail can currently be up to 130 chars long */
3584 const char *hs_state_str
=
3585 circuit_purpose_to_controller_hs_state_string(purpose
);
3586 const struct timeval
*old_timestamp_began
= tv
;
3587 char tbuf
[ISO_TIME_USEC_LEN
+1];
3588 format_iso_time_nospace_usec(tbuf
, old_timestamp_began
);
3590 tor_snprintf(event_tail
, sizeof(event_tail
),
3591 " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
3592 circuit_purpose_to_controller_string(purpose
),
3593 (hs_state_str
!= NULL
) ? " OLD_HS_STATE=" : "",
3594 (hs_state_str
!= NULL
) ? hs_state_str
: "",
3600 log_warn(LD_BUG
, "Unrecognized status code %d", (int)e
);
3601 tor_fragile_assert();
3606 char *circdesc
= circuit_describe_status_for_controller(circ
);
3607 const char *sp
= strlen(circdesc
) ? " " : "";
3608 send_control_event(EVENT_CIRCUIT_STATUS_MINOR
, ALL_FORMATS
,
3609 "650 CIRC_MINOR %lu %s%s%s%s\r\n",
3610 (unsigned long)circ
->global_identifier
,
3621 * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
3622 * interested controllers.
3625 control_event_circuit_purpose_changed(origin_circuit_t
*circ
,
3628 return control_event_circuit_status_minor(circ
,
3629 CIRC_MINOR_EVENT_PURPOSE_CHANGED
,
3635 * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
3636 * created-time from <b>old_tv_created</b>: tell any interested controllers.
3639 control_event_circuit_cannibalized(origin_circuit_t
*circ
,
3641 const struct timeval
*old_tv_created
)
3643 return control_event_circuit_status_minor(circ
,
3644 CIRC_MINOR_EVENT_CANNIBALIZED
,
3649 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
3650 * <b>buf</b>, determine the address:port combination requested on
3651 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
3654 write_stream_target_to_buf(entry_connection_t
*conn
, char *buf
, size_t len
)
3657 if (conn
->chosen_exit_name
)
3658 if (tor_snprintf(buf2
, sizeof(buf2
), ".%s.exit", conn
->chosen_exit_name
)<0)
3660 if (!conn
->socks_request
)
3662 if (tor_snprintf(buf
, len
, "%s%s%s:%d",
3663 conn
->socks_request
->address
,
3664 conn
->chosen_exit_name
? buf2
: "",
3665 !conn
->chosen_exit_name
&& connection_edge_is_rendezvous_stream(
3666 ENTRY_TO_EDGE_CONN(conn
)) ? ".onion" : "",
3667 conn
->socks_request
->port
)<0)
3672 /** Something has happened to the stream associated with AP connection
3673 * <b>conn</b>: tell any interested control connections. */
3675 control_event_stream_status(entry_connection_t
*conn
, stream_status_event_t tp
,
3678 char reason_buf
[64];
3679 char addrport_buf
[64];
3682 origin_circuit_t
*origin_circ
= NULL
;
3684 const char *purpose
= "";
3685 tor_assert(conn
->socks_request
);
3687 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS
))
3690 if (tp
== STREAM_EVENT_CLOSED
&&
3691 (reason_code
& END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
))
3694 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
3696 reason_buf
[0] = '\0';
3699 case STREAM_EVENT_SENT_CONNECT
: status
= "SENTCONNECT"; break;
3700 case STREAM_EVENT_SENT_RESOLVE
: status
= "SENTRESOLVE"; break;
3701 case STREAM_EVENT_SUCCEEDED
: status
= "SUCCEEDED"; break;
3702 case STREAM_EVENT_FAILED
: status
= "FAILED"; break;
3703 case STREAM_EVENT_CLOSED
: status
= "CLOSED"; break;
3704 case STREAM_EVENT_NEW
: status
= "NEW"; break;
3705 case STREAM_EVENT_NEW_RESOLVE
: status
= "NEWRESOLVE"; break;
3706 case STREAM_EVENT_FAILED_RETRIABLE
: status
= "DETACHED"; break;
3707 case STREAM_EVENT_REMAP
: status
= "REMAP"; break;
3709 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3712 if (reason_code
&& (tp
== STREAM_EVENT_FAILED
||
3713 tp
== STREAM_EVENT_CLOSED
||
3714 tp
== STREAM_EVENT_FAILED_RETRIABLE
)) {
3715 const char *reason_str
= stream_end_reason_to_control_string(reason_code
);
3718 tor_asprintf(&r
, " UNKNOWN_%d", reason_code
);
3721 if (reason_code
& END_STREAM_REASON_FLAG_REMOTE
)
3722 tor_snprintf(reason_buf
, sizeof(reason_buf
),
3723 " REASON=END REMOTE_REASON=%s", reason_str
);
3725 tor_snprintf(reason_buf
, sizeof(reason_buf
),
3726 " REASON=%s", reason_str
);
3728 } else if (reason_code
&& tp
== STREAM_EVENT_REMAP
) {
3729 switch (reason_code
) {
3730 case REMAP_STREAM_SOURCE_CACHE
:
3731 strlcpy(reason_buf
, " SOURCE=CACHE", sizeof(reason_buf
));
3733 case REMAP_STREAM_SOURCE_EXIT
:
3734 strlcpy(reason_buf
, " SOURCE=EXIT", sizeof(reason_buf
));
3737 tor_snprintf(reason_buf
, sizeof(reason_buf
), " REASON=UNKNOWN_%d",
3739 /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
3744 if (tp
== STREAM_EVENT_NEW
|| tp
== STREAM_EVENT_NEW_RESOLVE
) {
3746 * When the control conn is an AF_UNIX socket and we have no address,
3747 * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
3750 if (strcmp(ENTRY_TO_CONN(conn
)->address
, "(Tor_internal)") != 0) {
3751 tor_snprintf(addrport_buf
,sizeof(addrport_buf
), " SOURCE_ADDR=%s:%d",
3752 ENTRY_TO_CONN(conn
)->address
, ENTRY_TO_CONN(conn
)->port
);
3755 * else leave it blank so control on AF_UNIX doesn't need to make
3758 addrport_buf
[0] = '\0';
3761 addrport_buf
[0] = '\0';
3764 if (tp
== STREAM_EVENT_NEW_RESOLVE
) {
3765 purpose
= " PURPOSE=DNS_REQUEST";
3766 } else if (tp
== STREAM_EVENT_NEW
) {
3767 if (conn
->use_begindir
) {
3768 connection_t
*linked
= ENTRY_TO_CONN(conn
)->linked_conn
;
3769 int linked_dir_purpose
= -1;
3770 if (linked
&& linked
->type
== CONN_TYPE_DIR
)
3771 linked_dir_purpose
= linked
->purpose
;
3772 if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose
))
3773 purpose
= " PURPOSE=DIR_UPLOAD";
3775 purpose
= " PURPOSE=DIR_FETCH";
3777 purpose
= " PURPOSE=USER";
3780 circ
= circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn
));
3781 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
3782 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
3783 send_control_event(EVENT_STREAM_STATUS
, ALL_FORMATS
,
3784 "650 STREAM "U64_FORMAT
" %s %lu %s%s%s%s\r\n",
3785 U64_PRINTF_ARG(ENTRY_TO_CONN(conn
)->global_identifier
),
3788 (unsigned long)origin_circ
->global_identifier
: 0ul,
3789 buf
, reason_buf
, addrport_buf
, purpose
);
3791 /* XXX need to specify its intended exit, etc? */
3796 /** Figure out the best name for the target router of an OR connection
3797 * <b>conn</b>, and write it into the <b>len</b>-character buffer
3800 orconn_target_get_name(char *name
, size_t len
, or_connection_t
*conn
)
3802 const node_t
*node
= node_get_by_id(conn
->identity_digest
);
3804 tor_assert(len
> MAX_VERBOSE_NICKNAME_LEN
);
3805 node_get_verbose_nickname(node
, name
);
3806 } else if (! tor_digest_is_zero(conn
->identity_digest
)) {
3808 base16_encode(name
+1, len
-1, conn
->identity_digest
,
3811 tor_snprintf(name
, len
, "%s:%d",
3812 conn
->base_
.address
, conn
->base_
.port
);
3816 /** Called when the status of an OR connection <b>conn</b> changes: tell any
3817 * interested control connections. <b>tp</b> is the new status for the
3818 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
3819 * may be the reason why.
3822 control_event_or_conn_status(or_connection_t
*conn
, or_conn_status_event_t tp
,
3828 char ncircs_buf
[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
3830 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS
))
3835 case OR_CONN_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
3836 case OR_CONN_EVENT_CONNECTED
: status
= "CONNECTED"; break;
3837 case OR_CONN_EVENT_FAILED
: status
= "FAILED"; break;
3838 case OR_CONN_EVENT_CLOSED
: status
= "CLOSED"; break;
3839 case OR_CONN_EVENT_NEW
: status
= "NEW"; break;
3841 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3845 ncircs
= circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn
->chan
));
3849 ncircs
+= connection_or_get_num_circuits(conn
);
3850 if (ncircs
&& (tp
== OR_CONN_EVENT_FAILED
|| tp
== OR_CONN_EVENT_CLOSED
)) {
3851 tor_snprintf(ncircs_buf
, sizeof(ncircs_buf
), "%sNCIRCS=%d",
3852 reason
? " " : "", ncircs
);
3855 orconn_target_get_name(name
, sizeof(name
), conn
);
3856 send_control_event(EVENT_OR_CONN_STATUS
, ALL_FORMATS
,
3857 "650 ORCONN %s %s %s%s%s\r\n",
3859 reason
? "REASON=" : "",
3860 orconn_end_reason_to_control_string(reason
),
3867 * Print out STREAM_BW event for a single conn
3870 control_event_stream_bandwidth(edge_connection_t
*edge_conn
)
3872 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED
)) {
3873 if (!edge_conn
->n_read
&& !edge_conn
->n_written
)
3876 send_control_event(EVENT_STREAM_BANDWIDTH_USED
, ALL_FORMATS
,
3877 "650 STREAM_BW "U64_FORMAT
" %lu %lu\r\n",
3878 U64_PRINTF_ARG(edge_conn
->base_
.global_identifier
),
3879 (unsigned long)edge_conn
->n_read
,
3880 (unsigned long)edge_conn
->n_written
);
3882 edge_conn
->n_written
= edge_conn
->n_read
= 0;
3888 /** A second or more has elapsed: tell any interested control
3889 * connections how much bandwidth streams have used. */
3891 control_event_stream_bandwidth_used(void)
3893 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED
)) {
3894 smartlist_t
*conns
= get_connection_array();
3895 edge_connection_t
*edge_conn
;
3897 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
)
3899 if (conn
->type
!= CONN_TYPE_AP
)
3901 edge_conn
= TO_EDGE_CONN(conn
);
3902 if (!edge_conn
->n_read
&& !edge_conn
->n_written
)
3905 send_control_event(EVENT_STREAM_BANDWIDTH_USED
, ALL_FORMATS
,
3906 "650 STREAM_BW "U64_FORMAT
" %lu %lu\r\n",
3907 U64_PRINTF_ARG(edge_conn
->base_
.global_identifier
),
3908 (unsigned long)edge_conn
->n_read
,
3909 (unsigned long)edge_conn
->n_written
);
3911 edge_conn
->n_written
= edge_conn
->n_read
= 0;
3913 SMARTLIST_FOREACH_END(conn
);
3919 /** A second or more has elapsed: tell any interested control
3920 * connections how much bandwidth we used. */
3922 control_event_bandwidth_used(uint32_t n_read
, uint32_t n_written
)
3924 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED
)) {
3925 send_control_event(EVENT_BANDWIDTH_USED
, ALL_FORMATS
,
3926 "650 BW %lu %lu\r\n",
3927 (unsigned long)n_read
,
3928 (unsigned long)n_written
);
3934 /** Called when we are sending a log message to the controllers: suspend
3935 * sending further log messages to the controllers until we're done. Used by
3936 * CONN_LOG_PROTECT. */
3938 disable_control_logging(void)
3940 ++disable_log_messages
;
3943 /** We're done sending a log message to the controllers: re-enable controller
3944 * logging. Used by CONN_LOG_PROTECT. */
3946 enable_control_logging(void)
3948 if (--disable_log_messages
< 0)
3952 /** We got a log message: tell any interested control connections. */
3954 control_event_logmsg(int severity
, uint32_t domain
, const char *msg
)
3958 /* Don't even think of trying to add stuff to a buffer from a cpuworker
3960 if (! in_main_thread())
3963 if (disable_log_messages
)
3966 if (domain
== LD_BUG
&& EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
) &&
3967 severity
<= LOG_NOTICE
) {
3968 char *esc
= esc_for_log(msg
);
3969 ++disable_log_messages
;
3970 control_event_general_status(severity
, "BUG REASON=%s", esc
);
3971 --disable_log_messages
;
3975 event
= log_severity_to_event(severity
);
3976 if (event
>= 0 && EVENT_IS_INTERESTING(event
)) {
3979 if (strchr(msg
, '\n')) {
3981 b
= tor_strdup(msg
);
3982 for (cp
= b
; *cp
; ++cp
)
3983 if (*cp
== '\r' || *cp
== '\n')
3987 case LOG_DEBUG
: s
= "DEBUG"; break;
3988 case LOG_INFO
: s
= "INFO"; break;
3989 case LOG_NOTICE
: s
= "NOTICE"; break;
3990 case LOG_WARN
: s
= "WARN"; break;
3991 case LOG_ERR
: s
= "ERR"; break;
3992 default: s
= "UnknownLogSeverity"; break;
3994 ++disable_log_messages
;
3995 send_control_event(event
, ALL_FORMATS
, "650 %s %s\r\n", s
, b
?b
:msg
);
3996 --disable_log_messages
;
4001 /** Called whenever we receive new router descriptors: tell any
4002 * interested control connections. <b>routers</b> is a list of
4006 control_event_descriptors_changed(smartlist_t
*routers
)
4010 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC
))
4014 smartlist_t
*names
= smartlist_new();
4016 SMARTLIST_FOREACH(routers
, routerinfo_t
*, ri
, {
4017 char *b
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
4018 router_get_verbose_nickname(b
, ri
);
4019 smartlist_add(names
, b
);
4021 ids
= smartlist_join_strings(names
, " ", 0, NULL
);
4022 tor_asprintf(&msg
, "650 NEWDESC %s\r\n", ids
);
4023 send_control_event_string(EVENT_NEW_DESC
, ALL_FORMATS
, msg
);
4026 SMARTLIST_FOREACH(names
, char *, cp
, tor_free(cp
));
4027 smartlist_free(names
);
4032 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
4033 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
4034 * <b>error</b> is non-NULL, it is an error code describing the failure
4035 * mode of the mapping.
4038 control_event_address_mapped(const char *from
, const char *to
, time_t expires
,
4039 const char *error
, const int cached
)
4041 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP
))
4044 if (expires
< 3 || expires
== TIME_MAX
)
4045 send_control_event(EVENT_ADDRMAP
, ALL_FORMATS
,
4046 "650 ADDRMAP %s %s NEVER %s%s"
4047 "CACHED=\"%s\"\r\n",
4048 from
, to
, error
?error
:"", error
?" ":"",
4051 char buf
[ISO_TIME_LEN
+1];
4052 char buf2
[ISO_TIME_LEN
+1];
4053 format_local_iso_time(buf
,expires
);
4054 format_iso_time(buf2
,expires
);
4055 send_control_event(EVENT_ADDRMAP
, ALL_FORMATS
,
4056 "650 ADDRMAP %s %s \"%s\""
4057 " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
4059 error
?error
:"", error
?" ":"",
4060 buf2
, cached
?"YES":"NO");
4066 /** The authoritative dirserver has received a new descriptor that
4067 * has passed basic syntax checks and is properly self-signed.
4069 * Notify any interested party of the new descriptor and what has
4070 * been done with it, and also optionally give an explanation/reason. */
4072 control_event_or_authdir_new_descriptor(const char *action
,
4073 const char *desc
, size_t desclen
,
4076 char firstline
[1024];
4082 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS
))
4085 tor_snprintf(firstline
, sizeof(firstline
),
4086 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
4090 /* Escape the server descriptor properly */
4091 esclen
= write_escaped_data(desc
, desclen
, &esc
);
4093 totallen
= strlen(firstline
) + esclen
+ 1;
4094 buf
= tor_malloc(totallen
);
4095 strlcpy(buf
, firstline
, totallen
);
4096 strlcpy(buf
+strlen(firstline
), esc
, totallen
);
4097 send_control_event_string(EVENT_AUTHDIR_NEWDESCS
, ALL_FORMATS
,
4099 send_control_event_string(EVENT_AUTHDIR_NEWDESCS
, ALL_FORMATS
,
4107 /** Helper function for NS-style events. Constructs and sends an event
4108 * of type <b>event</b> with string <b>event_string</b> out of the set of
4109 * networkstatuses <b>statuses</b>. Currently it is used for NS events
4110 * and NEWCONSENSUS events. */
4112 control_event_networkstatus_changed_helper(smartlist_t
*statuses
,
4114 const char *event_string
)
4117 char *s
, *esc
= NULL
;
4118 if (!EVENT_IS_INTERESTING(event
) || !smartlist_len(statuses
))
4121 strs
= smartlist_new();
4122 smartlist_add(strs
, tor_strdup("650+"));
4123 smartlist_add(strs
, tor_strdup(event_string
));
4124 smartlist_add(strs
, tor_strdup("\r\n"));
4125 SMARTLIST_FOREACH(statuses
, const routerstatus_t
*, rs
,
4127 s
= networkstatus_getinfo_helper_single(rs
);
4129 smartlist_add(strs
, s
);
4132 s
= smartlist_join_strings(strs
, "", 0, NULL
);
4133 write_escaped_data(s
, strlen(s
), &esc
);
4134 SMARTLIST_FOREACH(strs
, char *, cp
, tor_free(cp
));
4135 smartlist_free(strs
);
4137 send_control_event_string(event
, ALL_FORMATS
, esc
);
4138 send_control_event_string(event
, ALL_FORMATS
,
4145 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
4146 * an NS event to any controller that cares. */
4148 control_event_networkstatus_changed(smartlist_t
*statuses
)
4150 return control_event_networkstatus_changed_helper(statuses
, EVENT_NS
, "NS");
4153 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
4154 * event consisting of an NS-style line for each relay in the consensus. */
4156 control_event_newconsensus(const networkstatus_t
*consensus
)
4158 if (!control_event_is_interesting(EVENT_NEWCONSENSUS
))
4160 return control_event_networkstatus_changed_helper(
4161 consensus
->routerstatus_list
, EVENT_NEWCONSENSUS
, "NEWCONSENSUS");
4164 /** Called when we compute a new circuitbuildtimeout */
4166 control_event_buildtimeout_set(const circuit_build_times_t
*cbt
,
4167 buildtimeout_set_event_t type
)
4169 const char *type_string
= NULL
;
4172 if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET
))
4175 qnt
= circuit_build_times_quantile_cutoff();
4178 case BUILDTIMEOUT_SET_EVENT_COMPUTED
:
4179 type_string
= "COMPUTED";
4181 case BUILDTIMEOUT_SET_EVENT_RESET
:
4182 type_string
= "RESET";
4185 case BUILDTIMEOUT_SET_EVENT_SUSPENDED
:
4186 type_string
= "SUSPENDED";
4189 case BUILDTIMEOUT_SET_EVENT_DISCARD
:
4190 type_string
= "DISCARD";
4193 case BUILDTIMEOUT_SET_EVENT_RESUME
:
4194 type_string
= "RESUME";
4197 type_string
= "UNKNOWN";
4201 send_control_event(EVENT_BUILDTIMEOUT_SET
, ALL_FORMATS
,
4202 "650 BUILDTIMEOUT_SET %s TOTAL_TIMES=%lu "
4203 "TIMEOUT_MS=%lu XM=%lu ALPHA=%f CUTOFF_QUANTILE=%f "
4204 "TIMEOUT_RATE=%f CLOSE_MS=%lu CLOSE_RATE=%f\r\n",
4205 type_string
, (unsigned long)cbt
->total_build_times
,
4206 (unsigned long)cbt
->timeout_ms
,
4207 (unsigned long)cbt
->Xm
, cbt
->alpha
, qnt
,
4208 circuit_build_times_timeout_rate(cbt
),
4209 (unsigned long)cbt
->close_ms
,
4210 circuit_build_times_close_rate(cbt
));
4215 /** Called when a signal has been processed from signal_callback */
4217 control_event_signal(uintptr_t signal
)
4219 const char *signal_string
= NULL
;
4221 if (!control_event_is_interesting(EVENT_SIGNAL
))
4226 signal_string
= "RELOAD";
4229 signal_string
= "DUMP";
4232 signal_string
= "DEBUG";
4235 signal_string
= "NEWNYM";
4237 case SIGCLEARDNSCACHE
:
4238 signal_string
= "CLEARDNSCACHE";
4241 log_warn(LD_BUG
, "Unrecognized signal %lu in control_event_signal",
4242 (unsigned long)signal
);
4246 send_control_event(EVENT_SIGNAL
, ALL_FORMATS
, "650 SIGNAL %s\r\n",
4251 /** Called when a single local_routerstatus_t has changed: Sends an NS event
4252 * to any controller that cares. */
4254 control_event_networkstatus_changed_single(const routerstatus_t
*rs
)
4256 smartlist_t
*statuses
;
4259 if (!EVENT_IS_INTERESTING(EVENT_NS
))
4262 statuses
= smartlist_new();
4263 smartlist_add(statuses
, (void*)rs
);
4264 r
= control_event_networkstatus_changed(statuses
);
4265 smartlist_free(statuses
);
4269 /** Our own router descriptor has changed; tell any controllers that care.
4272 control_event_my_descriptor_changed(void)
4274 send_control_event(EVENT_DESCCHANGED
, ALL_FORMATS
, "650 DESCCHANGED\r\n");
4278 /** Helper: sends a status event where <b>type</b> is one of
4279 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
4280 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
4281 * string corresponding to <b>args</b>. */
4283 control_event_status(int type
, int severity
, const char *format
, va_list args
)
4285 char *user_buf
= NULL
;
4286 char format_buf
[160];
4287 const char *status
, *sev
;
4290 case EVENT_STATUS_GENERAL
:
4291 status
= "STATUS_GENERAL";
4293 case EVENT_STATUS_CLIENT
:
4294 status
= "STATUS_CLIENT";
4296 case EVENT_STATUS_SERVER
:
4297 status
= "STATUS_SERVER";
4300 log_warn(LD_BUG
, "Unrecognized status type %d", type
);
4314 log_warn(LD_BUG
, "Unrecognized status severity %d", severity
);
4317 if (tor_snprintf(format_buf
, sizeof(format_buf
), "650 %s %s",
4319 log_warn(LD_BUG
, "Format string too long.");
4322 tor_vasprintf(&user_buf
, format
, args
);
4324 send_control_event(type
, ALL_FORMATS
, "%s %s\r\n", format_buf
, user_buf
);
4329 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
4330 * by formatting the arguments using the printf-style <b>format</b>. */
4332 control_event_general_status(int severity
, const char *format
, ...)
4336 if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
))
4339 va_start(ap
, format
);
4340 r
= control_event_status(EVENT_STATUS_GENERAL
, severity
, format
, ap
);
4345 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
4346 * by formatting the arguments using the printf-style <b>format</b>. */
4348 control_event_client_status(int severity
, const char *format
, ...)
4352 if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT
))
4355 va_start(ap
, format
);
4356 r
= control_event_status(EVENT_STATUS_CLIENT
, severity
, format
, ap
);
4361 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
4362 * by formatting the arguments using the printf-style <b>format</b>. */
4364 control_event_server_status(int severity
, const char *format
, ...)
4368 if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER
))
4371 va_start(ap
, format
);
4372 r
= control_event_status(EVENT_STATUS_SERVER
, severity
, format
, ap
);
4377 /** Called when the status of an entry guard with the given <b>nickname</b>
4378 * and identity <b>digest</b> has changed to <b>status</b>: tells any
4379 * controllers that care. */
4381 control_event_guard(const char *nickname
, const char *digest
,
4384 char hbuf
[HEX_DIGEST_LEN
+1];
4385 base16_encode(hbuf
, sizeof(hbuf
), digest
, DIGEST_LEN
);
4386 if (!EVENT_IS_INTERESTING(EVENT_GUARD
))
4390 char buf
[MAX_VERBOSE_NICKNAME_LEN
+1];
4391 const node_t
*node
= node_get_by_id(digest
);
4393 node_get_verbose_nickname(node
, buf
);
4395 tor_snprintf(buf
, sizeof(buf
), "$%s~%s", hbuf
, nickname
);
4397 send_control_event(EVENT_GUARD
, ALL_FORMATS
,
4398 "650 GUARD ENTRY %s %s\r\n", buf
, status
);
4403 /** Called when a configuration option changes. This is generally triggered
4404 * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
4405 * a smartlist_t containing (key, value, ...) pairs in sequence.
4406 * <b>value</b> can be NULL. */
4408 control_event_conf_changed(const smartlist_t
*elements
)
4413 if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED
) ||
4414 smartlist_len(elements
) == 0) {
4417 lines
= smartlist_new();
4418 for (i
= 0; i
< smartlist_len(elements
); i
+= 2) {
4419 char *k
= smartlist_get(elements
, i
);
4420 char *v
= smartlist_get(elements
, i
+1);
4422 smartlist_add_asprintf(lines
, "650-%s", k
);
4424 smartlist_add_asprintf(lines
, "650-%s=%s", k
, v
);
4427 result
= smartlist_join_strings(lines
, "\r\n", 0, NULL
);
4428 send_control_event(EVENT_CONF_CHANGED
, 0,
4429 "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result
);
4431 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
4432 smartlist_free(lines
);
4436 /** Helper: Return a newly allocated string containing a path to the
4437 * file where we store our authentication cookie. */
4439 get_cookie_file(void)
4441 const or_options_t
*options
= get_options();
4442 if (options
->CookieAuthFile
&& strlen(options
->CookieAuthFile
)) {
4443 return tor_strdup(options
->CookieAuthFile
);
4445 return get_datadir_fname("control_auth_cookie");
4449 /* Initialize the cookie-based authentication system of the
4450 * ControlPort. If <b>enabled</b> is 0, then disable the cookie
4451 * authentication system. */
4453 init_control_cookie_authentication(int enabled
)
4459 authentication_cookie_is_set
= 0;
4463 fname
= get_cookie_file();
4464 retval
= init_cookie_authentication(fname
, "", /* no header */
4465 AUTHENTICATION_COOKIE_LEN
,
4466 &authentication_cookie
,
4467 &authentication_cookie_is_set
);
4472 /** A copy of the process specifier of Tor's owning controller, or
4473 * NULL if this Tor instance is not currently owned by a process. */
4474 static char *owning_controller_process_spec
= NULL
;
4476 /** A process-termination monitor for Tor's owning controller, or NULL
4477 * if this Tor instance is not currently owned by a process. */
4478 static tor_process_monitor_t
*owning_controller_process_monitor
= NULL
;
4480 /** Process-termination monitor callback for Tor's owning controller
4483 owning_controller_procmon_cb(void *unused
)
4487 lost_owning_controller("process", "vanished");
4490 /** Set <b>process_spec</b> as Tor's owning controller process.
4491 * Exit on failure. */
4493 monitor_owning_controller_process(const char *process_spec
)
4497 tor_assert((owning_controller_process_spec
== NULL
) ==
4498 (owning_controller_process_monitor
== NULL
));
4500 if (owning_controller_process_spec
!= NULL
) {
4501 if ((process_spec
!= NULL
) && !strcmp(process_spec
,
4502 owning_controller_process_spec
)) {
4503 /* Same process -- return now, instead of disposing of and
4504 * recreating the process-termination monitor. */
4508 /* We are currently owned by a process, and we should no longer be
4509 * owned by it. Free the process-termination monitor. */
4510 tor_process_monitor_free(owning_controller_process_monitor
);
4511 owning_controller_process_monitor
= NULL
;
4513 tor_free(owning_controller_process_spec
);
4514 owning_controller_process_spec
= NULL
;
4517 tor_assert((owning_controller_process_spec
== NULL
) &&
4518 (owning_controller_process_monitor
== NULL
));
4520 if (process_spec
== NULL
)
4523 owning_controller_process_spec
= tor_strdup(process_spec
);
4524 owning_controller_process_monitor
=
4525 tor_process_monitor_new(tor_libevent_get_base(),
4526 owning_controller_process_spec
,
4528 owning_controller_procmon_cb
, NULL
,
4531 if (owning_controller_process_monitor
== NULL
) {
4532 log_err(LD_BUG
, "Couldn't create process-termination monitor for "
4533 "owning controller: %s. Exiting.",
4535 owning_controller_process_spec
= NULL
;
4541 /** Convert the name of a bootstrapping phase <b>s</b> into strings
4542 * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
4544 bootstrap_status_to_string(bootstrap_status_t s
, const char **tag
,
4545 const char **summary
)
4548 case BOOTSTRAP_STATUS_UNDEF
:
4550 *summary
= "Undefined";
4552 case BOOTSTRAP_STATUS_STARTING
:
4554 *summary
= "Starting";
4556 case BOOTSTRAP_STATUS_CONN_DIR
:
4558 *summary
= "Connecting to directory server";
4560 case BOOTSTRAP_STATUS_HANDSHAKE
:
4561 *tag
= "status_handshake";
4562 *summary
= "Finishing handshake";
4564 case BOOTSTRAP_STATUS_HANDSHAKE_DIR
:
4565 *tag
= "handshake_dir";
4566 *summary
= "Finishing handshake with directory server";
4568 case BOOTSTRAP_STATUS_ONEHOP_CREATE
:
4569 *tag
= "onehop_create";
4570 *summary
= "Establishing an encrypted directory connection";
4572 case BOOTSTRAP_STATUS_REQUESTING_STATUS
:
4573 *tag
= "requesting_status";
4574 *summary
= "Asking for networkstatus consensus";
4576 case BOOTSTRAP_STATUS_LOADING_STATUS
:
4577 *tag
= "loading_status";
4578 *summary
= "Loading networkstatus consensus";
4580 case BOOTSTRAP_STATUS_LOADING_KEYS
:
4581 *tag
= "loading_keys";
4582 *summary
= "Loading authority key certs";
4584 case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS
:
4585 *tag
= "requesting_descriptors";
4586 *summary
= "Asking for relay descriptors";
4588 case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS
:
4589 *tag
= "loading_descriptors";
4590 *summary
= "Loading relay descriptors";
4592 case BOOTSTRAP_STATUS_CONN_OR
:
4594 *summary
= "Connecting to the Tor network";
4596 case BOOTSTRAP_STATUS_HANDSHAKE_OR
:
4597 *tag
= "handshake_or";
4598 *summary
= "Finishing handshake with first hop";
4600 case BOOTSTRAP_STATUS_CIRCUIT_CREATE
:
4601 *tag
= "circuit_create";
4602 *summary
= "Establishing a Tor circuit";
4604 case BOOTSTRAP_STATUS_DONE
:
4609 // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
4610 *tag
= *summary
= "unknown";
4616 /** What percentage through the bootstrap process are we? We remember
4617 * this so we can avoid sending redundant bootstrap status events, and
4618 * so we can guess context for the bootstrap messages which are
4619 * ambiguous. It starts at 'undef', but gets set to 'starting' while
4620 * Tor initializes. */
4621 static int bootstrap_percent
= BOOTSTRAP_STATUS_UNDEF
;
4623 /** How many problems have we had getting to the next bootstrapping phase?
4624 * These include failure to establish a connection to a Tor relay,
4625 * failures to finish the TLS handshake, failures to validate the
4626 * consensus document, etc. */
4627 static int bootstrap_problems
= 0;
4629 /* We only tell the controller once we've hit a threshold of problems
4630 * for the current phase. */
4631 #define BOOTSTRAP_PROBLEM_THRESHOLD 10
4633 /** Called when Tor has made progress at bootstrapping its directory
4634 * information and initial circuits.
4636 * <b>status</b> is the new status, that is, what task we will be doing
4637 * next. <b>progress</b> is zero if we just started this task, else it
4638 * represents progress on the task. */
4640 control_event_bootstrap(bootstrap_status_t status
, int progress
)
4642 const char *tag
, *summary
;
4643 char buf
[BOOTSTRAP_MSG_LEN
];
4645 if (bootstrap_percent
== BOOTSTRAP_STATUS_DONE
)
4646 return; /* already bootstrapped; nothing to be done here. */
4648 /* special case for handshaking status, since our TLS handshaking code
4649 * can't distinguish what the connection is going to be for. */
4650 if (status
== BOOTSTRAP_STATUS_HANDSHAKE
) {
4651 if (bootstrap_percent
< BOOTSTRAP_STATUS_CONN_OR
) {
4652 status
= BOOTSTRAP_STATUS_HANDSHAKE_DIR
;
4654 status
= BOOTSTRAP_STATUS_HANDSHAKE_OR
;
4658 if (status
> bootstrap_percent
||
4659 (progress
&& progress
> bootstrap_percent
)) {
4660 bootstrap_status_to_string(status
, &tag
, &summary
);
4661 tor_log(status
? LOG_NOTICE
: LOG_INFO
, LD_CONTROL
,
4662 "Bootstrapped %d%%: %s.", progress
? progress
: status
, summary
);
4663 tor_snprintf(buf
, sizeof(buf
),
4664 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
4665 progress
? progress
: status
, tag
, summary
);
4666 tor_snprintf(last_sent_bootstrap_message
,
4667 sizeof(last_sent_bootstrap_message
),
4669 control_event_client_status(LOG_NOTICE
, "%s", buf
);
4670 if (status
> bootstrap_percent
) {
4671 bootstrap_percent
= status
; /* new milestone reached */
4673 if (progress
> bootstrap_percent
) {
4674 /* incremental progress within a milestone */
4675 bootstrap_percent
= progress
;
4676 bootstrap_problems
= 0; /* Progress! Reset our problem counter. */
4681 /** Called when Tor has failed to make bootstrapping progress in a way
4682 * that indicates a problem. <b>warn</b> gives a hint as to why, and
4683 * <b>reason</b> provides an "or_conn_end_reason" tag.
4686 control_event_bootstrap_problem
, (const char *warn
, int reason
))
4688 int status
= bootstrap_percent
;
4689 const char *tag
, *summary
;
4690 char buf
[BOOTSTRAP_MSG_LEN
];
4691 const char *recommendation
= "ignore";
4694 /* bootstrap_percent must not be in "undefined" state here. */
4695 tor_assert(status
>= 0);
4697 if (bootstrap_percent
== 100)
4698 return; /* already bootstrapped; nothing to be done here. */
4700 bootstrap_problems
++;
4702 if (bootstrap_problems
>= BOOTSTRAP_PROBLEM_THRESHOLD
)
4703 recommendation
= "warn";
4705 if (reason
== END_OR_CONN_REASON_NO_ROUTE
)
4706 recommendation
= "warn";
4708 if (get_options()->UseBridges
&&
4709 !any_bridge_descriptors_known() &&
4710 !any_pending_bridge_descriptor_fetches())
4711 recommendation
= "warn";
4713 if (we_are_hibernating())
4714 recommendation
= "ignore";
4716 while (status
>=0 && bootstrap_status_to_string(status
, &tag
, &summary
) < 0)
4717 status
--; /* find a recognized status string based on current progress */
4718 status
= bootstrap_percent
; /* set status back to the actual number */
4720 severity
= !strcmp(recommendation
, "warn") ? LOG_WARN
: LOG_INFO
;
4723 LD_CONTROL
, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
4724 "count %d; recommendation %s)",
4725 status
, summary
, warn
,
4726 orconn_end_reason_to_control_string(reason
),
4727 bootstrap_problems
, recommendation
);
4729 connection_or_report_broken_states(severity
, LD_HANDSHAKE
);
4731 tor_snprintf(buf
, sizeof(buf
),
4732 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
4733 "COUNT=%d RECOMMENDATION=%s",
4734 bootstrap_percent
, tag
, summary
, warn
,
4735 orconn_end_reason_to_control_string(reason
), bootstrap_problems
,
4737 tor_snprintf(last_sent_bootstrap_message
,
4738 sizeof(last_sent_bootstrap_message
),
4740 control_event_client_status(LOG_WARN
, "%s", buf
);
4743 /** We just generated a new summary of which countries we've seen clients
4744 * from recently. Send a copy to the controller in case it wants to
4745 * display it for the user. */
4747 control_event_clients_seen(const char *controller_str
)
4749 send_control_event(EVENT_CLIENTS_SEEN
, 0,
4750 "650 CLIENTS_SEEN %s\r\n", controller_str
);