1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2011, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
7 * \brief Implementation for Tor's control-socket interface.
8 * See doc/spec/control-spec.txt for full details on protocol.
11 #define CONTROL_PRIVATE
15 #include "circuitbuild.h"
16 #include "circuitlist.h"
17 #include "circuituse.h"
19 #include "connection.h"
20 #include "connection_edge.h"
22 #include "directory.h"
26 #include "hibernate.h"
28 #include "networkstatus.h"
32 #include "routerlist.h"
33 #include "routerparse.h"
37 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
38 * finished authentication and is accepting commands. */
39 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
41 /* Recognized asynchronous event types. It's okay to expand this list
42 * because it is used both as a list of v0 event types, and as indices
43 * into the bitfield to determine which controllers want which events.
45 #define _EVENT_MIN 0x0001
46 #define EVENT_CIRCUIT_STATUS 0x0001
47 #define EVENT_STREAM_STATUS 0x0002
48 #define EVENT_OR_CONN_STATUS 0x0003
49 #define EVENT_BANDWIDTH_USED 0x0004
50 #define EVENT_LOG_OBSOLETE 0x0005 /* Can reclaim this. */
51 #define EVENT_NEW_DESC 0x0006
52 #define EVENT_DEBUG_MSG 0x0007
53 #define EVENT_INFO_MSG 0x0008
54 #define EVENT_NOTICE_MSG 0x0009
55 #define EVENT_WARN_MSG 0x000A
56 #define EVENT_ERR_MSG 0x000B
57 #define EVENT_ADDRMAP 0x000C
58 // #define EVENT_AUTHDIR_NEWDESCS 0x000D
59 #define EVENT_DESCCHANGED 0x000E
60 // #define EVENT_NS 0x000F
61 #define EVENT_STATUS_CLIENT 0x0010
62 #define EVENT_STATUS_SERVER 0x0011
63 #define EVENT_STATUS_GENERAL 0x0012
64 #define EVENT_GUARD 0x0013
65 #define EVENT_STREAM_BANDWIDTH_USED 0x0014
66 #define EVENT_CLIENTS_SEEN 0x0015
67 #define EVENT_NEWCONSENSUS 0x0016
68 #define EVENT_BUILDTIMEOUT_SET 0x0017
69 #define _EVENT_MAX 0x0017
70 /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
72 /** Bitfield: The bit 1<<e is set if <b>any</b> open control
73 * connection is interested in events of type <b>e</b>. We use this
74 * so that we can decide to skip generating event messages that nobody
75 * has interest in without having to walk over the global connection
78 typedef uint32_t event_mask_t
;
80 /** An event mask of all the events that any controller is interested in
82 static event_mask_t global_event_mask
= 0;
84 /** True iff we have disabled log messages from being sent to the controller */
85 static int disable_log_messages
= 0;
87 /** Macro: true if any control connection is interested in events of type
89 #define EVENT_IS_INTERESTING(e) \
90 (global_event_mask & (1<<(e)))
92 /** If we're using cookie-type authentication, how long should our cookies be?
94 #define AUTHENTICATION_COOKIE_LEN 32
96 /** If true, we've set authentication_cookie to a secret code and
97 * stored it to disk. */
98 static int authentication_cookie_is_set
= 0;
99 /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
100 * and which we're using to authenticate controllers. (If the controller can
101 * read it off disk, it has permission to connect. */
102 static char authentication_cookie
[AUTHENTICATION_COOKIE_LEN
];
104 /** A sufficiently large size to record the last bootstrap phase string. */
105 #define BOOTSTRAP_MSG_LEN 1024
107 /** What was the last bootstrap phase message we sent? We keep track
108 * of this so we can respond to getinfo status/bootstrap-phase queries. */
109 static char last_sent_bootstrap_message
[BOOTSTRAP_MSG_LEN
];
111 /** Flag for event_format_t. Indicates that we should use the one standard
114 #define ALL_FORMATS 1
116 /** Bit field of flags to select how to format a controller event. Recognized
117 * flag is ALL_FORMATS. */
118 typedef int event_format_t
;
120 static void connection_printf_to_buf(control_connection_t
*conn
,
121 const char *format
, ...)
123 static void send_control_done(control_connection_t
*conn
);
124 static void send_control_event(uint16_t event
, event_format_t which
,
125 const char *format
, ...)
127 static int handle_control_setconf(control_connection_t
*conn
, uint32_t len
,
129 static int handle_control_resetconf(control_connection_t
*conn
, uint32_t len
,
131 static int handle_control_getconf(control_connection_t
*conn
, uint32_t len
,
133 static int handle_control_loadconf(control_connection_t
*conn
, uint32_t len
,
135 static int handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
137 static int handle_control_authenticate(control_connection_t
*conn
,
140 static int handle_control_signal(control_connection_t
*conn
, uint32_t len
,
142 static int handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
144 static char *list_getinfo_options(void);
145 static int handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
147 static int handle_control_extendcircuit(control_connection_t
*conn
,
150 static int handle_control_setcircuitpurpose(control_connection_t
*conn
,
151 uint32_t len
, const char *body
);
152 static int handle_control_attachstream(control_connection_t
*conn
,
155 static int handle_control_postdescriptor(control_connection_t
*conn
,
158 static int handle_control_redirectstream(control_connection_t
*conn
,
161 static int handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
163 static int handle_control_closecircuit(control_connection_t
*conn
,
166 static int handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
168 static int handle_control_usefeature(control_connection_t
*conn
,
171 static int write_stream_target_to_buf(edge_connection_t
*conn
, char *buf
,
173 static void orconn_target_get_name(char *buf
, size_t len
,
174 or_connection_t
*conn
);
175 static char *get_cookie_file(void);
177 /** Given a control event code for a message event, return the corresponding
180 event_to_log_severity(int event
)
183 case EVENT_DEBUG_MSG
: return LOG_DEBUG
;
184 case EVENT_INFO_MSG
: return LOG_INFO
;
185 case EVENT_NOTICE_MSG
: return LOG_NOTICE
;
186 case EVENT_WARN_MSG
: return LOG_WARN
;
187 case EVENT_ERR_MSG
: return LOG_ERR
;
192 /** Given a log severity, return the corresponding control event code. */
194 log_severity_to_event(int severity
)
197 case LOG_DEBUG
: return EVENT_DEBUG_MSG
;
198 case LOG_INFO
: return EVENT_INFO_MSG
;
199 case LOG_NOTICE
: return EVENT_NOTICE_MSG
;
200 case LOG_WARN
: return EVENT_WARN_MSG
;
201 case LOG_ERR
: return EVENT_ERR_MSG
;
206 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
207 * connection's event_mask field. */
209 control_update_global_event_mask(void)
211 smartlist_t
*conns
= get_connection_array();
212 event_mask_t old_mask
, new_mask
;
213 old_mask
= global_event_mask
;
215 global_event_mask
= 0;
216 SMARTLIST_FOREACH(conns
, connection_t
*, _conn
,
218 if (_conn
->type
== CONN_TYPE_CONTROL
&&
219 STATE_IS_OPEN(_conn
->state
)) {
220 control_connection_t
*conn
= TO_CONTROL_CONN(_conn
);
221 global_event_mask
|= conn
->event_mask
;
225 new_mask
= global_event_mask
;
227 /* Handle the aftermath. Set up the log callback to tell us only what
228 * we want to hear...*/
229 control_adjust_event_log_severity();
231 /* ...then, if we've started logging stream bw, clear the appropriate
233 if (! (old_mask
& EVENT_STREAM_BANDWIDTH_USED
) &&
234 (new_mask
& EVENT_STREAM_BANDWIDTH_USED
)) {
235 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
237 if (conn
->type
== CONN_TYPE_AP
) {
238 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
239 edge_conn
->n_written
= edge_conn
->n_read
= 0;
245 /** Adjust the log severities that result in control_event_logmsg being called
246 * to match the severity of log messages that any controllers are interested
249 control_adjust_event_log_severity(void)
252 int min_log_event
=EVENT_ERR_MSG
, max_log_event
=EVENT_DEBUG_MSG
;
254 for (i
= EVENT_DEBUG_MSG
; i
<= EVENT_ERR_MSG
; ++i
) {
255 if (EVENT_IS_INTERESTING(i
)) {
260 for (i
= EVENT_ERR_MSG
; i
>= EVENT_DEBUG_MSG
; --i
) {
261 if (EVENT_IS_INTERESTING(i
)) {
266 if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE
) ||
267 EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
)) {
268 if (min_log_event
> EVENT_NOTICE_MSG
)
269 min_log_event
= EVENT_NOTICE_MSG
;
270 if (max_log_event
< EVENT_ERR_MSG
)
271 max_log_event
= EVENT_ERR_MSG
;
273 if (min_log_event
<= max_log_event
)
274 change_callback_log_severity(event_to_log_severity(min_log_event
),
275 event_to_log_severity(max_log_event
),
276 control_event_logmsg
);
278 change_callback_log_severity(LOG_ERR
, LOG_ERR
,
279 control_event_logmsg
);
282 /** Return true iff the event with code <b>c</b> is being sent to any current
283 * control connection. This is useful if the amount of work needed to prepare
284 * to call the appropriate control_event_...() function is high.
287 control_event_is_interesting(int event
)
289 return EVENT_IS_INTERESTING(event
);
292 /** Append a NUL-terminated string <b>s</b> to the end of
293 * <b>conn</b>-\>outbuf.
296 connection_write_str_to_buf(const char *s
, control_connection_t
*conn
)
298 size_t len
= strlen(s
);
299 connection_write_to_buf(s
, len
, TO_CONN(conn
));
302 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
303 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
304 * contents of <b>data</b> into *<b>out</b>, adding a period before any period
305 * that appears at the start of a line, and adding a period-CRLF line at
306 * the end. Replace all LF characters sequences with CRLF. Return the number
307 * of bytes in *<b>out</b>.
310 write_escaped_data(const char *data
, size_t len
, char **out
)
312 size_t sz_out
= len
+8;
314 const char *start
= data
, *end
;
317 for (i
=0; i
<(int)len
; ++i
) {
319 sz_out
+= 2; /* Maybe add a CR; maybe add a dot. */
321 *out
= outp
= tor_malloc(sz_out
+1);
326 if (data
> start
&& data
[-1] != '\r')
329 } else if (*data
== '.') {
339 if (outp
< *out
+2 || fast_memcmp(outp
-2, "\r\n", 2)) {
346 *outp
= '\0'; /* NUL-terminate just in case. */
347 tor_assert((outp
- *out
) <= (int)sz_out
);
351 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
352 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
353 * the contents of <b>data</b> into *<b>out</b>, removing any period
354 * that appears at the start of a line, and replacing all CRLF sequences
355 * with LF. Return the number of
356 * bytes in *<b>out</b>. */
358 read_escaped_data(const char *data
, size_t len
, char **out
)
364 *out
= outp
= tor_malloc(len
+1);
369 /* we're at the start of a line. */
372 next
= memchr(data
, '\n', end
-data
);
374 size_t n_to_copy
= next
-data
;
375 /* Don't copy a CR that precedes this LF. */
376 if (n_to_copy
&& *(next
-1) == '\r')
378 memcpy(outp
, data
, n_to_copy
);
380 data
= next
+1; /* This will point at the start of the next line,
381 * or the end of the string, or a period. */
383 memcpy(outp
, data
, end
-data
);
395 /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
396 * double-quoted string with escaped characters, return the length of that
397 * string (as encoded, including quotes). Otherwise return -1. */
399 get_escaped_string_length(const char *start
, size_t in_len_max
,
402 const char *cp
, *end
;
409 end
= start
+in_len_max
;
411 /* Calculate length. */
414 return -1; /* Too long. */
415 } else if (*cp
== '\\') {
417 return -1; /* Can't escape EOS. */
420 } else if (*cp
== '\"') {
429 return (int)(cp
- start
+1);
432 /** As decode_escaped_string, but does not decode the string: copies the
433 * entire thing, including quotation marks. */
435 extract_escaped_string(const char *start
, size_t in_len_max
,
436 char **out
, size_t *out_len
)
438 int length
= get_escaped_string_length(start
, in_len_max
, NULL
);
442 *out
= tor_strndup(start
, *out_len
);
446 /** Given a pointer to a string starting at <b>start</b> containing
447 * <b>in_len_max</b> characters, decode a string beginning with one double
448 * quote, containing any number of non-quote characters or characters escaped
449 * with a backslash, and ending with a final double quote. Place the resulting
450 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
451 * store its length in <b>out_len</b>. On success, return a pointer to the
452 * character immediately following the escaped string. On failure, return
455 decode_escaped_string(const char *start
, size_t in_len_max
,
456 char **out
, size_t *out_len
)
458 const char *cp
, *end
;
460 int len
, n_chars
= 0;
462 len
= get_escaped_string_length(start
, in_len_max
, &n_chars
);
466 end
= start
+len
-1; /* Index of last quote. */
467 tor_assert(*end
== '\"');
468 outp
= *out
= tor_malloc(len
+1);
478 tor_assert((outp
- *out
) == (int)*out_len
);
483 /** Acts like sprintf, but writes its formatted string to the end of
484 * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
485 * but it will always end with a CRLF sequence.
487 * Currently the length of the message is limited to 1024 (including the
488 * ending CR LF NUL ("\\r\\n\\0"). */
490 connection_printf_to_buf(control_connection_t
*conn
, const char *format
, ...)
492 #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
494 char buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
];
498 r
= tor_vsnprintf(buf
, sizeof(buf
), format
, ap
);
501 log_warn(LD_BUG
, "Unable to format string for controller.");
505 if (fast_memcmp("\r\n\0", buf
+len
-2, 3)) {
506 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-1] = '\0';
507 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-2] = '\n';
508 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-3] = '\r';
510 connection_write_to_buf(buf
, len
, TO_CONN(conn
));
513 /** Write all of the open control ports to ControlPortWriteToFile */
515 control_ports_write_to_file(void)
519 or_options_t
*options
= get_options();
521 if (!options
->ControlPortWriteToFile
)
524 lines
= smartlist_create();
526 SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t
*, conn
) {
527 char *port_str
= NULL
;
528 if (conn
->type
!= CONN_TYPE_CONTROL_LISTENER
|| conn
->marked_for_close
)
531 if (conn
->socket_family
== AF_UNIX
) {
532 tor_asprintf(&port_str
, "UNIX_PORT=%s\n", conn
->address
);
533 smartlist_add(lines
, port_str
);
537 tor_asprintf(&port_str
, "PORT=%s:%d\n", conn
->address
, conn
->port
);
538 smartlist_add(lines
, port_str
);
539 } SMARTLIST_FOREACH_END(conn
);
541 joined
= smartlist_join_strings(lines
, "", 0, NULL
);
543 if (write_str_to_file(options
->ControlPortWriteToFile
, joined
, 0) < 0) {
544 log_warn(LD_CONTROL
, "Writing %s failed: %s",
545 options
->ControlPortWriteToFile
, strerror(errno
));
548 if (options
->ControlPortFileGroupReadable
) {
549 if (chmod(options
->ControlPortWriteToFile
, 0640)) {
550 log_warn(LD_FS
,"Unable to make %s group-readable.",
551 options
->ControlPortWriteToFile
);
556 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
557 smartlist_free(lines
);
560 /** Send a "DONE" message down the control connection <b>conn</b>. */
562 send_control_done(control_connection_t
*conn
)
564 connection_write_str_to_buf("250 OK\r\n", conn
);
567 /** Send an event to all v1 controllers that are listening for code
568 * <b>event</b>. The event's body is given by <b>msg</b>.
570 * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
571 * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
572 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
573 * to controllers that <em>have</em> enabled VERBOSE_NAMES.
575 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
576 * respect to the EXTENDED_EVENTS feature. */
578 send_control_event_string(uint16_t event
, event_format_t which
,
581 smartlist_t
*conns
= get_connection_array();
583 tor_assert(event
>= _EVENT_MIN
&& event
<= _EVENT_MAX
);
585 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
586 if (conn
->type
== CONN_TYPE_CONTROL
&&
587 !conn
->marked_for_close
&&
588 conn
->state
== CONTROL_CONN_STATE_OPEN
) {
589 control_connection_t
*control_conn
= TO_CONTROL_CONN(conn
);
591 if (control_conn
->event_mask
& (1<<event
)) {
593 connection_write_to_buf(msg
, strlen(msg
), TO_CONN(control_conn
));
594 if (event
== EVENT_ERR_MSG
)
596 else if (event
== EVENT_STATUS_GENERAL
)
597 is_err
= !strcmpstart(msg
, "STATUS_GENERAL ERR ");
598 else if (event
== EVENT_STATUS_CLIENT
)
599 is_err
= !strcmpstart(msg
, "STATUS_CLIENT ERR ");
600 else if (event
== EVENT_STATUS_SERVER
)
601 is_err
= !strcmpstart(msg
, "STATUS_SERVER ERR ");
603 connection_handle_write(TO_CONN(control_conn
), 1);
606 } SMARTLIST_FOREACH_END(conn
);
609 /** Helper for send_control1_event and send_control1_event_extended:
610 * Send an event to all v1 controllers that are listening for code
611 * <b>event</b>. The event's body is created by the printf-style format in
612 * <b>format</b>, and other arguments as provided.
614 * Currently the length of the message is limited to 1024 (including the
615 * ending \\r\\n\\0). */
617 send_control_event_impl(uint16_t event
, event_format_t which
,
618 const char *format
, va_list ap
)
620 /* This is just a little longer than the longest allowed log message */
621 #define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
623 char buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
];
626 r
= tor_vsnprintf(buf
, sizeof(buf
), format
, ap
);
628 log_warn(LD_BUG
, "Unable to format event for controller.");
633 if (fast_memcmp("\r\n\0", buf
+len
-2, 3)) {
634 /* if it is not properly terminated, do it now */
635 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-1] = '\0';
636 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-2] = '\n';
637 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-3] = '\r';
640 send_control_event_string(event
, which
|ALL_FORMATS
, buf
);
643 /** Send an event to all v1 controllers that are listening for code
644 * <b>event</b>. The event's body is created by the printf-style format in
645 * <b>format</b>, and other arguments as provided.
647 * Currently the length of the message is limited to 1024 (including the
648 * ending \\n\\r\\0. */
650 send_control_event(uint16_t event
, event_format_t which
,
651 const char *format
, ...)
654 va_start(ap
, format
);
655 send_control_event_impl(event
, which
, format
, ap
);
659 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
660 static origin_circuit_t
*
661 get_circ(const char *id
)
665 n_id
= (uint32_t) tor_parse_ulong(id
, 10, 0, UINT32_MAX
, &ok
, NULL
);
668 return circuit_get_by_global_id(n_id
);
671 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
672 static edge_connection_t
*
673 get_stream(const char *id
)
678 n_id
= tor_parse_uint64(id
, 10, 0, UINT64_MAX
, &ok
, NULL
);
681 conn
= connection_get_by_global_id(n_id
);
682 if (!conn
|| conn
->type
!= CONN_TYPE_AP
|| conn
->marked_for_close
)
684 return TO_EDGE_CONN(conn
);
687 /** Helper for setconf and resetconf. Acts like setconf, except
688 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
692 control_setconf_helper(control_connection_t
*conn
, uint32_t len
, char *body
,
695 setopt_err_t opt_err
;
696 config_line_t
*lines
=NULL
;
698 char *errstring
= NULL
;
699 const int clear_first
= 1;
702 smartlist_t
*entries
= smartlist_create();
704 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
705 * separated by space. break it into a list of configuration entries. */
710 while (!TOR_ISSPACE(*eq
) && *eq
!= '=')
712 key
= tor_strndup(body
, eq
-body
);
719 char *val_start
= body
;
720 while (!TOR_ISSPACE(*body
))
722 val
= tor_strndup(val_start
, body
-val_start
);
723 val_len
= strlen(val
);
725 body
= (char*)extract_escaped_string(body
, (len
- (body
-start
)),
728 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn
);
729 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
730 smartlist_free(entries
);
735 ent_len
= strlen(key
)+val_len
+3;
736 entry
= tor_malloc(ent_len
+1);
737 tor_snprintf(entry
, ent_len
, "%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) {
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_create();
819 smartlist_t
*answers
= smartlist_create();
820 smartlist_t
*unrecognized
= smartlist_create();
823 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(questions
, const char *, q
,
831 if (!option_is_recognized(q
)) {
832 smartlist_add(unrecognized
, (char*) q
);
834 config_line_t
*answer
= option_get_assignment(options
,q
);
836 const char *name
= option_get_canonical_name(q
);
837 size_t alen
= strlen(name
)+8;
838 char *astr
= tor_malloc(alen
);
839 tor_snprintf(astr
, alen
, "250-%s\r\n", name
);
840 smartlist_add(answers
, astr
);
845 size_t alen
= strlen(answer
->key
)+strlen(answer
->value
)+8;
846 char *astr
= tor_malloc(alen
);
847 tor_snprintf(astr
, alen
, "250-%s=%s\r\n",
848 answer
->key
, answer
->value
);
849 smartlist_add(answers
, astr
);
852 tor_free(answer
->key
);
853 tor_free(answer
->value
);
860 if ((len
= smartlist_len(unrecognized
))) {
861 for (i
=0; i
< len
-1; ++i
)
862 connection_printf_to_buf(conn
,
863 "552-Unrecognized configuration key \"%s\"\r\n",
864 (char*)smartlist_get(unrecognized
, i
));
865 connection_printf_to_buf(conn
,
866 "552 Unrecognized configuration key \"%s\"\r\n",
867 (char*)smartlist_get(unrecognized
, len
-1));
868 } else if ((len
= smartlist_len(answers
))) {
869 char *tmp
= smartlist_get(answers
, len
-1);
870 tor_assert(strlen(tmp
)>4);
872 msg
= smartlist_join_strings(answers
, "", 0, &msg_len
);
873 connection_write_to_buf(msg
, msg_len
, TO_CONN(conn
));
875 connection_write_str_to_buf("250 OK\r\n", conn
);
878 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
879 smartlist_free(answers
);
880 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
881 smartlist_free(questions
);
882 smartlist_free(unrecognized
);
889 /** Called when we get a +LOADCONF message. */
891 handle_control_loadconf(control_connection_t
*conn
, uint32_t len
,
895 char *errstring
= NULL
;
896 const char *msg
= NULL
;
899 retval
= options_init_from_string(body
, CMD_RUN_TOR
, NULL
, &errstring
);
901 if (retval
!= SETOPT_OK
)
903 "Controller gave us config file that didn't validate: %s",
907 case SETOPT_ERR_PARSE
:
908 msg
= "552 Invalid config file";
910 case SETOPT_ERR_TRANSITION
:
911 msg
= "553 Transition not allowed";
913 case SETOPT_ERR_SETTING
:
914 msg
= "553 Unable to set option";
916 case SETOPT_ERR_MISC
:
918 msg
= "550 Unable to load config";
925 connection_printf_to_buf(conn
, "%s: %s\r\n", msg
, errstring
);
927 connection_printf_to_buf(conn
, "%s\r\n", msg
);
929 send_control_done(conn
);
935 /** Called when we get a SETEVENTS message: update conn->event_mask,
936 * and reply with DONE or ERROR. */
938 handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
942 uint32_t event_mask
= 0;
943 smartlist_t
*events
= smartlist_create();
947 smartlist_split_string(events
, body
, " ",
948 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
949 SMARTLIST_FOREACH_BEGIN(events
, const char *, ev
)
951 if (!strcasecmp(ev
, "EXTENDED")) {
953 } else if (!strcasecmp(ev
, "CIRC"))
954 event_code
= EVENT_CIRCUIT_STATUS
;
955 else if (!strcasecmp(ev
, "STREAM"))
956 event_code
= EVENT_STREAM_STATUS
;
957 else if (!strcasecmp(ev
, "ORCONN"))
958 event_code
= EVENT_OR_CONN_STATUS
;
959 else if (!strcasecmp(ev
, "BW"))
960 event_code
= EVENT_BANDWIDTH_USED
;
961 else if (!strcasecmp(ev
, "DEBUG"))
962 event_code
= EVENT_DEBUG_MSG
;
963 else if (!strcasecmp(ev
, "INFO"))
964 event_code
= EVENT_INFO_MSG
;
965 else if (!strcasecmp(ev
, "NOTICE"))
966 event_code
= EVENT_NOTICE_MSG
;
967 else if (!strcasecmp(ev
, "WARN"))
968 event_code
= EVENT_WARN_MSG
;
969 else if (!strcasecmp(ev
, "ERR"))
970 event_code
= EVENT_ERR_MSG
;
971 else if (!strcasecmp(ev
, "NEWDESC"))
972 event_code
= EVENT_NEW_DESC
;
973 else if (!strcasecmp(ev
, "ADDRMAP"))
974 event_code
= EVENT_ADDRMAP
;
975 else if (!strcasecmp(ev
, "AUTHDIR_NEWDESCS"))
976 event_code
= EVENT_AUTHDIR_NEWDESCS
;
977 else if (!strcasecmp(ev
, "DESCCHANGED"))
978 event_code
= EVENT_DESCCHANGED
;
979 else if (!strcasecmp(ev
, "NS"))
980 event_code
= EVENT_NS
;
981 else if (!strcasecmp(ev
, "STATUS_GENERAL"))
982 event_code
= EVENT_STATUS_GENERAL
;
983 else if (!strcasecmp(ev
, "STATUS_CLIENT"))
984 event_code
= EVENT_STATUS_CLIENT
;
985 else if (!strcasecmp(ev
, "STATUS_SERVER"))
986 event_code
= EVENT_STATUS_SERVER
;
987 else if (!strcasecmp(ev
, "GUARD"))
988 event_code
= EVENT_GUARD
;
989 else if (!strcasecmp(ev
, "STREAM_BW"))
990 event_code
= EVENT_STREAM_BANDWIDTH_USED
;
991 else if (!strcasecmp(ev
, "CLIENTS_SEEN"))
992 event_code
= EVENT_CLIENTS_SEEN
;
993 else if (!strcasecmp(ev
, "NEWCONSENSUS"))
994 event_code
= EVENT_NEWCONSENSUS
;
995 else if (!strcasecmp(ev
, "BUILDTIMEOUT_SET"))
996 event_code
= EVENT_BUILDTIMEOUT_SET
;
998 connection_printf_to_buf(conn
, "552 Unrecognized event \"%s\"\r\n",
1000 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
1001 smartlist_free(events
);
1004 event_mask
|= (1 << event_code
);
1006 SMARTLIST_FOREACH_END(ev
);
1007 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
1008 smartlist_free(events
);
1010 conn
->event_mask
= event_mask
;
1012 control_update_global_event_mask();
1013 send_control_done(conn
);
1017 /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
1018 * Return a smartlist of acceptable passwords (unterminated strings of
1019 * length S2K_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on failure.
1022 decode_hashed_passwords(config_line_t
*passwords
)
1026 smartlist_t
*sl
= smartlist_create();
1028 tor_assert(passwords
);
1030 for (cl
= passwords
; cl
; cl
= cl
->next
) {
1031 const char *hashed
= cl
->value
;
1033 if (!strcmpstart(hashed
, "16:")) {
1034 if (base16_decode(decoded
, sizeof(decoded
), hashed
+3, strlen(hashed
+3))<0
1035 || strlen(hashed
+3) != (S2K_SPECIFIER_LEN
+DIGEST_LEN
)*2) {
1039 if (base64_decode(decoded
, sizeof(decoded
), hashed
, strlen(hashed
))
1040 != S2K_SPECIFIER_LEN
+DIGEST_LEN
) {
1044 smartlist_add(sl
, tor_memdup(decoded
, S2K_SPECIFIER_LEN
+DIGEST_LEN
));
1050 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
1055 /** Called when we get an AUTHENTICATE message. Check whether the
1056 * authentication is valid, and if so, update the connection's state to
1057 * OPEN. Reply with DONE or ERROR.
1060 handle_control_authenticate(control_connection_t
*conn
, uint32_t len
,
1063 int used_quoted_string
= 0;
1064 or_options_t
*options
= get_options();
1065 const char *errstr
= NULL
;
1067 size_t password_len
;
1070 int bad_cookie
=0, bad_password
=0;
1071 smartlist_t
*sl
= NULL
;
1073 if (TOR_ISXDIGIT(body
[0])) {
1075 while (TOR_ISXDIGIT(*cp
))
1077 i
= (int)(cp
- body
);
1080 password
= tor_malloc(password_len
+ 1);
1081 if (base16_decode(password
, password_len
+1, body
, i
)<0) {
1082 connection_write_str_to_buf(
1083 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1084 "password? If so, the standard requires that you put it in "
1085 "double quotes.\r\n", conn
);
1086 connection_mark_for_close(TO_CONN(conn
));
1090 } else if (TOR_ISSPACE(body
[0])) {
1091 password
= tor_strdup("");
1094 if (!decode_escaped_string(body
, len
, &password
, &password_len
)) {
1095 connection_write_str_to_buf("551 Invalid quoted string. You need "
1096 "to put the password in double quotes.\r\n", conn
);
1097 connection_mark_for_close(TO_CONN(conn
));
1100 used_quoted_string
= 1;
1103 if (!options
->CookieAuthentication
&& !options
->HashedControlPassword
&&
1104 !options
->HashedControlSessionPassword
) {
1105 /* if Tor doesn't demand any stronger authentication, then
1106 * the controller can get in with anything. */
1110 if (options
->CookieAuthentication
) {
1111 int also_password
= options
->HashedControlPassword
!= NULL
||
1112 options
->HashedControlSessionPassword
!= NULL
;
1113 if (password_len
!= AUTHENTICATION_COOKIE_LEN
) {
1114 if (!also_password
) {
1115 log_warn(LD_CONTROL
, "Got authentication cookie with wrong length "
1116 "(%d)", (int)password_len
);
1117 errstr
= "Wrong length on authentication cookie.";
1121 } else if (tor_memneq(authentication_cookie
, password
, password_len
)) {
1122 if (!also_password
) {
1123 log_warn(LD_CONTROL
, "Got mismatched authentication cookie");
1124 errstr
= "Authentication cookie did not match expected value.";
1133 if (options
->HashedControlPassword
||
1134 options
->HashedControlSessionPassword
) {
1136 smartlist_t
*sl_tmp
;
1137 char received
[DIGEST_LEN
];
1138 int also_cookie
= options
->CookieAuthentication
;
1139 sl
= smartlist_create();
1140 if (options
->HashedControlPassword
) {
1141 sl_tmp
= decode_hashed_passwords(options
->HashedControlPassword
);
1145 smartlist_add_all(sl
, sl_tmp
);
1146 smartlist_free(sl_tmp
);
1149 if (options
->HashedControlSessionPassword
) {
1150 sl_tmp
= decode_hashed_passwords(options
->HashedControlSessionPassword
);
1154 smartlist_add_all(sl
, sl_tmp
);
1155 smartlist_free(sl_tmp
);
1160 log_warn(LD_CONTROL
,
1161 "Couldn't decode HashedControlPassword: invalid base16");
1162 errstr
="Couldn't decode HashedControlPassword value in configuration.";
1165 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1168 SMARTLIST_FOREACH(sl
, char *, expected
,
1170 secret_to_key(received
,DIGEST_LEN
,password
,password_len
,expected
);
1171 if (tor_memeq(expected
+S2K_SPECIFIER_LEN
, received
, DIGEST_LEN
))
1174 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1177 if (used_quoted_string
)
1178 errstr
= "Password did not match HashedControlPassword value from "
1181 errstr
= "Password did not match HashedControlPassword value from "
1182 "configuration. Maybe you tried a plain text password? "
1183 "If so, the standard requires that you put it in double quotes.";
1190 /** We only get here if both kinds of authentication failed. */
1191 tor_assert(bad_password
&& bad_cookie
);
1192 log_warn(LD_CONTROL
, "Bad password or authentication cookie on controller.");
1193 errstr
= "Password did not match HashedControlPassword *or* authentication "
1198 connection_printf_to_buf(conn
, "515 Authentication failed: %s\r\n",
1199 errstr
? errstr
: "Unknown reason.");
1200 connection_mark_for_close(TO_CONN(conn
));
1203 log_info(LD_CONTROL
, "Authenticated control connection (%d)", conn
->_base
.s
);
1204 send_control_done(conn
);
1205 conn
->_base
.state
= CONTROL_CONN_STATE_OPEN
;
1207 if (sl
) { /* clean up */
1208 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1214 /** Called when we get a SAVECONF command. Try to flush the current options to
1215 * disk, and report success or failure. */
1217 handle_control_saveconf(control_connection_t
*conn
, uint32_t len
,
1222 if (options_save_current()<0) {
1223 connection_write_str_to_buf(
1224 "551 Unable to write configuration to disk.\r\n", conn
);
1226 send_control_done(conn
);
1231 /** Called when we get a SIGNAL command. React to the provided signal, and
1232 * report success or failure. (If the signal results in a shutdown, success
1233 * may not be reported.) */
1235 handle_control_signal(control_connection_t
*conn
, uint32_t len
,
1244 while (body
[n
] && ! TOR_ISSPACE(body
[n
]))
1246 s
= tor_strndup(body
, n
);
1247 if (!strcasecmp(s
, "RELOAD") || !strcasecmp(s
, "HUP"))
1249 else if (!strcasecmp(s
, "SHUTDOWN") || !strcasecmp(s
, "INT"))
1251 else if (!strcasecmp(s
, "DUMP") || !strcasecmp(s
, "USR1"))
1253 else if (!strcasecmp(s
, "DEBUG") || !strcasecmp(s
, "USR2"))
1255 else if (!strcasecmp(s
, "HALT") || !strcasecmp(s
, "TERM"))
1257 else if (!strcasecmp(s
, "NEWNYM"))
1259 else if (!strcasecmp(s
, "CLEARDNSCACHE"))
1260 sig
= SIGCLEARDNSCACHE
;
1262 connection_printf_to_buf(conn
, "552 Unrecognized signal code \"%s\"\r\n",
1270 send_control_done(conn
);
1271 /* Flush the "done" first if the signal might make us shut down. */
1272 if (sig
== SIGTERM
|| sig
== SIGINT
)
1273 connection_handle_write(TO_CONN(conn
), 1);
1275 process_signal(sig
);
1280 /** Called when we get a TAKEOWNERSHIP command. Mark this connection
1281 * as an owning connection, so that we will exit if the connection
1284 handle_control_takeownership(control_connection_t
*conn
, uint32_t len
,
1290 conn
->is_owning_control_connection
= 1;
1292 log_info(LD_CONTROL
, "Control connection %d has taken ownership of this "
1294 (int)(conn
->_base
.s
));
1296 send_control_done(conn
);
1300 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1301 * and report success or failure. */
1303 handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
1311 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
1313 lines
= smartlist_create();
1314 elts
= smartlist_create();
1315 reply
= smartlist_create();
1316 smartlist_split_string(lines
, body
, " ",
1317 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1318 SMARTLIST_FOREACH(lines
, char *, line
,
1321 smartlist_split_string(elts
, line
, "=", 0, 2);
1322 if (smartlist_len(elts
) == 2) {
1323 const char *from
= smartlist_get(elts
,0);
1324 const char *to
= smartlist_get(elts
,1);
1325 size_t anslen
= strlen(line
)+512;
1326 char *ans
= tor_malloc(anslen
);
1327 if (address_is_invalid_destination(to
, 1)) {
1328 tor_snprintf(ans
, anslen
,
1329 "512-syntax error: invalid address '%s'", to
);
1330 smartlist_add(reply
, ans
);
1331 log_warn(LD_CONTROL
,
1332 "Skipping invalid argument '%s' in MapAddress msg", to
);
1333 } else if (!strcmp(from
, ".") || !strcmp(from
, "0.0.0.0")) {
1334 const char *address
= addressmap_register_virtual_address(
1335 !strcmp(from
,".") ? RESOLVED_TYPE_HOSTNAME
: RESOLVED_TYPE_IPV4
,
1338 tor_snprintf(ans
, anslen
,
1339 "451-resource exhausted: skipping '%s'", line
);
1340 smartlist_add(reply
, ans
);
1341 log_warn(LD_CONTROL
,
1342 "Unable to allocate address for '%s' in MapAddress msg",
1343 safe_str_client(line
));
1345 tor_snprintf(ans
, anslen
, "250-%s=%s", address
, to
);
1346 smartlist_add(reply
, ans
);
1349 addressmap_register(from
, tor_strdup(to
), 1, ADDRMAPSRC_CONTROLLER
);
1350 tor_snprintf(ans
, anslen
, "250-%s", line
);
1351 smartlist_add(reply
, ans
);
1354 size_t anslen
= strlen(line
)+256;
1355 char *ans
= tor_malloc(anslen
);
1356 tor_snprintf(ans
, anslen
, "512-syntax error: mapping '%s' is "
1357 "not of expected form 'foo=bar'.", line
);
1358 smartlist_add(reply
, ans
);
1359 log_info(LD_CONTROL
, "Skipping MapAddress '%s': wrong "
1361 safe_str_client(line
));
1363 SMARTLIST_FOREACH(elts
, char *, cp
, tor_free(cp
));
1364 smartlist_clear(elts
);
1366 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
1367 smartlist_free(lines
);
1368 smartlist_free(elts
);
1370 if (smartlist_len(reply
)) {
1371 ((char*)smartlist_get(reply
,smartlist_len(reply
)-1))[3] = ' ';
1372 r
= smartlist_join_strings(reply
, "\r\n", 1, &sz
);
1373 connection_write_to_buf(r
, sz
, TO_CONN(conn
));
1376 const char *response
=
1377 "512 syntax error: not enough arguments to mapaddress.\r\n";
1378 connection_write_to_buf(response
, strlen(response
), TO_CONN(conn
));
1381 SMARTLIST_FOREACH(reply
, char *, cp
, tor_free(cp
));
1382 smartlist_free(reply
);
1386 /** Implementation helper for GETINFO: knows the answers for various
1387 * trivial-to-implement questions. */
1389 getinfo_helper_misc(control_connection_t
*conn
, const char *question
,
1390 char **answer
, const char **errmsg
)
1393 if (!strcmp(question
, "version")) {
1394 *answer
= tor_strdup(get_version());
1395 } else if (!strcmp(question
, "config-file")) {
1396 *answer
= tor_strdup(get_torrc_fname());
1397 } else if (!strcmp(question
, "config-text")) {
1398 *answer
= options_dump(get_options(), 1);
1399 } else if (!strcmp(question
, "info/names")) {
1400 *answer
= list_getinfo_options();
1401 } else if (!strcmp(question
, "events/names")) {
1402 *answer
= tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
1403 "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
1404 "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
1405 "GUARD STREAM_BW CLIENTS_SEEN NEWCONSENSUS");
1406 } else if (!strcmp(question
, "features/names")) {
1407 *answer
= tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1408 } else if (!strcmp(question
, "address")) {
1410 if (router_pick_published_address(get_options(), &addr
) < 0) {
1411 *errmsg
= "Address unknown";
1414 *answer
= tor_dup_ip(addr
);
1415 } else if (!strcmp(question
, "dir-usage")) {
1416 *answer
= directory_dump_request_log();
1417 } else if (!strcmp(question
, "fingerprint")) {
1418 routerinfo_t
*me
= router_get_my_routerinfo();
1420 *errmsg
= "No routerdesc known; am I really a server?";
1423 *answer
= tor_malloc(HEX_DIGEST_LEN
+1);
1424 base16_encode(*answer
, HEX_DIGEST_LEN
+1, me
->cache_info
.identity_digest
,
1430 /** Awful hack: return a newly allocated string based on a routerinfo and
1431 * (possibly) an extrainfo, sticking the read-history and write-history from
1432 * <b>ei</b> into the resulting string. The thing you get back won't
1433 * necessarily have a valid signature.
1435 * New code should never use this; it's for backward compatibility.
1437 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1438 * not be NUL-terminated. */
1440 munge_extrainfo_into_routerinfo(const char *ri_body
, signed_descriptor_t
*ri
,
1441 signed_descriptor_t
*ei
)
1443 char *out
= NULL
, *outp
;
1445 const char *router_sig
;
1446 const char *ei_body
= signed_descriptor_get_body(ei
);
1447 size_t ri_len
= ri
->signed_descriptor_len
;
1448 size_t ei_len
= ei
->signed_descriptor_len
;
1452 outp
= out
= tor_malloc(ri_len
+ei_len
+1);
1453 if (!(router_sig
= tor_memstr(ri_body
, ri_len
, "\nrouter-signature")))
1456 memcpy(out
, ri_body
, router_sig
-ri_body
);
1457 outp
+= router_sig
-ri_body
;
1459 for (i
=0; i
< 2; ++i
) {
1460 const char *kwd
= i
?"\nwrite-history ":"\nread-history ";
1461 const char *cp
, *eol
;
1462 if (!(cp
= tor_memstr(ei_body
, ei_len
, kwd
)))
1465 eol
= memchr(cp
, '\n', ei_len
- (cp
-ei_body
));
1466 memcpy(outp
, cp
, eol
-cp
+1);
1469 memcpy(outp
, router_sig
, ri_len
- (router_sig
-ri_body
));
1471 tor_assert(outp
-out
< (int)(ri_len
+ei_len
+1));
1476 return tor_strndup(ri_body
, ri
->signed_descriptor_len
);
1479 /** Implementation helper for GETINFO: answers requests for information about
1480 * which ports are bound. */
1482 getinfo_helper_listeners(control_connection_t
*control_conn
,
1483 const char *question
,
1484 char **answer
, const char **errmsg
)
1492 if (!strcmp(question
, "net/listeners/or"))
1493 type
= CONN_TYPE_OR_LISTENER
;
1494 else if (!strcmp(question
, "net/listeners/dir"))
1495 type
= CONN_TYPE_DIR_LISTENER
;
1496 else if (!strcmp(question
, "net/listeners/socks"))
1497 type
= CONN_TYPE_AP_LISTENER
;
1498 else if (!strcmp(question
, "net/listeners/trans"))
1499 type
= CONN_TYPE_AP_TRANS_LISTENER
;
1500 else if (!strcmp(question
, "net/listeners/natd"))
1501 type
= CONN_TYPE_AP_NATD_LISTENER
;
1502 else if (!strcmp(question
, "net/listeners/dns"))
1503 type
= CONN_TYPE_AP_DNS_LISTENER
;
1504 else if (!strcmp(question
, "net/listeners/control"))
1505 type
= CONN_TYPE_CONTROL_LISTENER
;
1507 return 0; /* unknown key */
1509 res
= smartlist_create();
1510 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t
*, conn
) {
1512 struct sockaddr_storage ss
;
1513 socklen_t ss_len
= sizeof(ss
);
1515 if (conn
->type
!= type
|| conn
->marked_for_close
|| conn
->s
< 0)
1518 if (getsockname(conn
->s
, (struct sockaddr
*)&ss
, &ss_len
) < 0) {
1519 tor_asprintf(&addr
, "%s:%d", conn
->address
, (int)conn
->port
);
1521 char *tmp
= tor_sockaddr_to_str((struct sockaddr
*)&ss
);
1522 addr
= esc_for_log(tmp
);
1526 smartlist_add(res
, addr
);
1527 } SMARTLIST_FOREACH_END(conn
);
1529 *answer
= smartlist_join_strings(res
, " ", 0, NULL
);
1531 SMARTLIST_FOREACH(res
, char *, cp
, tor_free(cp
));
1532 smartlist_free(res
);
1536 /** Implementation helper for GETINFO: knows the answers for questions about
1537 * directory information. */
1539 getinfo_helper_dir(control_connection_t
*control_conn
,
1540 const char *question
, char **answer
,
1541 const char **errmsg
)
1543 (void) control_conn
;
1544 if (!strcmpstart(question
, "desc/id/")) {
1545 routerinfo_t
*ri
= router_get_by_hexdigest(question
+strlen("desc/id/"));
1547 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1549 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
1551 } else if (!strcmpstart(question
, "desc/name/")) {
1552 routerinfo_t
*ri
= router_get_by_nickname(question
+strlen("desc/name/"),1);
1554 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1556 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
1558 } else if (!strcmp(question
, "desc/all-recent")) {
1559 routerlist_t
*routerlist
= router_get_routerlist();
1560 smartlist_t
*sl
= smartlist_create();
1561 if (routerlist
&& routerlist
->routers
) {
1562 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
1564 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1567 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
1570 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
1571 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
1573 } else if (!strcmp(question
, "desc/all-recent-extrainfo-hack")) {
1574 /* XXXX Remove this once Torstat asks for extrainfos. */
1575 routerlist_t
*routerlist
= router_get_routerlist();
1576 smartlist_t
*sl
= smartlist_create();
1577 if (routerlist
&& routerlist
->routers
) {
1578 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
1580 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1581 signed_descriptor_t
*ei
= extrainfo_get_by_descriptor_digest(
1582 ri
->cache_info
.extra_info_digest
);
1584 smartlist_add(sl
, munge_extrainfo_into_routerinfo(body
,
1585 &ri
->cache_info
, ei
));
1588 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
1592 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
1593 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
1595 } else if (!strcmpstart(question
, "desc-annotations/id/")) {
1596 routerinfo_t
*ri
= router_get_by_hexdigest(question
+
1597 strlen("desc-annotations/id/"));
1599 const char *annotations
=
1600 signed_descriptor_get_annotations(&ri
->cache_info
);
1602 *answer
= tor_strndup(annotations
,
1603 ri
->cache_info
.annotations_len
);
1605 } else if (!strcmpstart(question
, "dir/server/")) {
1606 size_t answer_len
= 0, url_len
= strlen(question
)+2;
1607 char *url
= tor_malloc(url_len
);
1608 smartlist_t
*descs
= smartlist_create();
1612 tor_snprintf(url
, url_len
, "/tor/%s", question
+4);
1613 res
= dirserv_get_routerdescs(descs
, url
, &msg
);
1615 log_warn(LD_CONTROL
, "getinfo '%s': %s", question
, msg
);
1616 smartlist_free(descs
);
1621 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
1622 answer_len
+= sd
->signed_descriptor_len
);
1623 cp
= *answer
= tor_malloc(answer_len
+1);
1624 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
1626 memcpy(cp
, signed_descriptor_get_body(sd
),
1627 sd
->signed_descriptor_len
);
1628 cp
+= sd
->signed_descriptor_len
;
1632 smartlist_free(descs
);
1633 } else if (!strcmpstart(question
, "dir/status/")) {
1634 if (directory_permits_controller_requests(get_options())) {
1637 smartlist_t
*status_list
= smartlist_create();
1638 dirserv_get_networkstatus_v2(status_list
,
1639 question
+strlen("dir/status/"));
1640 SMARTLIST_FOREACH(status_list
, cached_dir_t
*, d
, len
+= d
->dir_len
);
1641 cp
= *answer
= tor_malloc(len
+1);
1642 SMARTLIST_FOREACH(status_list
, cached_dir_t
*, d
, {
1643 memcpy(cp
, d
->dir
, d
->dir_len
);
1647 smartlist_free(status_list
);
1649 smartlist_t
*fp_list
= smartlist_create();
1650 smartlist_t
*status_list
= smartlist_create();
1651 dirserv_get_networkstatus_v2_fingerprints(
1652 fp_list
, question
+strlen("dir/status/"));
1653 SMARTLIST_FOREACH(fp_list
, const char *, fp
, {
1655 char *fname
= networkstatus_get_cache_filename(fp
);
1656 s
= read_file_to_str(fname
, 0, NULL
);
1658 smartlist_add(status_list
, s
);
1661 SMARTLIST_FOREACH(fp_list
, char *, fp
, tor_free(fp
));
1662 smartlist_free(fp_list
);
1663 *answer
= smartlist_join_strings(status_list
, "", 0, NULL
);
1664 SMARTLIST_FOREACH(status_list
, char *, s
, tor_free(s
));
1665 smartlist_free(status_list
);
1667 } else if (!strcmp(question
, "dir/status-vote/current/consensus")) { /* v3 */
1668 if (directory_caches_dir_info(get_options())) {
1669 const cached_dir_t
*consensus
= dirserv_get_consensus("ns");
1671 *answer
= tor_strdup(consensus
->dir
);
1673 if (!*answer
) { /* try loading it from disk */
1674 char *filename
= get_datadir_fname("cached-consensus");
1675 *answer
= read_file_to_str(filename
, RFTS_IGNORE_MISSING
, NULL
);
1678 } else if (!strcmp(question
, "network-status")) { /* v1 */
1679 routerlist_t
*routerlist
= router_get_routerlist();
1680 if (!routerlist
|| !routerlist
->routers
||
1681 list_server_status_v1(routerlist
->routers
, answer
, 1) < 0) {
1684 } else if (!strcmpstart(question
, "extra-info/digest/")) {
1685 question
+= strlen("extra-info/digest/");
1686 if (strlen(question
) == HEX_DIGEST_LEN
) {
1688 signed_descriptor_t
*sd
= NULL
;
1689 if (base16_decode(d
, sizeof(d
), question
, strlen(question
))==0) {
1690 /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
1691 * but I don't want to risk affecting other parts of the code,
1692 * especially since the rules for using our own extrainfo (including
1693 * when it might be freed) are different from those for using one
1694 * we have downloaded. */
1695 if (router_extrainfo_digest_is_me(d
))
1696 sd
= &(router_get_my_extrainfo()->cache_info
);
1698 sd
= extrainfo_get_by_descriptor_digest(d
);
1701 const char *body
= signed_descriptor_get_body(sd
);
1703 *answer
= tor_strndup(body
, sd
->signed_descriptor_len
);
1711 /** Implementation helper for GETINFO: knows how to generate summaries of the
1712 * current states of things we send events about. */
1714 getinfo_helper_events(control_connection_t
*control_conn
,
1715 const char *question
, char **answer
,
1716 const char **errmsg
)
1718 (void) control_conn
;
1719 if (!strcmp(question
, "circuit-status")) {
1721 smartlist_t
*status
= smartlist_create();
1722 for (circ
= _circuit_get_global_list(); circ
; circ
= circ
->next
) {
1726 const char *purpose
;
1727 if (! CIRCUIT_IS_ORIGIN(circ
) || circ
->marked_for_close
)
1730 path
= circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ
));
1732 if (circ
->state
== CIRCUIT_STATE_OPEN
)
1734 else if (strlen(path
))
1739 purpose
= circuit_purpose_to_controller_string(circ
->purpose
);
1740 slen
= strlen(path
)+strlen(state
)+strlen(purpose
)+30;
1741 s
= tor_malloc(slen
+1);
1742 tor_snprintf(s
, slen
, "%lu %s%s%s PURPOSE=%s",
1743 (unsigned long)TO_ORIGIN_CIRCUIT(circ
)->global_identifier
,
1744 state
, *path
? " " : "", path
, purpose
);
1745 smartlist_add(status
, s
);
1748 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1749 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1750 smartlist_free(status
);
1751 } else if (!strcmp(question
, "stream-status")) {
1752 smartlist_t
*conns
= get_connection_array();
1753 smartlist_t
*status
= smartlist_create();
1755 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
1757 edge_connection_t
*conn
;
1761 origin_circuit_t
*origin_circ
= NULL
;
1762 if (base_conn
->type
!= CONN_TYPE_AP
||
1763 base_conn
->marked_for_close
||
1764 base_conn
->state
== AP_CONN_STATE_SOCKS_WAIT
||
1765 base_conn
->state
== AP_CONN_STATE_NATD_WAIT
)
1767 conn
= TO_EDGE_CONN(base_conn
);
1768 switch (conn
->_base
.state
)
1770 case AP_CONN_STATE_CONTROLLER_WAIT
:
1771 case AP_CONN_STATE_CIRCUIT_WAIT
:
1772 if (conn
->socks_request
&&
1773 SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
))
1774 state
= "NEWRESOLVE";
1778 case AP_CONN_STATE_RENDDESC_WAIT
:
1779 case AP_CONN_STATE_CONNECT_WAIT
:
1780 state
= "SENTCONNECT"; break;
1781 case AP_CONN_STATE_RESOLVE_WAIT
:
1782 state
= "SENTRESOLVE"; break;
1783 case AP_CONN_STATE_OPEN
:
1784 state
= "SUCCEEDED"; break;
1786 log_warn(LD_BUG
, "Asked for stream in unknown state %d",
1790 circ
= circuit_get_by_edge_conn(conn
);
1791 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
1792 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
1793 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
1794 slen
= strlen(buf
)+strlen(state
)+32;
1795 s
= tor_malloc(slen
+1);
1796 tor_snprintf(s
, slen
, "%lu %s %lu %s",
1797 (unsigned long) conn
->_base
.global_identifier
,state
,
1799 (unsigned long)origin_circ
->global_identifier
: 0ul,
1801 smartlist_add(status
, s
);
1802 } SMARTLIST_FOREACH_END(base_conn
);
1803 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1804 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1805 smartlist_free(status
);
1806 } else if (!strcmp(question
, "orconn-status")) {
1807 smartlist_t
*conns
= get_connection_array();
1808 smartlist_t
*status
= smartlist_create();
1809 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
1814 or_connection_t
*conn
;
1815 if (base_conn
->type
!= CONN_TYPE_OR
|| base_conn
->marked_for_close
)
1817 conn
= TO_OR_CONN(base_conn
);
1818 if (conn
->_base
.state
== OR_CONN_STATE_OPEN
)
1819 state
= "CONNECTED";
1820 else if (conn
->nickname
)
1824 orconn_target_get_name(name
, sizeof(name
), conn
);
1825 slen
= strlen(name
)+strlen(state
)+2;
1826 s
= tor_malloc(slen
+1);
1827 tor_snprintf(s
, slen
, "%s %s", name
, state
);
1828 smartlist_add(status
, s
);
1829 } SMARTLIST_FOREACH_END(base_conn
);
1830 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1831 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1832 smartlist_free(status
);
1833 } else if (!strcmpstart(question
, "address-mappings/")) {
1834 time_t min_e
, max_e
;
1835 smartlist_t
*mappings
;
1836 question
+= strlen("address-mappings/");
1837 if (!strcmp(question
, "all")) {
1838 min_e
= 0; max_e
= TIME_MAX
;
1839 } else if (!strcmp(question
, "cache")) {
1840 min_e
= 2; max_e
= TIME_MAX
;
1841 } else if (!strcmp(question
, "config")) {
1842 min_e
= 0; max_e
= 0;
1843 } else if (!strcmp(question
, "control")) {
1844 min_e
= 1; max_e
= 1;
1848 mappings
= smartlist_create();
1849 addressmap_get_mappings(mappings
, min_e
, max_e
, 1);
1850 *answer
= smartlist_join_strings(mappings
, "\r\n", 0, NULL
);
1851 SMARTLIST_FOREACH(mappings
, char *, cp
, tor_free(cp
));
1852 smartlist_free(mappings
);
1853 } else if (!strcmpstart(question
, "status/")) {
1854 /* Note that status/ is not a catch-all for events; there's only supposed
1855 * to be a status GETINFO if there's a corresponding STATUS event. */
1856 if (!strcmp(question
, "status/circuit-established")) {
1857 *answer
= tor_strdup(can_complete_circuit
? "1" : "0");
1858 } else if (!strcmp(question
, "status/enough-dir-info")) {
1859 *answer
= tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
1860 } else if (!strcmp(question
, "status/good-server-descriptor") ||
1861 !strcmp(question
, "status/accepted-server-descriptor")) {
1862 /* They're equivalent for now, until we can figure out how to make
1863 * good-server-descriptor be what we want. See comment in
1864 * control-spec.txt. */
1865 *answer
= tor_strdup(directories_have_accepted_server_descriptor()
1867 } else if (!strcmp(question
, "status/reachability-succeeded/or")) {
1868 *answer
= tor_strdup(check_whether_orport_reachable() ? "1" : "0");
1869 } else if (!strcmp(question
, "status/reachability-succeeded/dir")) {
1870 *answer
= tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
1871 } else if (!strcmp(question
, "status/reachability-succeeded")) {
1872 *answer
= tor_malloc(16);
1873 tor_snprintf(*answer
, 16, "OR=%d DIR=%d",
1874 check_whether_orport_reachable() ? 1 : 0,
1875 check_whether_dirport_reachable() ? 1 : 0);
1876 } else if (!strcmp(question
, "status/bootstrap-phase")) {
1877 *answer
= tor_strdup(last_sent_bootstrap_message
);
1878 } else if (!strcmpstart(question
, "status/version/")) {
1879 int is_server
= server_mode(get_options());
1880 networkstatus_t
*c
= networkstatus_get_latest_consensus();
1881 version_status_t status
;
1882 const char *recommended
;
1884 recommended
= is_server
? c
->server_versions
: c
->client_versions
;
1885 status
= tor_version_is_obsolete(VERSION
, recommended
);
1888 status
= VS_UNKNOWN
;
1891 if (!strcmp(question
, "status/version/recommended")) {
1892 *answer
= tor_strdup(recommended
);
1895 if (!strcmp(question
, "status/version/current")) {
1898 case VS_RECOMMENDED
: *answer
= tor_strdup("recommended"); break;
1899 case VS_OLD
: *answer
= tor_strdup("obsolete"); break;
1900 case VS_NEW
: *answer
= tor_strdup("new"); break;
1901 case VS_NEW_IN_SERIES
: *answer
= tor_strdup("new in series"); break;
1902 case VS_UNRECOMMENDED
: *answer
= tor_strdup("unrecommended"); break;
1903 case VS_EMPTY
: *answer
= tor_strdup("none recommended"); break;
1904 case VS_UNKNOWN
: *answer
= tor_strdup("unknown"); break;
1905 default: tor_fragile_assert();
1907 } else if (!strcmp(question
, "status/version/num-versioning") ||
1908 !strcmp(question
, "status/version/num-concurring")) {
1910 tor_snprintf(s
, sizeof(s
), "%d", get_n_authorities(V3_AUTHORITY
));
1911 *answer
= tor_strdup(s
);
1912 log_warn(LD_GENERAL
, "%s is deprecated; it no longer gives useful "
1913 "information", question
);
1915 } else if (!strcmp(question
, "status/clients-seen")) {
1916 char *bridge_stats
= geoip_get_bridge_stats_controller(time(NULL
));
1917 if (!bridge_stats
) {
1918 *errmsg
= "No bridge-client stats available";
1921 *answer
= bridge_stats
;
1929 /** Callback function for GETINFO: on a given control connection, try to
1930 * answer the question <b>q</b> and store the newly-allocated answer in
1931 * *<b>a</b>. If an internal error occurs, return -1 and optionally set
1932 * *<b>error_out</b> to point to an error message to be delivered to the
1933 * controller. On success, _or if the key is not recognized_, return 0. Do not
1934 * set <b>a</b> if the key is not recognized.
1936 typedef int (*getinfo_helper_t
)(control_connection_t
*,
1937 const char *q
, char **a
,
1938 const char **error_out
);
1940 /** A single item for the GETINFO question-to-answer-function table. */
1941 typedef struct getinfo_item_t
{
1942 const char *varname
; /**< The value (or prefix) of the question. */
1943 getinfo_helper_t fn
; /**< The function that knows the answer: NULL if
1944 * this entry is documentation-only. */
1945 const char *desc
; /**< Description of the variable. */
1946 int is_prefix
; /** Must varname match exactly, or must it be a prefix? */
1949 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
1950 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
1951 #define DOC(name, desc) { name, NULL, desc, 0 }
1953 /** Table mapping questions accepted by GETINFO to the functions that know how
1954 * to answer them. */
1955 static const getinfo_item_t getinfo_items
[] = {
1956 ITEM("version", misc
, "The current version of Tor."),
1957 ITEM("config-file", misc
, "Current location of the \"torrc\" file."),
1958 ITEM("config-text", misc
,
1959 "Return the string that would be written by a saveconf command."),
1960 ITEM("accounting/bytes", accounting
,
1961 "Number of bytes read/written so far in the accounting interval."),
1962 ITEM("accounting/bytes-left", accounting
,
1963 "Number of bytes left to write/read so far in the accounting interval."),
1964 ITEM("accounting/enabled", accounting
, "Is accounting currently enabled?"),
1965 ITEM("accounting/hibernating", accounting
, "Are we hibernating or awake?"),
1966 ITEM("accounting/interval-start", accounting
,
1967 "Time when the accounting period starts."),
1968 ITEM("accounting/interval-end", accounting
,
1969 "Time when the accounting period ends."),
1970 ITEM("accounting/interval-wake", accounting
,
1971 "Time to wake up in this accounting period."),
1972 ITEM("helper-nodes", entry_guards
, NULL
), /* deprecated */
1973 ITEM("entry-guards", entry_guards
,
1974 "Which nodes are we using as entry guards?"),
1975 ITEM("fingerprint", misc
, NULL
),
1976 PREFIX("config/", config
, "Current configuration values."),
1978 "List of configuration options, types, and documentation."),
1979 ITEM("info/names", misc
,
1980 "List of GETINFO options, types, and documentation."),
1981 ITEM("events/names", misc
,
1982 "Events that the controller can ask for with SETEVENTS."),
1983 ITEM("features/names", misc
, "What arguments can USEFEATURE take?"),
1984 PREFIX("desc/id/", dir
, "Router descriptors by ID."),
1985 PREFIX("desc/name/", dir
, "Router descriptors by nickname."),
1986 ITEM("desc/all-recent", dir
,
1987 "All non-expired, non-superseded router descriptors."),
1988 ITEM("desc/all-recent-extrainfo-hack", dir
, NULL
), /* Hack. */
1989 PREFIX("extra-info/digest/", dir
, "Extra-info documents by digest."),
1990 PREFIX("net/listeners/", listeners
, "Bound addresses by type"),
1991 ITEM("ns/all", networkstatus
,
1992 "Brief summary of router status (v2 directory format)"),
1993 PREFIX("ns/id/", networkstatus
,
1994 "Brief summary of router status by ID (v2 directory format)."),
1995 PREFIX("ns/name/", networkstatus
,
1996 "Brief summary of router status by nickname (v2 directory format)."),
1997 PREFIX("ns/purpose/", networkstatus
,
1998 "Brief summary of router status by purpose (v2 directory format)."),
2000 ITEM("network-status", dir
,
2001 "Brief summary of router status (v1 directory format)"),
2002 ITEM("circuit-status", events
, "List of current circuits originating here."),
2003 ITEM("stream-status", events
,"List of current streams."),
2004 ITEM("orconn-status", events
, "A list of current OR connections."),
2005 PREFIX("address-mappings/", events
, NULL
),
2006 DOC("address-mappings/all", "Current address mappings."),
2007 DOC("address-mappings/cache", "Current cached DNS replies."),
2008 DOC("address-mappings/config",
2009 "Current address mappings from configuration."),
2010 DOC("address-mappings/control", "Current address mappings from controller."),
2011 PREFIX("status/", events
, NULL
),
2012 DOC("status/circuit-established",
2013 "Whether we think client functionality is working."),
2014 DOC("status/enough-dir-info",
2015 "Whether we have enough up-to-date directory information to build "
2017 DOC("status/bootstrap-phase",
2018 "The last bootstrap phase status event that Tor sent."),
2019 DOC("status/clients-seen",
2020 "Breakdown of client countries seen by a bridge."),
2021 DOC("status/version/recommended", "List of currently recommended versions."),
2022 DOC("status/version/current", "Status of the current version."),
2023 DOC("status/version/num-versioning", "Number of versioning authorities."),
2024 DOC("status/version/num-concurring",
2025 "Number of versioning authorities agreeing on the status of the "
2027 ITEM("address", misc
, "IP address of this Tor host, if we can guess it."),
2028 ITEM("dir-usage", misc
, "Breakdown of bytes transferred over DirPort."),
2029 PREFIX("desc-annotations/id/", dir
, "Router annotations by hexdigest."),
2030 PREFIX("dir/server/", dir
,"Router descriptors as retrieved from a DirPort."),
2031 PREFIX("dir/status/", dir
,
2032 "v2 networkstatus docs as retrieved from a DirPort."),
2033 ITEM("dir/status-vote/current/consensus", dir
,
2034 "v3 Networkstatus consensus as retrieved from a DirPort."),
2035 ITEM("exit-policy/default", policies
,
2036 "The default value appended to the configured exit policy."),
2037 PREFIX("ip-to-country/", geoip
, "Perform a GEOIP lookup"),
2038 { NULL
, NULL
, NULL
, 0 }
2041 /** Allocate and return a list of recognized GETINFO options. */
2043 list_getinfo_options(void)
2047 smartlist_t
*lines
= smartlist_create();
2049 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
2050 if (!getinfo_items
[i
].desc
)
2053 tor_asprintf(&buf
, "%s%s -- %s\n",
2054 getinfo_items
[i
].varname
,
2055 getinfo_items
[i
].is_prefix
? "*" : "",
2056 getinfo_items
[i
].desc
);
2057 smartlist_add(lines
, buf
);
2059 smartlist_sort_strings(lines
);
2061 ans
= smartlist_join_strings(lines
, "", 0, NULL
);
2062 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
2063 smartlist_free(lines
);
2068 /** Lookup the 'getinfo' entry <b>question</b>, and return
2069 * the answer in <b>*answer</b> (or NULL if key not recognized).
2070 * Return 0 if success or unrecognized, or -1 if recognized but
2071 * internal error. */
2073 handle_getinfo_helper(control_connection_t
*control_conn
,
2074 const char *question
, char **answer
,
2075 const char **err_out
)
2078 *answer
= NULL
; /* unrecognized key by default */
2080 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
2082 if (getinfo_items
[i
].is_prefix
)
2083 match
= !strcmpstart(question
, getinfo_items
[i
].varname
);
2085 match
= !strcmp(question
, getinfo_items
[i
].varname
);
2087 tor_assert(getinfo_items
[i
].fn
);
2088 return getinfo_items
[i
].fn(control_conn
, question
, answer
, err_out
);
2092 return 0; /* unrecognized */
2095 /** Called when we receive a GETINFO command. Try to fetch all requested
2096 * information, and reply with information or error message. */
2098 handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
2101 smartlist_t
*questions
= smartlist_create();
2102 smartlist_t
*answers
= smartlist_create();
2103 smartlist_t
*unrecognized
= smartlist_create();
2104 char *msg
= NULL
, *ans
= NULL
;
2106 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
2108 smartlist_split_string(questions
, body
, " ",
2109 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2110 SMARTLIST_FOREACH_BEGIN(questions
, const char *, q
) {
2111 const char *errmsg
= NULL
;
2112 if (handle_getinfo_helper(conn
, q
, &ans
, &errmsg
) < 0) {
2114 errmsg
= "Internal error";
2115 connection_printf_to_buf(conn
, "551 %s\r\n", errmsg
);
2119 smartlist_add(unrecognized
, (char*)q
);
2121 smartlist_add(answers
, tor_strdup(q
));
2122 smartlist_add(answers
, ans
);
2124 } SMARTLIST_FOREACH_END(q
);
2125 if (smartlist_len(unrecognized
)) {
2126 for (i
=0; i
< smartlist_len(unrecognized
)-1; ++i
)
2127 connection_printf_to_buf(conn
,
2128 "552-Unrecognized key \"%s\"\r\n",
2129 (char*)smartlist_get(unrecognized
, i
));
2130 connection_printf_to_buf(conn
,
2131 "552 Unrecognized key \"%s\"\r\n",
2132 (char*)smartlist_get(unrecognized
, i
));
2136 for (i
= 0; i
< smartlist_len(answers
); i
+= 2) {
2137 char *k
= smartlist_get(answers
, i
);
2138 char *v
= smartlist_get(answers
, i
+1);
2139 if (!strchr(v
, '\n') && !strchr(v
, '\r')) {
2140 connection_printf_to_buf(conn
, "250-%s=", k
);
2141 connection_write_str_to_buf(v
, conn
);
2142 connection_write_str_to_buf("\r\n", conn
);
2146 esc_len
= write_escaped_data(v
, strlen(v
), &esc
);
2147 connection_printf_to_buf(conn
, "250+%s=\r\n", k
);
2148 connection_write_to_buf(esc
, esc_len
, TO_CONN(conn
));
2152 connection_write_str_to_buf("250 OK\r\n", conn
);
2155 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
2156 smartlist_free(answers
);
2157 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
2158 smartlist_free(questions
);
2159 smartlist_free(unrecognized
);
2165 /** Given a string, convert it to a circuit purpose. */
2167 circuit_purpose_from_string(const char *string
)
2169 if (!strcasecmpstart(string
, "purpose="))
2170 string
+= strlen("purpose=");
2172 if (!strcasecmp(string
, "general"))
2173 return CIRCUIT_PURPOSE_C_GENERAL
;
2174 else if (!strcasecmp(string
, "controller"))
2175 return CIRCUIT_PURPOSE_CONTROLLER
;
2177 return CIRCUIT_PURPOSE_UNKNOWN
;
2180 /** Return a newly allocated smartlist containing the arguments to the command
2181 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
2182 * or if <b>max_args</b> is nonnegative and there are more than
2183 * <b>max_args</b> arguments, send a 512 error to the controller, using
2184 * <b>command</b> as the command name in the error message. */
2185 static smartlist_t
*
2186 getargs_helper(const char *command
, control_connection_t
*conn
,
2187 const char *body
, int min_args
, int max_args
)
2189 smartlist_t
*args
= smartlist_create();
2190 smartlist_split_string(args
, body
, " ",
2191 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2192 if (smartlist_len(args
) < min_args
) {
2193 connection_printf_to_buf(conn
, "512 Missing argument to %s\r\n",command
);
2195 } else if (max_args
>= 0 && smartlist_len(args
) > max_args
) {
2196 connection_printf_to_buf(conn
, "512 Too many arguments to %s\r\n",command
);
2201 SMARTLIST_FOREACH(args
, char *, s
, tor_free(s
));
2202 smartlist_free(args
);
2206 /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
2207 * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
2208 * such element exists. */
2210 find_element_starting_with(smartlist_t
*sl
, int start_at
, const char *prefix
)
2213 for (i
= start_at
; i
< smartlist_len(sl
); ++i
) {
2214 const char *elt
= smartlist_get(sl
, i
);
2215 if (!strcasecmpstart(elt
, prefix
))
2221 /** Helper. Return true iff s is an argument that we should treat as a
2222 * key-value pair. */
2224 is_keyval_pair(const char *s
)
2226 /* An argument is a key-value pair if it has an =, and it isn't of the form
2227 * $fingeprint=name */
2228 return strchr(s
, '=') && s
[0] != '$';
2231 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
2232 * circuit, and report success or failure. */
2234 handle_control_extendcircuit(control_connection_t
*conn
, uint32_t len
,
2237 smartlist_t
*router_nicknames
=NULL
, *routers
=NULL
;
2238 origin_circuit_t
*circ
= NULL
;
2240 uint8_t intended_purpose
= CIRCUIT_PURPOSE_C_GENERAL
;
2244 router_nicknames
= smartlist_create();
2246 args
= getargs_helper("EXTENDCIRCUIT", conn
, body
, 1, -1);
2250 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,0));
2253 const char *purp
= find_element_starting_with(args
, 1, "PURPOSE=");
2256 intended_purpose
= circuit_purpose_from_string(purp
);
2257 if (intended_purpose
== CIRCUIT_PURPOSE_UNKNOWN
) {
2258 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
2259 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2260 smartlist_free(args
);
2265 if ((smartlist_len(args
) == 1) ||
2266 (smartlist_len(args
) >= 2 && is_keyval_pair(smartlist_get(args
, 1)))) {
2267 // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
2268 circ
= circuit_launch_by_router(intended_purpose
, NULL
,
2269 CIRCLAUNCH_NEED_CAPACITY
);
2271 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
2273 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
2274 (unsigned long)circ
->global_identifier
);
2276 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2277 smartlist_free(args
);
2280 // "EXTENDCIRCUIT 0 router1,router2" ||
2281 // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
2284 if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
,0)))) {
2285 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2286 (char*)smartlist_get(args
, 0));
2287 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2288 smartlist_free(args
);
2292 smartlist_split_string(router_nicknames
, smartlist_get(args
,1), ",", 0, 0);
2294 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2295 smartlist_free(args
);
2297 routers
= smartlist_create();
2298 SMARTLIST_FOREACH(router_nicknames
, const char *, n
,
2300 routerinfo_t
*r
= router_get_by_nickname(n
, 1);
2302 connection_printf_to_buf(conn
, "552 No such router \"%s\"\r\n", n
);
2305 smartlist_add(routers
, r
);
2307 if (!smartlist_len(routers
)) {
2308 connection_write_str_to_buf("512 No router names provided\r\n", conn
);
2313 /* start a new circuit */
2314 circ
= origin_circuit_init(intended_purpose
, 0);
2317 /* now circ refers to something that is ready to be extended */
2318 SMARTLIST_FOREACH(routers
, routerinfo_t
*, r
,
2320 extend_info_t
*info
= extend_info_from_router(r
);
2321 circuit_append_new_exit(circ
, info
);
2322 extend_info_free(info
);
2325 /* now that we've populated the cpath, start extending */
2328 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
2329 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
2330 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
2334 if (circ
->_base
.state
== CIRCUIT_STATE_OPEN
) {
2336 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
2337 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
2338 log_info(LD_CONTROL
,
2339 "send_next_onion_skin failed; circuit marked for closing.");
2340 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
2341 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn
);
2347 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
2348 (unsigned long)circ
->global_identifier
);
2349 if (zero_circ
) /* send a 'launched' event, for completeness */
2350 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
2352 SMARTLIST_FOREACH(router_nicknames
, char *, n
, tor_free(n
));
2353 smartlist_free(router_nicknames
);
2354 smartlist_free(routers
);
2358 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
2359 * circuit and it's a valid purpose, change it. */
2361 handle_control_setcircuitpurpose(control_connection_t
*conn
,
2362 uint32_t len
, const char *body
)
2364 origin_circuit_t
*circ
= NULL
;
2365 uint8_t new_purpose
;
2367 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
2369 args
= getargs_helper("SETCIRCUITPURPOSE", conn
, body
, 2, -1);
2373 if (!(circ
= get_circ(smartlist_get(args
,0)))) {
2374 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2375 (char*)smartlist_get(args
, 0));
2380 const char *purp
= find_element_starting_with(args
,1,"PURPOSE=");
2381 new_purpose
= circuit_purpose_from_string(purp
);
2382 if (new_purpose
== CIRCUIT_PURPOSE_UNKNOWN
) {
2383 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
2388 circ
->_base
.purpose
= new_purpose
;
2389 connection_write_str_to_buf("250 OK\r\n", conn
);
2393 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2394 smartlist_free(args
);
2399 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
2400 * stream, and report success or failure. */
2402 handle_control_attachstream(control_connection_t
*conn
, uint32_t len
,
2405 edge_connection_t
*ap_conn
= NULL
;
2406 origin_circuit_t
*circ
= NULL
;
2409 crypt_path_t
*cpath
=NULL
;
2410 int hop
=0, hop_line_ok
=1;
2413 args
= getargs_helper("ATTACHSTREAM", conn
, body
, 2, -1);
2417 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,1));
2419 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))) {
2420 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2421 (char*)smartlist_get(args
, 0));
2422 } else if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
, 1)))) {
2423 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2424 (char*)smartlist_get(args
, 1));
2426 const char *hopstring
= find_element_starting_with(args
,2,"HOP=");
2428 hopstring
+= strlen("HOP=");
2429 hop
= (int) tor_parse_ulong(hopstring
, 10, 0, INT_MAX
,
2430 &hop_line_ok
, NULL
);
2431 if (!hop_line_ok
) { /* broken hop line */
2432 connection_printf_to_buf(conn
, "552 Bad value hop=%s\r\n", hopstring
);
2436 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2437 smartlist_free(args
);
2438 if (!ap_conn
|| (!zero_circ
&& !circ
) || !hop_line_ok
)
2441 if (ap_conn
->_base
.state
!= AP_CONN_STATE_CONTROLLER_WAIT
&&
2442 ap_conn
->_base
.state
!= AP_CONN_STATE_CONNECT_WAIT
&&
2443 ap_conn
->_base
.state
!= AP_CONN_STATE_RESOLVE_WAIT
) {
2444 connection_write_str_to_buf(
2445 "555 Connection is not managed by controller.\r\n",
2450 /* Do we need to detach it first? */
2451 if (ap_conn
->_base
.state
!= AP_CONN_STATE_CONTROLLER_WAIT
) {
2452 circuit_t
*tmpcirc
= circuit_get_by_edge_conn(ap_conn
);
2453 connection_edge_end(ap_conn
, END_STREAM_REASON_TIMEOUT
);
2454 /* Un-mark it as ending, since we're going to reuse it. */
2455 ap_conn
->edge_has_sent_end
= 0;
2456 ap_conn
->end_reason
= 0;
2458 circuit_detach_stream(tmpcirc
,ap_conn
);
2459 ap_conn
->_base
.state
= AP_CONN_STATE_CONTROLLER_WAIT
;
2462 if (circ
&& (circ
->_base
.state
!= CIRCUIT_STATE_OPEN
)) {
2463 connection_write_str_to_buf(
2464 "551 Can't attach stream to non-open origin circuit\r\n",
2468 /* Is this a single hop circuit? */
2469 if (circ
&& (circuit_get_cpath_len(circ
)<2 || hop
==1)) {
2470 routerinfo_t
*r
= NULL
;
2472 if (circ
->build_state
&&
2473 circ
->build_state
->chosen_exit
&&
2474 !tor_digest_is_zero(circ
->build_state
->chosen_exit
->identity_digest
)) {
2475 exit_digest
= circ
->build_state
->chosen_exit
->identity_digest
;
2476 r
= router_get_by_digest(exit_digest
);
2478 /* Do both the client and relay allow one-hop exit circuits? */
2479 if (!r
|| !r
->allow_single_hop_exits
||
2480 !get_options()->AllowSingleHopCircuits
) {
2481 connection_write_str_to_buf(
2482 "551 Can't attach stream to this one-hop circuit.\r\n", conn
);
2485 ap_conn
->chosen_exit_name
= tor_strdup(hex_str(exit_digest
, DIGEST_LEN
));
2488 if (circ
&& hop
>0) {
2489 /* find this hop in the circuit, and set cpath */
2490 cpath
= circuit_get_cpath_hop(circ
, hop
);
2492 connection_printf_to_buf(conn
,
2493 "551 Circuit doesn't have %d hops.\r\n", hop
);
2497 if (connection_ap_handshake_rewrite_and_attach(ap_conn
, circ
, cpath
) < 0) {
2498 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn
);
2501 send_control_done(conn
);
2505 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
2506 * descriptor, and report success or failure. */
2508 handle_control_postdescriptor(control_connection_t
*conn
, uint32_t len
,
2512 const char *msg
=NULL
;
2513 uint8_t purpose
= ROUTER_PURPOSE_GENERAL
;
2514 int cache
= 0; /* eventually, we may switch this to 1 */
2516 char *cp
= memchr(body
, '\n', len
);
2517 smartlist_t
*args
= smartlist_create();
2521 smartlist_split_string(args
, body
, " ",
2522 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2523 SMARTLIST_FOREACH(args
, char *, option
,
2525 if (!strcasecmpstart(option
, "purpose=")) {
2526 option
+= strlen("purpose=");
2527 purpose
= router_purpose_from_string(option
);
2528 if (purpose
== ROUTER_PURPOSE_UNKNOWN
) {
2529 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n",
2533 } else if (!strcasecmpstart(option
, "cache=")) {
2534 option
+= strlen("cache=");
2535 if (!strcasecmp(option
, "no"))
2537 else if (!strcasecmp(option
, "yes"))
2540 connection_printf_to_buf(conn
, "552 Unknown cache request \"%s\"\r\n",
2544 } else { /* unrecognized argument? */
2545 connection_printf_to_buf(conn
,
2546 "512 Unexpected argument \"%s\" to postdescriptor\r\n", option
);
2551 read_escaped_data(cp
, len
-(cp
-body
), &desc
);
2553 switch (router_load_single_router(desc
, purpose
, cache
, &msg
)) {
2555 if (!msg
) msg
= "Could not parse descriptor";
2556 connection_printf_to_buf(conn
, "554 %s\r\n", msg
);
2559 if (!msg
) msg
= "Descriptor not added";
2560 connection_printf_to_buf(conn
, "251 %s\r\n",msg
);
2563 send_control_done(conn
);
2569 SMARTLIST_FOREACH(args
, char *, arg
, tor_free(arg
));
2570 smartlist_free(args
);
2574 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
2575 * address of the named AP stream, and report success or failure. */
2577 handle_control_redirectstream(control_connection_t
*conn
, uint32_t len
,
2580 edge_connection_t
*ap_conn
= NULL
;
2581 char *new_addr
= NULL
;
2582 uint16_t new_port
= 0;
2586 args
= getargs_helper("REDIRECTSTREAM", conn
, body
, 2, -1);
2590 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))
2591 || !ap_conn
->socks_request
) {
2592 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2593 (char*)smartlist_get(args
, 0));
2596 if (smartlist_len(args
) > 2) { /* they included a port too */
2597 new_port
= (uint16_t) tor_parse_ulong(smartlist_get(args
, 2),
2598 10, 1, 65535, &ok
, NULL
);
2601 connection_printf_to_buf(conn
, "512 Cannot parse port \"%s\"\r\n",
2602 (char*)smartlist_get(args
, 2));
2604 new_addr
= tor_strdup(smartlist_get(args
, 1));
2608 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2609 smartlist_free(args
);
2613 strlcpy(ap_conn
->socks_request
->address
, new_addr
,
2614 sizeof(ap_conn
->socks_request
->address
));
2616 ap_conn
->socks_request
->port
= new_port
;
2618 send_control_done(conn
);
2622 /** Called when we get a CLOSESTREAM command; try to close the named stream
2623 * and report success or failure. */
2625 handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
2628 edge_connection_t
*ap_conn
=NULL
;
2634 args
= getargs_helper("CLOSESTREAM", conn
, body
, 2, -1);
2638 else if (!(ap_conn
= get_stream(smartlist_get(args
, 0))))
2639 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2640 (char*)smartlist_get(args
, 0));
2642 reason
= (uint8_t) tor_parse_ulong(smartlist_get(args
,1), 10, 0, 255,
2645 connection_printf_to_buf(conn
, "552 Unrecognized reason \"%s\"\r\n",
2646 (char*)smartlist_get(args
, 1));
2650 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2651 smartlist_free(args
);
2655 connection_mark_unattached_ap(ap_conn
, reason
);
2656 send_control_done(conn
);
2660 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
2661 * and report success or failure. */
2663 handle_control_closecircuit(control_connection_t
*conn
, uint32_t len
,
2666 origin_circuit_t
*circ
= NULL
;
2671 args
= getargs_helper("CLOSECIRCUIT", conn
, body
, 1, -1);
2675 if (!(circ
=get_circ(smartlist_get(args
, 0))))
2676 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2677 (char*)smartlist_get(args
, 0));
2680 for (i
=1; i
< smartlist_len(args
); ++i
) {
2681 if (!strcasecmp(smartlist_get(args
, i
), "IfUnused"))
2684 log_info(LD_CONTROL
, "Skipping unknown option %s",
2685 (char*)smartlist_get(args
,i
));
2688 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2689 smartlist_free(args
);
2693 if (!safe
|| !circ
->p_streams
) {
2694 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_REQUESTED
);
2697 send_control_done(conn
);
2701 /** Called when we get a RESOLVE command: start trying to resolve
2702 * the listed addresses. */
2704 handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
2707 smartlist_t
*args
, *failed
;
2709 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
2711 if (!(conn
->event_mask
& ((uint32_t)1L<<EVENT_ADDRMAP
))) {
2712 log_warn(LD_CONTROL
, "Controller asked us to resolve an address, but "
2713 "isn't listening for ADDRMAP events. It probably won't see "
2716 args
= smartlist_create();
2717 smartlist_split_string(args
, body
, " ",
2718 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2720 const char *modearg
= find_element_starting_with(args
, 0, "mode=");
2721 if (modearg
&& !strcasecmp(modearg
, "mode=reverse"))
2724 failed
= smartlist_create();
2725 SMARTLIST_FOREACH(args
, const char *, arg
, {
2726 if (!is_keyval_pair(arg
)) {
2727 if (dnsserv_launch_request(arg
, is_reverse
)<0)
2728 smartlist_add(failed
, (char*)arg
);
2732 send_control_done(conn
);
2733 SMARTLIST_FOREACH(failed
, const char *, arg
, {
2734 control_event_address_mapped(arg
, arg
, time(NULL
),
2735 "Unable to launch resolve request");
2738 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2739 smartlist_free(args
);
2740 smartlist_free(failed
);
2744 /** Called when we get a PROTOCOLINFO command: send back a reply. */
2746 handle_control_protocolinfo(control_connection_t
*conn
, uint32_t len
,
2749 const char *bad_arg
= NULL
;
2753 conn
->have_sent_protocolinfo
= 1;
2754 args
= smartlist_create();
2755 smartlist_split_string(args
, body
, " ",
2756 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2757 SMARTLIST_FOREACH(args
, const char *, arg
, {
2759 tor_parse_long(arg
, 10, 0, LONG_MAX
, &ok
, NULL
);
2766 connection_printf_to_buf(conn
, "513 No such version %s\r\n",
2768 /* Don't tolerate bad arguments when not authenticated. */
2769 if (!STATE_IS_OPEN(TO_CONN(conn
)->state
))
2770 connection_mark_for_close(TO_CONN(conn
));
2773 or_options_t
*options
= get_options();
2774 int cookies
= options
->CookieAuthentication
;
2775 char *cfile
= get_cookie_file();
2776 char *esc_cfile
= esc_for_log(cfile
);
2779 int passwd
= (options
->HashedControlPassword
!= NULL
||
2780 options
->HashedControlSessionPassword
!= NULL
);
2781 smartlist_t
*mlist
= smartlist_create();
2783 smartlist_add(mlist
, (char*)"COOKIE");
2785 smartlist_add(mlist
, (char*)"HASHEDPASSWORD");
2786 if (!cookies
&& !passwd
)
2787 smartlist_add(mlist
, (char*)"NULL");
2788 methods
= smartlist_join_strings(mlist
, ",", 0, NULL
);
2789 smartlist_free(mlist
);
2792 connection_printf_to_buf(conn
,
2793 "250-PROTOCOLINFO 1\r\n"
2794 "250-AUTH METHODS=%s%s%s\r\n"
2795 "250-VERSION Tor=%s\r\n"
2798 cookies
?" COOKIEFILE=":"",
2799 cookies
?esc_cfile
:"",
2803 tor_free(esc_cfile
);
2806 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2807 smartlist_free(args
);
2811 /** Called when we get a USEFEATURE command: parse the feature list, and
2812 * set up the control_connection's options properly. */
2814 handle_control_usefeature(control_connection_t
*conn
,
2820 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
2821 args
= smartlist_create();
2822 smartlist_split_string(args
, body
, " ",
2823 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2824 SMARTLIST_FOREACH(args
, const char *, arg
, {
2825 if (!strcasecmp(arg
, "VERBOSE_NAMES"))
2827 else if (!strcasecmp(arg
, "EXTENDED_EVENTS"))
2830 connection_printf_to_buf(conn
, "552 Unrecognized feature \"%s\"\r\n",
2838 send_control_done(conn
);
2841 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2842 smartlist_free(args
);
2846 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
2848 connection_control_finished_flushing(control_connection_t
*conn
)
2852 connection_stop_writing(TO_CONN(conn
));
2856 /** Called when <b>conn</b> has gotten its socket closed. */
2858 connection_control_reached_eof(control_connection_t
*conn
)
2862 log_info(LD_CONTROL
,"Control connection reached EOF. Closing.");
2863 connection_mark_for_close(TO_CONN(conn
));
2867 /** Shut down this Tor instance in the same way that SIGINT would, but
2868 * with a log message appropriate for the loss of an owning controller. */
2870 lost_owning_controller(const char *owner_type
, const char *loss_manner
)
2872 int shutdown_slowly
= server_mode(get_options());
2874 log_notice(LD_CONTROL
, "Owning controller %s has %s -- %s.",
2875 owner_type
, loss_manner
,
2876 shutdown_slowly
? "shutting down" : "exiting now");
2878 /* XXXX Perhaps this chunk of code should be a separate function,
2879 * called here and by process_signal(SIGINT). */
2881 if (!shutdown_slowly
) {
2885 /* XXXX This will close all listening sockets except control-port
2886 * listeners. Perhaps we should close those too. */
2887 hibernate_begin_shutdown();
2890 /** Called when <b>conn</b> is being freed. */
2892 connection_control_closed(control_connection_t
*conn
)
2896 conn
->event_mask
= 0;
2897 control_update_global_event_mask();
2899 if (conn
->is_owning_control_connection
) {
2900 lost_owning_controller("connection", "closed");
2904 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
2905 * stage of the protocol. */
2907 is_valid_initial_command(control_connection_t
*conn
, const char *cmd
)
2909 if (conn
->_base
.state
== CONTROL_CONN_STATE_OPEN
)
2911 if (!strcasecmp(cmd
, "PROTOCOLINFO"))
2912 return !conn
->have_sent_protocolinfo
;
2913 if (!strcasecmp(cmd
, "AUTHENTICATE") ||
2914 !strcasecmp(cmd
, "QUIT"))
2919 /** Do not accept any control command of more than 1MB in length. Anything
2920 * that needs to be anywhere near this long probably means that one of our
2921 * interfaces is broken. */
2922 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
2924 /** Called when data has arrived on a v1 control connection: Try to fetch
2925 * commands from conn->inbuf, and execute them.
2928 connection_control_process_inbuf(control_connection_t
*conn
)
2931 uint32_t cmd_data_len
;
2936 tor_assert(conn
->_base
.state
== CONTROL_CONN_STATE_OPEN
||
2937 conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH
);
2939 if (!conn
->incoming_cmd
) {
2940 conn
->incoming_cmd
= tor_malloc(1024);
2941 conn
->incoming_cmd_len
= 1024;
2942 conn
->incoming_cmd_cur_len
= 0;
2945 if (conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
2946 peek_buf_has_control0_command(conn
->_base
.inbuf
)) {
2947 /* Detect v0 commands and send a "no more v0" message. */
2950 set_uint16(buf
+2, htons(0x0000)); /* type == error */
2951 set_uint16(buf
+4, htons(0x0001)); /* code == internal error */
2952 strlcpy(buf
+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
2953 "and later; upgrade your controller.",
2955 body_len
= 2+strlen(buf
+6)+2; /* code, msg, nul. */
2956 set_uint16(buf
+0, htons(body_len
));
2957 connection_write_to_buf(buf
, 4+body_len
, TO_CONN(conn
));
2958 connection_mark_for_close(TO_CONN(conn
));
2959 conn
->_base
.hold_open_until_flushed
= 1;
2967 /* First, fetch a line. */
2969 data_len
= conn
->incoming_cmd_len
- conn
->incoming_cmd_cur_len
;
2970 r
= fetch_from_buf_line(conn
->_base
.inbuf
,
2971 conn
->incoming_cmd
+conn
->incoming_cmd_cur_len
,
2974 /* Line not all here yet. Wait. */
2977 if (data_len
+ conn
->incoming_cmd_cur_len
> MAX_COMMAND_LINE_LENGTH
) {
2978 connection_write_str_to_buf("500 Line too long.\r\n", conn
);
2979 connection_stop_reading(TO_CONN(conn
));
2980 connection_mark_for_close(TO_CONN(conn
));
2981 conn
->_base
.hold_open_until_flushed
= 1;
2983 while (conn
->incoming_cmd_len
< data_len
+conn
->incoming_cmd_cur_len
)
2984 conn
->incoming_cmd_len
*= 2;
2985 conn
->incoming_cmd
= tor_realloc(conn
->incoming_cmd
,
2986 conn
->incoming_cmd_len
);
2990 tor_assert(data_len
);
2992 last_idx
= conn
->incoming_cmd_cur_len
;
2993 conn
->incoming_cmd_cur_len
+= (int)data_len
;
2995 /* We have appended a line to incoming_cmd. Is the command done? */
2996 if (last_idx
== 0 && *conn
->incoming_cmd
!= '+')
2997 /* One line command, didn't start with '+'. */
2999 /* XXXX this code duplication is kind of dumb. */
3000 if (last_idx
+3 == conn
->incoming_cmd_cur_len
&&
3001 tor_memeq(conn
->incoming_cmd
+ last_idx
, ".\r\n", 3)) {
3002 /* Just appended ".\r\n"; we're done. Remove it. */
3003 conn
->incoming_cmd
[last_idx
] = '\0';
3004 conn
->incoming_cmd_cur_len
-= 3;
3006 } else if (last_idx
+2 == conn
->incoming_cmd_cur_len
&&
3007 tor_memeq(conn
->incoming_cmd
+ last_idx
, ".\n", 2)) {
3008 /* Just appended ".\n"; we're done. Remove it. */
3009 conn
->incoming_cmd
[last_idx
] = '\0';
3010 conn
->incoming_cmd_cur_len
-= 2;
3013 /* Otherwise, read another line. */
3015 data_len
= conn
->incoming_cmd_cur_len
;
3016 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
3020 while ((size_t)cmd_len
< data_len
3021 && !TOR_ISSPACE(conn
->incoming_cmd
[cmd_len
]))
3024 conn
->incoming_cmd
[cmd_len
]='\0';
3025 args
= conn
->incoming_cmd
+cmd_len
+1;
3026 tor_assert(data_len
>(size_t)cmd_len
);
3027 data_len
-= (cmd_len
+1); /* skip the command and NUL we added after it */
3028 while (*args
== ' ' || *args
== '\t') {
3033 /* If the connection is already closing, ignore further commands */
3034 if (TO_CONN(conn
)->marked_for_close
) {
3038 /* Otherwise, Quit is always valid. */
3039 if (!strcasecmp(conn
->incoming_cmd
, "QUIT")) {
3040 connection_write_str_to_buf("250 closing connection\r\n", conn
);
3041 connection_mark_for_close(TO_CONN(conn
));
3042 conn
->_base
.hold_open_until_flushed
= 1;
3046 if (conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
3047 !is_valid_initial_command(conn
, conn
->incoming_cmd
)) {
3048 connection_write_str_to_buf("514 Authentication required.\r\n", conn
);
3049 connection_mark_for_close(TO_CONN(conn
));
3053 if (data_len
>= UINT32_MAX
) {
3054 connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn
);
3055 connection_mark_for_close(TO_CONN(conn
));
3059 /* XXXX Why is this not implemented as a table like the GETINFO
3060 * items are? Even handling the plus signs at the beginnings of
3061 * commands wouldn't be very hard with proper macros. */
3062 cmd_data_len
= (uint32_t)data_len
;
3063 if (!strcasecmp(conn
->incoming_cmd
, "SETCONF")) {
3064 if (handle_control_setconf(conn
, cmd_data_len
, args
))
3066 } else if (!strcasecmp(conn
->incoming_cmd
, "RESETCONF")) {
3067 if (handle_control_resetconf(conn
, cmd_data_len
, args
))
3069 } else if (!strcasecmp(conn
->incoming_cmd
, "GETCONF")) {
3070 if (handle_control_getconf(conn
, cmd_data_len
, args
))
3072 } else if (!strcasecmp(conn
->incoming_cmd
, "+LOADCONF")) {
3073 if (handle_control_loadconf(conn
, cmd_data_len
, args
))
3075 } else if (!strcasecmp(conn
->incoming_cmd
, "SETEVENTS")) {
3076 if (handle_control_setevents(conn
, cmd_data_len
, args
))
3078 } else if (!strcasecmp(conn
->incoming_cmd
, "AUTHENTICATE")) {
3079 if (handle_control_authenticate(conn
, cmd_data_len
, args
))
3081 } else if (!strcasecmp(conn
->incoming_cmd
, "SAVECONF")) {
3082 if (handle_control_saveconf(conn
, cmd_data_len
, args
))
3084 } else if (!strcasecmp(conn
->incoming_cmd
, "SIGNAL")) {
3085 if (handle_control_signal(conn
, cmd_data_len
, args
))
3087 } else if (!strcasecmp(conn
->incoming_cmd
, "TAKEOWNERSHIP")) {
3088 if (handle_control_takeownership(conn
, cmd_data_len
, args
))
3090 } else if (!strcasecmp(conn
->incoming_cmd
, "MAPADDRESS")) {
3091 if (handle_control_mapaddress(conn
, cmd_data_len
, args
))
3093 } else if (!strcasecmp(conn
->incoming_cmd
, "GETINFO")) {
3094 if (handle_control_getinfo(conn
, cmd_data_len
, args
))
3096 } else if (!strcasecmp(conn
->incoming_cmd
, "EXTENDCIRCUIT")) {
3097 if (handle_control_extendcircuit(conn
, cmd_data_len
, args
))
3099 } else if (!strcasecmp(conn
->incoming_cmd
, "SETCIRCUITPURPOSE")) {
3100 if (handle_control_setcircuitpurpose(conn
, cmd_data_len
, args
))
3102 } else if (!strcasecmp(conn
->incoming_cmd
, "SETROUTERPURPOSE")) {
3103 connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn
);
3104 } else if (!strcasecmp(conn
->incoming_cmd
, "ATTACHSTREAM")) {
3105 if (handle_control_attachstream(conn
, cmd_data_len
, args
))
3107 } else if (!strcasecmp(conn
->incoming_cmd
, "+POSTDESCRIPTOR")) {
3108 if (handle_control_postdescriptor(conn
, cmd_data_len
, args
))
3110 } else if (!strcasecmp(conn
->incoming_cmd
, "REDIRECTSTREAM")) {
3111 if (handle_control_redirectstream(conn
, cmd_data_len
, args
))
3113 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSESTREAM")) {
3114 if (handle_control_closestream(conn
, cmd_data_len
, args
))
3116 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSECIRCUIT")) {
3117 if (handle_control_closecircuit(conn
, cmd_data_len
, args
))
3119 } else if (!strcasecmp(conn
->incoming_cmd
, "USEFEATURE")) {
3120 if (handle_control_usefeature(conn
, cmd_data_len
, args
))
3122 } else if (!strcasecmp(conn
->incoming_cmd
, "RESOLVE")) {
3123 if (handle_control_resolve(conn
, cmd_data_len
, args
))
3125 } else if (!strcasecmp(conn
->incoming_cmd
, "PROTOCOLINFO")) {
3126 if (handle_control_protocolinfo(conn
, cmd_data_len
, args
))
3129 connection_printf_to_buf(conn
, "510 Unrecognized command \"%s\"\r\n",
3130 conn
->incoming_cmd
);
3133 conn
->incoming_cmd_cur_len
= 0;
3137 /** Something has happened to circuit <b>circ</b>: tell any interested
3138 * control connections. */
3140 control_event_circuit_status(origin_circuit_t
*circ
, circuit_status_event_t tp
,
3144 char extended_buf
[96];
3145 int providing_reason
=0;
3146 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS
))
3152 case CIRC_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
3153 case CIRC_EVENT_BUILT
: status
= "BUILT"; break;
3154 case CIRC_EVENT_EXTENDED
: status
= "EXTENDED"; break;
3155 case CIRC_EVENT_FAILED
: status
= "FAILED"; break;
3156 case CIRC_EVENT_CLOSED
: status
= "CLOSED"; break;
3158 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3162 tor_snprintf(extended_buf
, sizeof(extended_buf
), "PURPOSE=%s",
3163 circuit_purpose_to_controller_string(circ
->_base
.purpose
));
3165 if (tp
== CIRC_EVENT_FAILED
|| tp
== CIRC_EVENT_CLOSED
) {
3166 const char *reason_str
= circuit_end_reason_to_control_string(reason_code
);
3167 char *reason
= NULL
;
3168 size_t n
=strlen(extended_buf
);
3171 reason
= tor_malloc(16);
3172 tor_snprintf(reason
, 16, "UNKNOWN_%d", reason_code
);
3173 reason_str
= reason
;
3175 if (reason_code
> 0 && reason_code
& END_CIRC_REASON_FLAG_REMOTE
) {
3176 tor_snprintf(extended_buf
+n
, sizeof(extended_buf
)-n
,
3177 " REASON=DESTROYED REMOTE_REASON=%s", reason_str
);
3179 tor_snprintf(extended_buf
+n
, sizeof(extended_buf
)-n
,
3180 " REASON=%s", reason_str
);
3186 char *vpath
= circuit_list_path_for_controller(circ
);
3187 const char *sp
= strlen(vpath
) ? " " : "";
3188 send_control_event(EVENT_CIRCUIT_STATUS
, ALL_FORMATS
,
3189 "650 CIRC %lu %s%s%s %s\r\n",
3190 (unsigned long)circ
->global_identifier
,
3191 status
, sp
, vpath
, extended_buf
);
3198 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
3199 * <b>buf</b>, determine the address:port combination requested on
3200 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
3203 write_stream_target_to_buf(edge_connection_t
*conn
, char *buf
, size_t len
)
3206 if (conn
->chosen_exit_name
)
3207 if (tor_snprintf(buf2
, sizeof(buf2
), ".%s.exit", conn
->chosen_exit_name
)<0)
3209 if (!conn
->socks_request
)
3211 if (tor_snprintf(buf
, len
, "%s%s%s:%d",
3212 conn
->socks_request
->address
,
3213 conn
->chosen_exit_name
? buf2
: "",
3214 !conn
->chosen_exit_name
&&
3215 connection_edge_is_rendezvous_stream(conn
) ? ".onion" : "",
3216 conn
->socks_request
->port
)<0)
3221 /** Something has happened to the stream associated with AP connection
3222 * <b>conn</b>: tell any interested control connections. */
3224 control_event_stream_status(edge_connection_t
*conn
, stream_status_event_t tp
,
3227 char reason_buf
[64];
3228 char addrport_buf
[64];
3231 origin_circuit_t
*origin_circ
= NULL
;
3233 const char *purpose
= "";
3234 tor_assert(conn
->socks_request
);
3236 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS
))
3239 if (tp
== STREAM_EVENT_CLOSED
&&
3240 (reason_code
& END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
))
3243 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
3245 reason_buf
[0] = '\0';
3248 case STREAM_EVENT_SENT_CONNECT
: status
= "SENTCONNECT"; break;
3249 case STREAM_EVENT_SENT_RESOLVE
: status
= "SENTRESOLVE"; break;
3250 case STREAM_EVENT_SUCCEEDED
: status
= "SUCCEEDED"; break;
3251 case STREAM_EVENT_FAILED
: status
= "FAILED"; break;
3252 case STREAM_EVENT_CLOSED
: status
= "CLOSED"; break;
3253 case STREAM_EVENT_NEW
: status
= "NEW"; break;
3254 case STREAM_EVENT_NEW_RESOLVE
: status
= "NEWRESOLVE"; break;
3255 case STREAM_EVENT_FAILED_RETRIABLE
: status
= "DETACHED"; break;
3256 case STREAM_EVENT_REMAP
: status
= "REMAP"; break;
3258 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3261 if (reason_code
&& (tp
== STREAM_EVENT_FAILED
||
3262 tp
== STREAM_EVENT_CLOSED
||
3263 tp
== STREAM_EVENT_FAILED_RETRIABLE
)) {
3264 const char *reason_str
= stream_end_reason_to_control_string(reason_code
);
3268 tor_snprintf(r
, 16, " UNKNOWN_%d", reason_code
);
3271 if (reason_code
& END_STREAM_REASON_FLAG_REMOTE
)
3272 tor_snprintf(reason_buf
, sizeof(reason_buf
),
3273 " REASON=END REMOTE_REASON=%s", reason_str
);
3275 tor_snprintf(reason_buf
, sizeof(reason_buf
),
3276 " REASON=%s", reason_str
);
3278 } else if (reason_code
&& tp
== STREAM_EVENT_REMAP
) {
3279 switch (reason_code
) {
3280 case REMAP_STREAM_SOURCE_CACHE
:
3281 strlcpy(reason_buf
, " SOURCE=CACHE", sizeof(reason_buf
));
3283 case REMAP_STREAM_SOURCE_EXIT
:
3284 strlcpy(reason_buf
, " SOURCE=EXIT", sizeof(reason_buf
));
3287 tor_snprintf(reason_buf
, sizeof(reason_buf
), " REASON=UNKNOWN_%d",
3289 /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
3294 if (tp
== STREAM_EVENT_NEW
) {
3295 tor_snprintf(addrport_buf
,sizeof(addrport_buf
), " SOURCE_ADDR=%s:%d",
3296 TO_CONN(conn
)->address
, TO_CONN(conn
)->port
);
3298 addrport_buf
[0] = '\0';
3301 if (tp
== STREAM_EVENT_NEW_RESOLVE
) {
3302 purpose
= " PURPOSE=DNS_REQUEST";
3303 } else if (tp
== STREAM_EVENT_NEW
) {
3304 if (conn
->is_dns_request
||
3305 (conn
->socks_request
&&
3306 SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
)))
3307 purpose
= " PURPOSE=DNS_REQUEST";
3308 else if (conn
->use_begindir
) {
3309 connection_t
*linked
= TO_CONN(conn
)->linked_conn
;
3310 int linked_dir_purpose
= -1;
3311 if (linked
&& linked
->type
== CONN_TYPE_DIR
)
3312 linked_dir_purpose
= linked
->purpose
;
3313 if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose
))
3314 purpose
= " PURPOSE=DIR_UPLOAD";
3316 purpose
= " PURPOSE=DIR_FETCH";
3318 purpose
= " PURPOSE=USER";
3321 circ
= circuit_get_by_edge_conn(conn
);
3322 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
3323 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
3324 send_control_event(EVENT_STREAM_STATUS
, ALL_FORMATS
,
3325 "650 STREAM "U64_FORMAT
" %s %lu %s%s%s%s\r\n",
3326 U64_PRINTF_ARG(conn
->_base
.global_identifier
), status
,
3328 (unsigned long)origin_circ
->global_identifier
: 0ul,
3329 buf
, reason_buf
, addrport_buf
, purpose
);
3331 /* XXX need to specify its intended exit, etc? */
3336 /** Figure out the best name for the target router of an OR connection
3337 * <b>conn</b>, and write it into the <b>len</b>-character buffer
3340 orconn_target_get_name(char *name
, size_t len
, or_connection_t
*conn
)
3342 routerinfo_t
*ri
= router_get_by_digest(conn
->identity_digest
);
3344 tor_assert(len
> MAX_VERBOSE_NICKNAME_LEN
);
3345 router_get_verbose_nickname(name
, ri
);
3346 } else if (! tor_digest_is_zero(conn
->identity_digest
)) {
3348 base16_encode(name
+1, len
-1, conn
->identity_digest
,
3351 tor_snprintf(name
, len
, "%s:%d",
3352 conn
->_base
.address
, conn
->_base
.port
);
3356 /** Called when the status of an OR connection <b>conn</b> changes: tell any
3357 * interested control connections. <b>tp</b> is the new status for the
3358 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
3359 * may be the reason why.
3362 control_event_or_conn_status(or_connection_t
*conn
, or_conn_status_event_t tp
,
3368 char ncircs_buf
[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
3370 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS
))
3375 case OR_CONN_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
3376 case OR_CONN_EVENT_CONNECTED
: status
= "CONNECTED"; break;
3377 case OR_CONN_EVENT_FAILED
: status
= "FAILED"; break;
3378 case OR_CONN_EVENT_CLOSED
: status
= "CLOSED"; break;
3379 case OR_CONN_EVENT_NEW
: status
= "NEW"; break;
3381 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3384 ncircs
= circuit_count_pending_on_or_conn(conn
);
3385 ncircs
+= conn
->n_circuits
;
3386 if (ncircs
&& (tp
== OR_CONN_EVENT_FAILED
|| tp
== OR_CONN_EVENT_CLOSED
)) {
3387 tor_snprintf(ncircs_buf
, sizeof(ncircs_buf
), "%sNCIRCS=%d",
3388 reason
? " " : "", ncircs
);
3391 orconn_target_get_name(name
, sizeof(name
), conn
);
3392 send_control_event(EVENT_OR_CONN_STATUS
, ALL_FORMATS
,
3393 "650 ORCONN %s %s %s%s%s\r\n",
3395 reason
? "REASON=" : "",
3396 orconn_end_reason_to_control_string(reason
),
3403 * Print out STREAM_BW event for a single conn
3406 control_event_stream_bandwidth(edge_connection_t
*edge_conn
)
3408 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED
)) {
3409 if (!edge_conn
->n_read
&& !edge_conn
->n_written
)
3412 send_control_event(EVENT_STREAM_BANDWIDTH_USED
, ALL_FORMATS
,
3413 "650 STREAM_BW "U64_FORMAT
" %lu %lu\r\n",
3414 U64_PRINTF_ARG(edge_conn
->_base
.global_identifier
),
3415 (unsigned long)edge_conn
->n_read
,
3416 (unsigned long)edge_conn
->n_written
);
3418 edge_conn
->n_written
= edge_conn
->n_read
= 0;
3424 /** A second or more has elapsed: tell any interested control
3425 * connections how much bandwidth streams have used. */
3427 control_event_stream_bandwidth_used(void)
3429 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED
)) {
3430 smartlist_t
*conns
= get_connection_array();
3431 edge_connection_t
*edge_conn
;
3433 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
)
3435 if (conn
->type
!= CONN_TYPE_AP
)
3437 edge_conn
= TO_EDGE_CONN(conn
);
3438 if (!edge_conn
->n_read
&& !edge_conn
->n_written
)
3441 send_control_event(EVENT_STREAM_BANDWIDTH_USED
, ALL_FORMATS
,
3442 "650 STREAM_BW "U64_FORMAT
" %lu %lu\r\n",
3443 U64_PRINTF_ARG(edge_conn
->_base
.global_identifier
),
3444 (unsigned long)edge_conn
->n_read
,
3445 (unsigned long)edge_conn
->n_written
);
3447 edge_conn
->n_written
= edge_conn
->n_read
= 0;
3449 SMARTLIST_FOREACH_END(conn
);
3455 /** A second or more has elapsed: tell any interested control
3456 * connections how much bandwidth we used. */
3458 control_event_bandwidth_used(uint32_t n_read
, uint32_t n_written
)
3460 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED
)) {
3461 send_control_event(EVENT_BANDWIDTH_USED
, ALL_FORMATS
,
3462 "650 BW %lu %lu\r\n",
3463 (unsigned long)n_read
,
3464 (unsigned long)n_written
);
3470 /** Called when we are sending a log message to the controllers: suspend
3471 * sending further log messages to the controllers until we're done. Used by
3472 * CONN_LOG_PROTECT. */
3474 disable_control_logging(void)
3476 ++disable_log_messages
;
3479 /** We're done sending a log message to the controllers: re-enable controller
3480 * logging. Used by CONN_LOG_PROTECT. */
3482 enable_control_logging(void)
3484 if (--disable_log_messages
< 0)
3488 /** We got a log message: tell any interested control connections. */
3490 control_event_logmsg(int severity
, uint32_t domain
, const char *msg
)
3494 /* Don't even think of trying to add stuff to a buffer from a cpuworker
3496 if (! in_main_thread())
3499 if (disable_log_messages
)
3502 if (domain
== LD_BUG
&& EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
) &&
3503 severity
<= LOG_NOTICE
) {
3504 char *esc
= esc_for_log(msg
);
3505 ++disable_log_messages
;
3506 control_event_general_status(severity
, "BUG REASON=\"%s\"", esc
);
3507 --disable_log_messages
;
3511 event
= log_severity_to_event(severity
);
3512 if (event
>= 0 && EVENT_IS_INTERESTING(event
)) {
3515 if (strchr(msg
, '\n')) {
3517 b
= tor_strdup(msg
);
3518 for (cp
= b
; *cp
; ++cp
)
3519 if (*cp
== '\r' || *cp
== '\n')
3523 case LOG_DEBUG
: s
= "DEBUG"; break;
3524 case LOG_INFO
: s
= "INFO"; break;
3525 case LOG_NOTICE
: s
= "NOTICE"; break;
3526 case LOG_WARN
: s
= "WARN"; break;
3527 case LOG_ERR
: s
= "ERR"; break;
3528 default: s
= "UnknownLogSeverity"; break;
3530 ++disable_log_messages
;
3531 send_control_event(event
, ALL_FORMATS
, "650 %s %s\r\n", s
, b
?b
:msg
);
3532 --disable_log_messages
;
3537 /** Called whenever we receive new router descriptors: tell any
3538 * interested control connections. <b>routers</b> is a list of
3542 control_event_descriptors_changed(smartlist_t
*routers
)
3546 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC
))
3550 smartlist_t
*names
= smartlist_create();
3553 SMARTLIST_FOREACH(routers
, routerinfo_t
*, ri
, {
3554 char *b
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
3555 router_get_verbose_nickname(b
, ri
);
3556 smartlist_add(names
, b
);
3558 ids
= smartlist_join_strings(names
, " ", 0, &names_len
);
3559 names_len
= strlen(ids
)+32;
3560 msg
= tor_malloc(names_len
);
3561 tor_snprintf(msg
, names_len
, "650 NEWDESC %s\r\n", ids
);
3562 send_control_event_string(EVENT_NEW_DESC
, ALL_FORMATS
, msg
);
3565 SMARTLIST_FOREACH(names
, char *, cp
, tor_free(cp
));
3566 smartlist_free(names
);
3571 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
3572 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
3573 * <b>error</b> is non-NULL, it is an error code describing the failure
3574 * mode of the mapping.
3577 control_event_address_mapped(const char *from
, const char *to
, time_t expires
,
3580 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP
))
3583 if (expires
< 3 || expires
== TIME_MAX
)
3584 send_control_event(EVENT_ADDRMAP
, ALL_FORMATS
,
3585 "650 ADDRMAP %s %s NEVER %s\r\n", from
, to
,
3588 char buf
[ISO_TIME_LEN
+1];
3589 char buf2
[ISO_TIME_LEN
+1];
3590 format_local_iso_time(buf
,expires
);
3591 format_iso_time(buf2
,expires
);
3592 send_control_event(EVENT_ADDRMAP
, ALL_FORMATS
,
3593 "650 ADDRMAP %s %s \"%s\""
3594 " %s%sEXPIRES=\"%s\"\r\n",
3596 error
?error
:"", error
?" ":"",
3603 /** The authoritative dirserver has received a new descriptor that
3604 * has passed basic syntax checks and is properly self-signed.
3606 * Notify any interested party of the new descriptor and what has
3607 * been done with it, and also optionally give an explanation/reason. */
3609 control_event_or_authdir_new_descriptor(const char *action
,
3610 const char *desc
, size_t desclen
,
3613 char firstline
[1024];
3619 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS
))
3622 tor_snprintf(firstline
, sizeof(firstline
),
3623 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
3627 /* Escape the server descriptor properly */
3628 esclen
= write_escaped_data(desc
, desclen
, &esc
);
3630 totallen
= strlen(firstline
) + esclen
+ 1;
3631 buf
= tor_malloc(totallen
);
3632 strlcpy(buf
, firstline
, totallen
);
3633 strlcpy(buf
+strlen(firstline
), esc
, totallen
);
3634 send_control_event_string(EVENT_AUTHDIR_NEWDESCS
, ALL_FORMATS
,
3636 send_control_event_string(EVENT_AUTHDIR_NEWDESCS
, ALL_FORMATS
,
3644 /** Helper function for NS-style events. Constructs and sends an event
3645 * of type <b>event</b> with string <b>event_string</b> out of the set of
3646 * networkstatuses <b>statuses</b>. Currently it is used for NS events
3647 * and NEWCONSENSUS events. */
3649 control_event_networkstatus_changed_helper(smartlist_t
*statuses
,
3651 const char *event_string
)
3654 char *s
, *esc
= NULL
;
3655 if (!EVENT_IS_INTERESTING(event
) || !smartlist_len(statuses
))
3658 strs
= smartlist_create();
3659 smartlist_add(strs
, tor_strdup("650+"));
3660 smartlist_add(strs
, tor_strdup(event_string
));
3661 smartlist_add(strs
, tor_strdup("\r\n"));
3662 SMARTLIST_FOREACH(statuses
, routerstatus_t
*, rs
,
3664 s
= networkstatus_getinfo_helper_single(rs
);
3666 smartlist_add(strs
, s
);
3669 s
= smartlist_join_strings(strs
, "", 0, NULL
);
3670 write_escaped_data(s
, strlen(s
), &esc
);
3671 SMARTLIST_FOREACH(strs
, char *, cp
, tor_free(cp
));
3672 smartlist_free(strs
);
3674 send_control_event_string(event
, ALL_FORMATS
, esc
);
3675 send_control_event_string(event
, ALL_FORMATS
,
3682 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
3683 * an NS event to any controller that cares. */
3685 control_event_networkstatus_changed(smartlist_t
*statuses
)
3687 return control_event_networkstatus_changed_helper(statuses
, EVENT_NS
, "NS");
3690 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
3691 * event consisting of an NS-style line for each relay in the consensus. */
3693 control_event_newconsensus(const networkstatus_t
*consensus
)
3695 if (!control_event_is_interesting(EVENT_NEWCONSENSUS
))
3697 return control_event_networkstatus_changed_helper(
3698 consensus
->routerstatus_list
, EVENT_NEWCONSENSUS
, "NEWCONSENSUS");
3701 /** Called when we compute a new circuitbuildtimeout */
3703 control_event_buildtimeout_set(const circuit_build_times_t
*cbt
,
3704 buildtimeout_set_event_t type
)
3706 const char *type_string
= NULL
;
3707 double qnt
= circuit_build_times_quantile_cutoff();
3709 if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET
))
3713 case BUILDTIMEOUT_SET_EVENT_COMPUTED
:
3714 type_string
= "COMPUTED";
3716 case BUILDTIMEOUT_SET_EVENT_RESET
:
3717 type_string
= "RESET";
3720 case BUILDTIMEOUT_SET_EVENT_SUSPENDED
:
3721 type_string
= "SUSPENDED";
3724 case BUILDTIMEOUT_SET_EVENT_DISCARD
:
3725 type_string
= "DISCARD";
3728 case BUILDTIMEOUT_SET_EVENT_RESUME
:
3729 type_string
= "RESUME";
3732 type_string
= "UNKNOWN";
3736 send_control_event(EVENT_BUILDTIMEOUT_SET
, ALL_FORMATS
,
3737 "650 BUILDTIMEOUT_SET %s TOTAL_TIMES=%lu "
3738 "TIMEOUT_MS=%lu XM=%lu ALPHA=%lf CUTOFF_QUANTILE=%lf "
3739 "TIMEOUT_RATE=%lf CLOSE_MS=%lu CLOSE_RATE=%lf\r\n",
3740 type_string
, (unsigned long)cbt
->total_build_times
,
3741 (unsigned long)cbt
->timeout_ms
,
3742 (unsigned long)cbt
->Xm
, cbt
->alpha
, qnt
,
3743 circuit_build_times_timeout_rate(cbt
),
3744 (unsigned long)cbt
->close_ms
,
3745 circuit_build_times_close_rate(cbt
));
3750 /** Called when a single local_routerstatus_t has changed: Sends an NS event
3751 * to any controller that cares. */
3753 control_event_networkstatus_changed_single(routerstatus_t
*rs
)
3755 smartlist_t
*statuses
;
3758 if (!EVENT_IS_INTERESTING(EVENT_NS
))
3761 statuses
= smartlist_create();
3762 smartlist_add(statuses
, rs
);
3763 r
= control_event_networkstatus_changed(statuses
);
3764 smartlist_free(statuses
);
3768 /** Our own router descriptor has changed; tell any controllers that care.
3771 control_event_my_descriptor_changed(void)
3773 send_control_event(EVENT_DESCCHANGED
, ALL_FORMATS
, "650 DESCCHANGED\r\n");
3777 /** Helper: sends a status event where <b>type</b> is one of
3778 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
3779 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
3780 * string corresponding to <b>args</b>. */
3782 control_event_status(int type
, int severity
, const char *format
, va_list args
)
3784 char format_buf
[160];
3785 const char *status
, *sev
;
3788 case EVENT_STATUS_GENERAL
:
3789 status
= "STATUS_GENERAL";
3791 case EVENT_STATUS_CLIENT
:
3792 status
= "STATUS_CLIENT";
3794 case EVENT_STATUS_SERVER
:
3795 status
= "STATUS_SERVER";
3798 log_warn(LD_BUG
, "Unrecognized status type %d", type
);
3812 log_warn(LD_BUG
, "Unrecognized status severity %d", severity
);
3815 if (tor_snprintf(format_buf
, sizeof(format_buf
), "650 %s %s %s\r\n",
3816 status
, sev
, format
)<0) {
3817 log_warn(LD_BUG
, "Format string too long.");
3821 send_control_event_impl(type
, ALL_FORMATS
, format_buf
, args
);
3825 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
3826 * by formatting the arguments using the printf-style <b>format</b>. */
3828 control_event_general_status(int severity
, const char *format
, ...)
3832 if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
))
3835 va_start(ap
, format
);
3836 r
= control_event_status(EVENT_STATUS_GENERAL
, severity
, format
, ap
);
3841 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
3842 * by formatting the arguments using the printf-style <b>format</b>. */
3844 control_event_client_status(int severity
, const char *format
, ...)
3848 if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT
))
3851 va_start(ap
, format
);
3852 r
= control_event_status(EVENT_STATUS_CLIENT
, severity
, format
, ap
);
3857 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
3858 * by formatting the arguments using the printf-style <b>format</b>. */
3860 control_event_server_status(int severity
, const char *format
, ...)
3864 if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER
))
3867 va_start(ap
, format
);
3868 r
= control_event_status(EVENT_STATUS_SERVER
, severity
, format
, ap
);
3873 /** Called when the status of an entry guard with the given <b>nickname</b>
3874 * and identity <b>digest</b> has changed to <b>status</b>: tells any
3875 * controllers that care. */
3877 control_event_guard(const char *nickname
, const char *digest
,
3880 char hbuf
[HEX_DIGEST_LEN
+1];
3881 base16_encode(hbuf
, sizeof(hbuf
), digest
, DIGEST_LEN
);
3882 if (!EVENT_IS_INTERESTING(EVENT_GUARD
))
3886 char buf
[MAX_VERBOSE_NICKNAME_LEN
+1];
3887 routerinfo_t
*ri
= router_get_by_digest(digest
);
3889 router_get_verbose_nickname(buf
, ri
);
3891 tor_snprintf(buf
, sizeof(buf
), "$%s~%s", hbuf
, nickname
);
3893 send_control_event(EVENT_GUARD
, ALL_FORMATS
,
3894 "650 GUARD ENTRY %s %s\r\n", buf
, status
);
3899 /** Helper: Return a newly allocated string containing a path to the
3900 * file where we store our authentication cookie. */
3902 get_cookie_file(void)
3904 or_options_t
*options
= get_options();
3905 if (options
->CookieAuthFile
&& strlen(options
->CookieAuthFile
)) {
3906 return tor_strdup(options
->CookieAuthFile
);
3908 return get_datadir_fname("control_auth_cookie");
3912 /** Choose a random authentication cookie and write it to disk.
3913 * Anybody who can read the cookie from disk will be considered
3914 * authorized to use the control connection. Return -1 if we can't
3915 * write the file, or 0 on success. */
3917 init_cookie_authentication(int enabled
)
3921 authentication_cookie_is_set
= 0;
3925 /* We don't want to generate a new cookie every time we call
3926 * options_act(). One should be enough. */
3927 if (authentication_cookie_is_set
)
3928 return 0; /* all set */
3930 fname
= get_cookie_file();
3931 crypto_rand(authentication_cookie
, AUTHENTICATION_COOKIE_LEN
);
3932 authentication_cookie_is_set
= 1;
3933 if (write_bytes_to_file(fname
, authentication_cookie
,
3934 AUTHENTICATION_COOKIE_LEN
, 1)) {
3935 log_warn(LD_FS
,"Error writing authentication cookie to %s.",
3941 if (get_options()->CookieAuthFileGroupReadable
) {
3942 if (chmod(fname
, 0640)) {
3943 log_warn(LD_FS
,"Unable to make %s group-readable.", escaped(fname
));
3952 /** A copy of the process specifier of Tor's owning controller, or
3953 * NULL if this Tor instance is not currently owned by a process. */
3954 static char *owning_controller_process_spec
= NULL
;
3956 /** A process-termination monitor for Tor's owning controller, or NULL
3957 * if this Tor instance is not currently owned by a process. */
3958 static tor_process_monitor_t
*owning_controller_process_monitor
= NULL
;
3960 /** Process-termination monitor callback for Tor's owning controller
3963 owning_controller_procmon_cb(void *unused
)
3967 lost_owning_controller("process", "vanished");
3970 /** Set <b>process_spec</b> as Tor's owning controller process.
3971 * Exit on failure. */
3973 monitor_owning_controller_process(const char *process_spec
)
3977 tor_assert((owning_controller_process_spec
== NULL
) ==
3978 (owning_controller_process_monitor
== NULL
));
3980 if (owning_controller_process_spec
!= NULL
) {
3981 if ((process_spec
!= NULL
) && !strcmp(process_spec
,
3982 owning_controller_process_spec
)) {
3983 /* Same process -- return now, instead of disposing of and
3984 * recreating the process-termination monitor. */
3988 /* We are currently owned by a process, and we should no longer be
3989 * owned by it. Free the process-termination monitor. */
3990 tor_process_monitor_free(owning_controller_process_monitor
);
3991 owning_controller_process_monitor
= NULL
;
3993 tor_free(owning_controller_process_spec
);
3994 owning_controller_process_spec
= NULL
;
3997 tor_assert((owning_controller_process_spec
== NULL
) &&
3998 (owning_controller_process_monitor
== NULL
));
4000 if (process_spec
== NULL
)
4003 owning_controller_process_spec
= tor_strdup(process_spec
);
4004 owning_controller_process_monitor
=
4005 tor_process_monitor_new(tor_libevent_get_base(),
4006 owning_controller_process_spec
,
4008 owning_controller_procmon_cb
, NULL
,
4011 if (owning_controller_process_monitor
== NULL
) {
4012 log_err(LD_BUG
, "Couldn't create process-termination monitor for "
4013 "owning controller: %s. Exiting.",
4015 owning_controller_process_spec
= NULL
;
4021 /** Convert the name of a bootstrapping phase <b>s</b> into strings
4022 * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
4024 bootstrap_status_to_string(bootstrap_status_t s
, const char **tag
,
4025 const char **summary
)
4028 case BOOTSTRAP_STATUS_UNDEF
:
4030 *summary
= "Undefined";
4032 case BOOTSTRAP_STATUS_STARTING
:
4034 *summary
= "Starting";
4036 case BOOTSTRAP_STATUS_CONN_DIR
:
4038 *summary
= "Connecting to directory server";
4040 case BOOTSTRAP_STATUS_HANDSHAKE
:
4041 *tag
= "status_handshake";
4042 *summary
= "Finishing handshake";
4044 case BOOTSTRAP_STATUS_HANDSHAKE_DIR
:
4045 *tag
= "handshake_dir";
4046 *summary
= "Finishing handshake with directory server";
4048 case BOOTSTRAP_STATUS_ONEHOP_CREATE
:
4049 *tag
= "onehop_create";
4050 *summary
= "Establishing an encrypted directory connection";
4052 case BOOTSTRAP_STATUS_REQUESTING_STATUS
:
4053 *tag
= "requesting_status";
4054 *summary
= "Asking for networkstatus consensus";
4056 case BOOTSTRAP_STATUS_LOADING_STATUS
:
4057 *tag
= "loading_status";
4058 *summary
= "Loading networkstatus consensus";
4060 case BOOTSTRAP_STATUS_LOADING_KEYS
:
4061 *tag
= "loading_keys";
4062 *summary
= "Loading authority key certs";
4064 case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS
:
4065 *tag
= "requesting_descriptors";
4066 *summary
= "Asking for relay descriptors";
4068 case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS
:
4069 *tag
= "loading_descriptors";
4070 *summary
= "Loading relay descriptors";
4072 case BOOTSTRAP_STATUS_CONN_OR
:
4074 *summary
= "Connecting to the Tor network";
4076 case BOOTSTRAP_STATUS_HANDSHAKE_OR
:
4077 *tag
= "handshake_or";
4078 *summary
= "Finishing handshake with first hop";
4080 case BOOTSTRAP_STATUS_CIRCUIT_CREATE
:
4081 *tag
= "circuit_create";
4082 *summary
= "Establishing a Tor circuit";
4084 case BOOTSTRAP_STATUS_DONE
:
4089 // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
4090 *tag
= *summary
= "unknown";
4096 /** What percentage through the bootstrap process are we? We remember
4097 * this so we can avoid sending redundant bootstrap status events, and
4098 * so we can guess context for the bootstrap messages which are
4099 * ambiguous. It starts at 'undef', but gets set to 'starting' while
4100 * Tor initializes. */
4101 static int bootstrap_percent
= BOOTSTRAP_STATUS_UNDEF
;
4103 /** How many problems have we had getting to the next bootstrapping phase?
4104 * These include failure to establish a connection to a Tor relay,
4105 * failures to finish the TLS handshake, failures to validate the
4106 * consensus document, etc. */
4107 static int bootstrap_problems
= 0;
4109 /* We only tell the controller once we've hit a threshold of problems
4110 * for the current phase. */
4111 #define BOOTSTRAP_PROBLEM_THRESHOLD 10
4113 /** Called when Tor has made progress at bootstrapping its directory
4114 * information and initial circuits.
4116 * <b>status</b> is the new status, that is, what task we will be doing
4117 * next. <b>progress</b> is zero if we just started this task, else it
4118 * represents progress on the task. */
4120 control_event_bootstrap(bootstrap_status_t status
, int progress
)
4122 const char *tag
, *summary
;
4123 char buf
[BOOTSTRAP_MSG_LEN
];
4125 if (bootstrap_percent
== BOOTSTRAP_STATUS_DONE
)
4126 return; /* already bootstrapped; nothing to be done here. */
4128 /* special case for handshaking status, since our TLS handshaking code
4129 * can't distinguish what the connection is going to be for. */
4130 if (status
== BOOTSTRAP_STATUS_HANDSHAKE
) {
4131 if (bootstrap_percent
< BOOTSTRAP_STATUS_CONN_OR
) {
4132 status
= BOOTSTRAP_STATUS_HANDSHAKE_DIR
;
4134 status
= BOOTSTRAP_STATUS_HANDSHAKE_OR
;
4138 if (status
> bootstrap_percent
||
4139 (progress
&& progress
> bootstrap_percent
)) {
4140 bootstrap_status_to_string(status
, &tag
, &summary
);
4141 log(status
? LOG_NOTICE
: LOG_INFO
, LD_CONTROL
,
4142 "Bootstrapped %d%%: %s.", progress
? progress
: status
, summary
);
4143 tor_snprintf(buf
, sizeof(buf
),
4144 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
4145 progress
? progress
: status
, tag
, summary
);
4146 tor_snprintf(last_sent_bootstrap_message
,
4147 sizeof(last_sent_bootstrap_message
),
4149 control_event_client_status(LOG_NOTICE
, "%s", buf
);
4150 if (status
> bootstrap_percent
) {
4151 bootstrap_percent
= status
; /* new milestone reached */
4153 if (progress
> bootstrap_percent
) {
4154 /* incremental progress within a milestone */
4155 bootstrap_percent
= progress
;
4156 bootstrap_problems
= 0; /* Progress! Reset our problem counter. */
4161 /** Called when Tor has failed to make bootstrapping progress in a way
4162 * that indicates a problem. <b>warn</b> gives a hint as to why, and
4163 * <b>reason</b> provides an "or_conn_end_reason" tag.
4166 control_event_bootstrap_problem(const char *warn
, int reason
)
4168 int status
= bootstrap_percent
;
4169 const char *tag
, *summary
;
4170 char buf
[BOOTSTRAP_MSG_LEN
];
4171 const char *recommendation
= "ignore";
4173 /* bootstrap_percent must not be in "undefined" state here. */
4174 tor_assert(status
>= 0);
4176 if (bootstrap_percent
== 100)
4177 return; /* already bootstrapped; nothing to be done here. */
4179 bootstrap_problems
++;
4181 if (bootstrap_problems
>= BOOTSTRAP_PROBLEM_THRESHOLD
)
4182 recommendation
= "warn";
4184 if (reason
== END_OR_CONN_REASON_NO_ROUTE
)
4185 recommendation
= "warn";
4187 if (get_options()->UseBridges
&&
4188 !any_bridge_descriptors_known() &&
4189 !any_pending_bridge_descriptor_fetches())
4190 recommendation
= "warn";
4192 while (status
>=0 && bootstrap_status_to_string(status
, &tag
, &summary
) < 0)
4193 status
--; /* find a recognized status string based on current progress */
4194 status
= bootstrap_percent
; /* set status back to the actual number */
4196 log_fn(!strcmp(recommendation
, "warn") ? LOG_WARN
: LOG_INFO
,
4197 LD_CONTROL
, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
4198 "count %d; recommendation %s)",
4199 status
, summary
, warn
,
4200 orconn_end_reason_to_control_string(reason
),
4201 bootstrap_problems
, recommendation
);
4202 tor_snprintf(buf
, sizeof(buf
),
4203 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
4204 "COUNT=%d RECOMMENDATION=%s",
4205 bootstrap_percent
, tag
, summary
, warn
,
4206 orconn_end_reason_to_control_string(reason
), bootstrap_problems
,
4208 tor_snprintf(last_sent_bootstrap_message
,
4209 sizeof(last_sent_bootstrap_message
),
4211 control_event_client_status(LOG_WARN
, "%s", buf
);
4214 /** We just generated a new summary of which countries we've seen clients
4215 * from recently. Send a copy to the controller in case it wants to
4216 * display it for the user. */
4218 control_event_clients_seen(const char *controller_str
)
4220 send_control_event(EVENT_CLIENTS_SEEN
, 0,
4221 "650 CLIENTS_SEEN %s\r\n", controller_str
);