1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2011, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
7 * \brief Implementation for Tor's control-socket interface.
8 * See doc/spec/control-spec.txt for full details on protocol.
11 #define CONTROL_PRIVATE
15 #include "circuitbuild.h"
16 #include "circuitlist.h"
17 #include "circuituse.h"
19 #include "connection.h"
20 #include "connection_edge.h"
22 #include "directory.h"
26 #include "hibernate.h"
28 #include "networkstatus.h"
32 #include "routerlist.h"
33 #include "routerparse.h"
35 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
36 * finished authentication and is accepting commands. */
37 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
39 /* Recognized asynchronous event types. It's okay to expand this list
40 * because it is used both as a list of v0 event types, and as indices
41 * into the bitfield to determine which controllers want which events.
43 #define _EVENT_MIN 0x0001
44 #define EVENT_CIRCUIT_STATUS 0x0001
45 #define EVENT_STREAM_STATUS 0x0002
46 #define EVENT_OR_CONN_STATUS 0x0003
47 #define EVENT_BANDWIDTH_USED 0x0004
48 #define EVENT_LOG_OBSOLETE 0x0005 /* Can reclaim this. */
49 #define EVENT_NEW_DESC 0x0006
50 #define EVENT_DEBUG_MSG 0x0007
51 #define EVENT_INFO_MSG 0x0008
52 #define EVENT_NOTICE_MSG 0x0009
53 #define EVENT_WARN_MSG 0x000A
54 #define EVENT_ERR_MSG 0x000B
55 #define EVENT_ADDRMAP 0x000C
56 // #define EVENT_AUTHDIR_NEWDESCS 0x000D
57 #define EVENT_DESCCHANGED 0x000E
58 // #define EVENT_NS 0x000F
59 #define EVENT_STATUS_CLIENT 0x0010
60 #define EVENT_STATUS_SERVER 0x0011
61 #define EVENT_STATUS_GENERAL 0x0012
62 #define EVENT_GUARD 0x0013
63 #define EVENT_STREAM_BANDWIDTH_USED 0x0014
64 #define EVENT_CLIENTS_SEEN 0x0015
65 #define EVENT_NEWCONSENSUS 0x0016
66 #define EVENT_BUILDTIMEOUT_SET 0x0017
67 #define _EVENT_MAX 0x0017
68 /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
70 /** Bitfield: The bit 1<<e is set if <b>any</b> open control
71 * connection is interested in events of type <b>e</b>. We use this
72 * so that we can decide to skip generating event messages that nobody
73 * has interest in without having to walk over the global connection
76 typedef uint32_t event_mask_t
;
78 /** An event mask of all the events that any controller is interested in
80 static event_mask_t global_event_mask
= 0;
82 /** True iff we have disabled log messages from being sent to the controller */
83 static int disable_log_messages
= 0;
85 /** Macro: true if any control connection is interested in events of type
87 #define EVENT_IS_INTERESTING(e) \
88 (global_event_mask & (1<<(e)))
90 /** If we're using cookie-type authentication, how long should our cookies be?
92 #define AUTHENTICATION_COOKIE_LEN 32
94 /** If true, we've set authentication_cookie to a secret code and
95 * stored it to disk. */
96 static int authentication_cookie_is_set
= 0;
97 /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
98 * and which we're using to authenticate controllers. (If the controller can
99 * read it off disk, it has permission to connect. */
100 static char authentication_cookie
[AUTHENTICATION_COOKIE_LEN
];
102 /** A sufficiently large size to record the last bootstrap phase string. */
103 #define BOOTSTRAP_MSG_LEN 1024
105 /** What was the last bootstrap phase message we sent? We keep track
106 * of this so we can respond to getinfo status/bootstrap-phase queries. */
107 static char last_sent_bootstrap_message
[BOOTSTRAP_MSG_LEN
];
109 /** Flag for event_format_t. Indicates that we should use the one standard
112 #define ALL_FORMATS 1
114 /** Bit field of flags to select how to format a controller event. Recognized
115 * flag is ALL_FORMATS. */
116 typedef int event_format_t
;
118 static void connection_printf_to_buf(control_connection_t
*conn
,
119 const char *format
, ...)
121 static void send_control_done(control_connection_t
*conn
);
122 static void send_control_event(uint16_t event
, event_format_t which
,
123 const char *format
, ...)
125 static int handle_control_setconf(control_connection_t
*conn
, uint32_t len
,
127 static int handle_control_resetconf(control_connection_t
*conn
, uint32_t len
,
129 static int handle_control_getconf(control_connection_t
*conn
, uint32_t len
,
131 static int handle_control_loadconf(control_connection_t
*conn
, uint32_t len
,
133 static int handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
135 static int handle_control_authenticate(control_connection_t
*conn
,
138 static int handle_control_signal(control_connection_t
*conn
, uint32_t len
,
140 static int handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
142 static char *list_getinfo_options(void);
143 static int handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
145 static int handle_control_extendcircuit(control_connection_t
*conn
,
148 static int handle_control_setcircuitpurpose(control_connection_t
*conn
,
149 uint32_t len
, const char *body
);
150 static int handle_control_attachstream(control_connection_t
*conn
,
153 static int handle_control_postdescriptor(control_connection_t
*conn
,
156 static int handle_control_redirectstream(control_connection_t
*conn
,
159 static int handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
161 static int handle_control_closecircuit(control_connection_t
*conn
,
164 static int handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
166 static int handle_control_usefeature(control_connection_t
*conn
,
169 static int write_stream_target_to_buf(edge_connection_t
*conn
, char *buf
,
171 static void orconn_target_get_name(char *buf
, size_t len
,
172 or_connection_t
*conn
);
173 static char *get_cookie_file(void);
175 /** Given a control event code for a message event, return the corresponding
178 event_to_log_severity(int event
)
181 case EVENT_DEBUG_MSG
: return LOG_DEBUG
;
182 case EVENT_INFO_MSG
: return LOG_INFO
;
183 case EVENT_NOTICE_MSG
: return LOG_NOTICE
;
184 case EVENT_WARN_MSG
: return LOG_WARN
;
185 case EVENT_ERR_MSG
: return LOG_ERR
;
190 /** Given a log severity, return the corresponding control event code. */
192 log_severity_to_event(int severity
)
195 case LOG_DEBUG
: return EVENT_DEBUG_MSG
;
196 case LOG_INFO
: return EVENT_INFO_MSG
;
197 case LOG_NOTICE
: return EVENT_NOTICE_MSG
;
198 case LOG_WARN
: return EVENT_WARN_MSG
;
199 case LOG_ERR
: return EVENT_ERR_MSG
;
204 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
205 * connection's event_mask field. */
207 control_update_global_event_mask(void)
209 smartlist_t
*conns
= get_connection_array();
210 event_mask_t old_mask
, new_mask
;
211 old_mask
= global_event_mask
;
213 global_event_mask
= 0;
214 SMARTLIST_FOREACH(conns
, connection_t
*, _conn
,
216 if (_conn
->type
== CONN_TYPE_CONTROL
&&
217 STATE_IS_OPEN(_conn
->state
)) {
218 control_connection_t
*conn
= TO_CONTROL_CONN(_conn
);
219 global_event_mask
|= conn
->event_mask
;
223 new_mask
= global_event_mask
;
225 /* Handle the aftermath. Set up the log callback to tell us only what
226 * we want to hear...*/
227 control_adjust_event_log_severity();
229 /* ...then, if we've started logging stream bw, clear the appropriate
231 if (! (old_mask
& EVENT_STREAM_BANDWIDTH_USED
) &&
232 (new_mask
& EVENT_STREAM_BANDWIDTH_USED
)) {
233 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
235 if (conn
->type
== CONN_TYPE_AP
) {
236 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
237 edge_conn
->n_written
= edge_conn
->n_read
= 0;
243 /** Adjust the log severities that result in control_event_logmsg being called
244 * to match the severity of log messages that any controllers are interested
247 control_adjust_event_log_severity(void)
250 int min_log_event
=EVENT_ERR_MSG
, max_log_event
=EVENT_DEBUG_MSG
;
252 for (i
= EVENT_DEBUG_MSG
; i
<= EVENT_ERR_MSG
; ++i
) {
253 if (EVENT_IS_INTERESTING(i
)) {
258 for (i
= EVENT_ERR_MSG
; i
>= EVENT_DEBUG_MSG
; --i
) {
259 if (EVENT_IS_INTERESTING(i
)) {
264 if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE
) ||
265 EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
)) {
266 if (min_log_event
> EVENT_NOTICE_MSG
)
267 min_log_event
= EVENT_NOTICE_MSG
;
268 if (max_log_event
< EVENT_ERR_MSG
)
269 max_log_event
= EVENT_ERR_MSG
;
271 if (min_log_event
<= max_log_event
)
272 change_callback_log_severity(event_to_log_severity(min_log_event
),
273 event_to_log_severity(max_log_event
),
274 control_event_logmsg
);
276 change_callback_log_severity(LOG_ERR
, LOG_ERR
,
277 control_event_logmsg
);
280 /** Return true iff the event with code <b>c</b> is being sent to any current
281 * control connection. This is useful if the amount of work needed to prepare
282 * to call the appropriate control_event_...() function is high.
285 control_event_is_interesting(int event
)
287 return EVENT_IS_INTERESTING(event
);
290 /** Append a NUL-terminated string <b>s</b> to the end of
291 * <b>conn</b>-\>outbuf.
294 connection_write_str_to_buf(const char *s
, control_connection_t
*conn
)
296 size_t len
= strlen(s
);
297 connection_write_to_buf(s
, len
, TO_CONN(conn
));
300 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
301 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
302 * contents of <b>data</b> into *<b>out</b>, adding a period before any period
303 * that appears at the start of a line, and adding a period-CRLF line at
304 * the end. Replace all LF characters sequences with CRLF. Return the number
305 * of bytes in *<b>out</b>.
308 write_escaped_data(const char *data
, size_t len
, char **out
)
310 size_t sz_out
= len
+8;
312 const char *start
= data
, *end
;
315 for (i
=0; i
<(int)len
; ++i
) {
317 sz_out
+= 2; /* Maybe add a CR; maybe add a dot. */
319 *out
= outp
= tor_malloc(sz_out
+1);
324 if (data
> start
&& data
[-1] != '\r')
327 } else if (*data
== '.') {
337 if (outp
< *out
+2 || fast_memcmp(outp
-2, "\r\n", 2)) {
344 *outp
= '\0'; /* NUL-terminate just in case. */
345 tor_assert((outp
- *out
) <= (int)sz_out
);
349 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
350 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
351 * the contents of <b>data</b> into *<b>out</b>, removing any period
352 * that appears at the start of a line, and replacing all CRLF sequences
353 * with LF. Return the number of
354 * bytes in *<b>out</b>. */
356 read_escaped_data(const char *data
, size_t len
, char **out
)
362 *out
= outp
= tor_malloc(len
+1);
367 /* we're at the start of a line. */
370 next
= memchr(data
, '\n', end
-data
);
372 size_t n_to_copy
= next
-data
;
373 /* Don't copy a CR that precedes this LF. */
374 if (n_to_copy
&& *(next
-1) == '\r')
376 memcpy(outp
, data
, n_to_copy
);
378 data
= next
+1; /* This will point at the start of the next line,
379 * or the end of the string, or a period. */
381 memcpy(outp
, data
, end
-data
);
393 /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
394 * double-quoted string with escaped characters, return the length of that
395 * string (as encoded, including quotes). Otherwise return -1. */
397 get_escaped_string_length(const char *start
, size_t in_len_max
,
400 const char *cp
, *end
;
407 end
= start
+in_len_max
;
409 /* Calculate length. */
412 return -1; /* Too long. */
413 } else if (*cp
== '\\') {
415 return -1; /* Can't escape EOS. */
418 } else if (*cp
== '\"') {
427 return (int)(cp
- start
+1);
430 /** As decode_escaped_string, but does not decode the string: copies the
431 * entire thing, including quotation marks. */
433 extract_escaped_string(const char *start
, size_t in_len_max
,
434 char **out
, size_t *out_len
)
436 int length
= get_escaped_string_length(start
, in_len_max
, NULL
);
440 *out
= tor_strndup(start
, *out_len
);
444 /** Given a pointer to a string starting at <b>start</b> containing
445 * <b>in_len_max</b> characters, decode a string beginning with one double
446 * quote, containing any number of non-quote characters or characters escaped
447 * with a backslash, and ending with a final double quote. Place the resulting
448 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
449 * store its length in <b>out_len</b>. On success, return a pointer to the
450 * character immediately following the escaped string. On failure, return
453 decode_escaped_string(const char *start
, size_t in_len_max
,
454 char **out
, size_t *out_len
)
456 const char *cp
, *end
;
458 int len
, n_chars
= 0;
460 len
= get_escaped_string_length(start
, in_len_max
, &n_chars
);
464 end
= start
+len
-1; /* Index of last quote. */
465 tor_assert(*end
== '\"');
466 outp
= *out
= tor_malloc(len
+1);
476 tor_assert((outp
- *out
) == (int)*out_len
);
481 /** Acts like sprintf, but writes its formatted string to the end of
482 * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
483 * but it will always end with a CRLF sequence.
485 * Currently the length of the message is limited to 1024 (including the
486 * ending CR LF NUL ("\\r\\n\\0"). */
488 connection_printf_to_buf(control_connection_t
*conn
, const char *format
, ...)
490 #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
492 char buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
];
496 r
= tor_vsnprintf(buf
, sizeof(buf
), format
, ap
);
499 log_warn(LD_BUG
, "Unable to format string for controller.");
503 if (fast_memcmp("\r\n\0", buf
+len
-2, 3)) {
504 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-1] = '\0';
505 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-2] = '\n';
506 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-3] = '\r';
508 connection_write_to_buf(buf
, len
, TO_CONN(conn
));
511 /** Write all of the open control ports to ControlPortWriteToFile */
513 control_ports_write_to_file(void)
517 or_options_t
*options
= get_options();
519 if (!options
->ControlPortWriteToFile
)
522 lines
= smartlist_create();
524 SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t
*, conn
) {
525 char *port_str
= NULL
;
526 if (conn
->type
!= CONN_TYPE_CONTROL_LISTENER
|| conn
->marked_for_close
)
529 if (conn
->socket_family
== AF_UNIX
) {
530 tor_asprintf(&port_str
, "UNIX_PORT=%s\n", conn
->address
);
531 smartlist_add(lines
, port_str
);
535 tor_asprintf(&port_str
, "PORT=%s:%d\n", conn
->address
, conn
->port
);
536 smartlist_add(lines
, port_str
);
537 } SMARTLIST_FOREACH_END(conn
);
539 joined
= smartlist_join_strings(lines
, "", 0, NULL
);
541 if (write_str_to_file(options
->ControlPortWriteToFile
, joined
, 0) < 0) {
542 log_warn(LD_CONTROL
, "Writing %s failed: %s",
543 options
->ControlPortWriteToFile
, strerror(errno
));
546 if (options
->ControlPortFileGroupReadable
) {
547 if (chmod(options
->ControlPortWriteToFile
, 0640)) {
548 log_warn(LD_FS
,"Unable to make %s group-readable.",
549 options
->ControlPortWriteToFile
);
554 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
555 smartlist_free(lines
);
558 /** Send a "DONE" message down the control connection <b>conn</b>. */
560 send_control_done(control_connection_t
*conn
)
562 connection_write_str_to_buf("250 OK\r\n", conn
);
565 /** Send an event to all v1 controllers that are listening for code
566 * <b>event</b>. The event's body is given by <b>msg</b>.
568 * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
569 * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
570 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
571 * to controllers that <em>have</em> enabled VERBOSE_NAMES.
573 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
574 * respect to the EXTENDED_EVENTS feature. */
576 send_control_event_string(uint16_t event
, event_format_t which
,
579 smartlist_t
*conns
= get_connection_array();
581 tor_assert(event
>= _EVENT_MIN
&& event
<= _EVENT_MAX
);
583 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
584 if (conn
->type
== CONN_TYPE_CONTROL
&&
585 !conn
->marked_for_close
&&
586 conn
->state
== CONTROL_CONN_STATE_OPEN
) {
587 control_connection_t
*control_conn
= TO_CONTROL_CONN(conn
);
589 if (control_conn
->event_mask
& (1<<event
)) {
591 connection_write_to_buf(msg
, strlen(msg
), TO_CONN(control_conn
));
592 if (event
== EVENT_ERR_MSG
)
594 else if (event
== EVENT_STATUS_GENERAL
)
595 is_err
= !strcmpstart(msg
, "STATUS_GENERAL ERR ");
596 else if (event
== EVENT_STATUS_CLIENT
)
597 is_err
= !strcmpstart(msg
, "STATUS_CLIENT ERR ");
598 else if (event
== EVENT_STATUS_SERVER
)
599 is_err
= !strcmpstart(msg
, "STATUS_SERVER ERR ");
601 connection_handle_write(TO_CONN(control_conn
), 1);
604 } SMARTLIST_FOREACH_END(conn
);
607 /** Helper for send_control1_event and send_control1_event_extended:
608 * Send an event to all v1 controllers that are listening for code
609 * <b>event</b>. The event's body is created by the printf-style format in
610 * <b>format</b>, and other arguments as provided.
612 * Currently the length of the message is limited to 1024 (including the
613 * ending \\r\\n\\0). */
615 send_control_event_impl(uint16_t event
, event_format_t which
,
616 const char *format
, va_list ap
)
618 /* This is just a little longer than the longest allowed log message */
619 #define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
621 char buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
];
624 r
= tor_vsnprintf(buf
, sizeof(buf
), format
, ap
);
626 log_warn(LD_BUG
, "Unable to format event for controller.");
631 if (fast_memcmp("\r\n\0", buf
+len
-2, 3)) {
632 /* if it is not properly terminated, do it now */
633 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-1] = '\0';
634 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-2] = '\n';
635 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-3] = '\r';
638 send_control_event_string(event
, which
|ALL_FORMATS
, buf
);
641 /** Send an event to all v1 controllers that are listening for code
642 * <b>event</b>. The event's body is created by the printf-style format in
643 * <b>format</b>, and other arguments as provided.
645 * Currently the length of the message is limited to 1024 (including the
646 * ending \\n\\r\\0. */
648 send_control_event(uint16_t event
, event_format_t which
,
649 const char *format
, ...)
652 va_start(ap
, format
);
653 send_control_event_impl(event
, which
, format
, ap
);
657 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
658 static origin_circuit_t
*
659 get_circ(const char *id
)
663 n_id
= (uint32_t) tor_parse_ulong(id
, 10, 0, UINT32_MAX
, &ok
, NULL
);
666 return circuit_get_by_global_id(n_id
);
669 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
670 static edge_connection_t
*
671 get_stream(const char *id
)
676 n_id
= tor_parse_uint64(id
, 10, 0, UINT64_MAX
, &ok
, NULL
);
679 conn
= connection_get_by_global_id(n_id
);
680 if (!conn
|| conn
->type
!= CONN_TYPE_AP
|| conn
->marked_for_close
)
682 return TO_EDGE_CONN(conn
);
685 /** Helper for setconf and resetconf. Acts like setconf, except
686 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
690 control_setconf_helper(control_connection_t
*conn
, uint32_t len
, char *body
,
693 setopt_err_t opt_err
;
694 config_line_t
*lines
=NULL
;
696 char *errstring
= NULL
;
697 const int clear_first
= 1;
700 smartlist_t
*entries
= smartlist_create();
702 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
703 * separated by space. break it into a list of configuration entries. */
708 while (!TOR_ISSPACE(*eq
) && *eq
!= '=')
710 key
= tor_strndup(body
, eq
-body
);
717 char *val_start
= body
;
718 while (!TOR_ISSPACE(*body
))
720 val
= tor_strndup(val_start
, body
-val_start
);
721 val_len
= strlen(val
);
723 body
= (char*)extract_escaped_string(body
, (len
- (body
-start
)),
726 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn
);
727 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
728 smartlist_free(entries
);
733 ent_len
= strlen(key
)+val_len
+3;
734 entry
= tor_malloc(ent_len
+1);
735 tor_snprintf(entry
, ent_len
, "%s %s", key
, val
);
741 smartlist_add(entries
, entry
);
742 while (TOR_ISSPACE(*body
))
746 smartlist_add(entries
, tor_strdup(""));
747 config
= smartlist_join_strings(entries
, "\n", 0, NULL
);
748 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
749 smartlist_free(entries
);
751 if (config_get_lines(config
, &lines
) < 0) {
752 log_warn(LD_CONTROL
,"Controller gave us config lines we can't parse.");
753 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
760 opt_err
= options_trial_assign(lines
, use_defaults
, clear_first
, &errstring
);
764 case SETOPT_ERR_MISC
:
765 msg
= "552 Unrecognized option";
767 case SETOPT_ERR_PARSE
:
768 msg
= "513 Unacceptable option value";
770 case SETOPT_ERR_TRANSITION
:
771 msg
= "553 Transition not allowed";
773 case SETOPT_ERR_SETTING
:
775 msg
= "553 Unable to set option";
778 config_free_lines(lines
);
779 send_control_done(conn
);
783 "Controller gave us config lines that didn't validate: %s",
785 connection_printf_to_buf(conn
, "%s: %s\r\n", msg
, errstring
);
786 config_free_lines(lines
);
792 /** Called when we receive a SETCONF message: parse the body and try
793 * to update our configuration. Reply with a DONE or ERROR message.
794 * Modifies the contents of body.*/
796 handle_control_setconf(control_connection_t
*conn
, uint32_t len
, char *body
)
798 return control_setconf_helper(conn
, len
, body
, 0);
801 /** Called when we receive a RESETCONF message: parse the body and try
802 * to update our configuration. Reply with a DONE or ERROR message.
803 * Modifies the contents of body. */
805 handle_control_resetconf(control_connection_t
*conn
, uint32_t len
, char *body
)
807 return control_setconf_helper(conn
, len
, body
, 1);
810 /** Called when we receive a GETCONF message. Parse the request, and
811 * reply with a CONFVALUE or an ERROR message */
813 handle_control_getconf(control_connection_t
*conn
, uint32_t body_len
,
816 smartlist_t
*questions
= smartlist_create();
817 smartlist_t
*answers
= smartlist_create();
818 smartlist_t
*unrecognized
= smartlist_create();
821 or_options_t
*options
= get_options();
824 (void) body_len
; /* body is NUL-terminated; so we can ignore len. */
825 smartlist_split_string(questions
, body
, " ",
826 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
827 SMARTLIST_FOREACH(questions
, const char *, q
,
829 if (!option_is_recognized(q
)) {
830 smartlist_add(unrecognized
, (char*) q
);
832 config_line_t
*answer
= option_get_assignment(options
,q
);
834 const char *name
= option_get_canonical_name(q
);
835 size_t alen
= strlen(name
)+8;
836 char *astr
= tor_malloc(alen
);
837 tor_snprintf(astr
, alen
, "250-%s\r\n", name
);
838 smartlist_add(answers
, astr
);
843 size_t alen
= strlen(answer
->key
)+strlen(answer
->value
)+8;
844 char *astr
= tor_malloc(alen
);
845 tor_snprintf(astr
, alen
, "250-%s=%s\r\n",
846 answer
->key
, answer
->value
);
847 smartlist_add(answers
, astr
);
850 tor_free(answer
->key
);
851 tor_free(answer
->value
);
858 if ((len
= smartlist_len(unrecognized
))) {
859 for (i
=0; i
< len
-1; ++i
)
860 connection_printf_to_buf(conn
,
861 "552-Unrecognized configuration key \"%s\"\r\n",
862 (char*)smartlist_get(unrecognized
, i
));
863 connection_printf_to_buf(conn
,
864 "552 Unrecognized configuration key \"%s\"\r\n",
865 (char*)smartlist_get(unrecognized
, len
-1));
866 } else if ((len
= smartlist_len(answers
))) {
867 char *tmp
= smartlist_get(answers
, len
-1);
868 tor_assert(strlen(tmp
)>4);
870 msg
= smartlist_join_strings(answers
, "", 0, &msg_len
);
871 connection_write_to_buf(msg
, msg_len
, TO_CONN(conn
));
873 connection_write_str_to_buf("250 OK\r\n", conn
);
876 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
877 smartlist_free(answers
);
878 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
879 smartlist_free(questions
);
880 smartlist_free(unrecognized
);
887 /** Called when we get a +LOADCONF message. */
889 handle_control_loadconf(control_connection_t
*conn
, uint32_t len
,
893 char *errstring
= NULL
;
894 const char *msg
= NULL
;
897 retval
= options_init_from_string(body
, CMD_RUN_TOR
, NULL
, &errstring
);
899 if (retval
!= SETOPT_OK
)
901 "Controller gave us config file that didn't validate: %s",
905 case SETOPT_ERR_PARSE
:
906 msg
= "552 Invalid config file";
908 case SETOPT_ERR_TRANSITION
:
909 msg
= "553 Transition not allowed";
911 case SETOPT_ERR_SETTING
:
912 msg
= "553 Unable to set option";
914 case SETOPT_ERR_MISC
:
916 msg
= "550 Unable to load config";
923 connection_printf_to_buf(conn
, "%s: %s\r\n", msg
, errstring
);
925 connection_printf_to_buf(conn
, "%s\r\n", msg
);
927 send_control_done(conn
);
933 /** Called when we get a SETEVENTS message: update conn->event_mask,
934 * and reply with DONE or ERROR. */
936 handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
940 uint32_t event_mask
= 0;
941 smartlist_t
*events
= smartlist_create();
945 smartlist_split_string(events
, body
, " ",
946 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
947 SMARTLIST_FOREACH_BEGIN(events
, const char *, ev
)
949 if (!strcasecmp(ev
, "EXTENDED")) {
951 } else if (!strcasecmp(ev
, "CIRC"))
952 event_code
= EVENT_CIRCUIT_STATUS
;
953 else if (!strcasecmp(ev
, "STREAM"))
954 event_code
= EVENT_STREAM_STATUS
;
955 else if (!strcasecmp(ev
, "ORCONN"))
956 event_code
= EVENT_OR_CONN_STATUS
;
957 else if (!strcasecmp(ev
, "BW"))
958 event_code
= EVENT_BANDWIDTH_USED
;
959 else if (!strcasecmp(ev
, "DEBUG"))
960 event_code
= EVENT_DEBUG_MSG
;
961 else if (!strcasecmp(ev
, "INFO"))
962 event_code
= EVENT_INFO_MSG
;
963 else if (!strcasecmp(ev
, "NOTICE"))
964 event_code
= EVENT_NOTICE_MSG
;
965 else if (!strcasecmp(ev
, "WARN"))
966 event_code
= EVENT_WARN_MSG
;
967 else if (!strcasecmp(ev
, "ERR"))
968 event_code
= EVENT_ERR_MSG
;
969 else if (!strcasecmp(ev
, "NEWDESC"))
970 event_code
= EVENT_NEW_DESC
;
971 else if (!strcasecmp(ev
, "ADDRMAP"))
972 event_code
= EVENT_ADDRMAP
;
973 else if (!strcasecmp(ev
, "AUTHDIR_NEWDESCS"))
974 event_code
= EVENT_AUTHDIR_NEWDESCS
;
975 else if (!strcasecmp(ev
, "DESCCHANGED"))
976 event_code
= EVENT_DESCCHANGED
;
977 else if (!strcasecmp(ev
, "NS"))
978 event_code
= EVENT_NS
;
979 else if (!strcasecmp(ev
, "STATUS_GENERAL"))
980 event_code
= EVENT_STATUS_GENERAL
;
981 else if (!strcasecmp(ev
, "STATUS_CLIENT"))
982 event_code
= EVENT_STATUS_CLIENT
;
983 else if (!strcasecmp(ev
, "STATUS_SERVER"))
984 event_code
= EVENT_STATUS_SERVER
;
985 else if (!strcasecmp(ev
, "GUARD"))
986 event_code
= EVENT_GUARD
;
987 else if (!strcasecmp(ev
, "STREAM_BW"))
988 event_code
= EVENT_STREAM_BANDWIDTH_USED
;
989 else if (!strcasecmp(ev
, "CLIENTS_SEEN"))
990 event_code
= EVENT_CLIENTS_SEEN
;
991 else if (!strcasecmp(ev
, "NEWCONSENSUS"))
992 event_code
= EVENT_NEWCONSENSUS
;
993 else if (!strcasecmp(ev
, "BUILDTIMEOUT_SET"))
994 event_code
= EVENT_BUILDTIMEOUT_SET
;
996 connection_printf_to_buf(conn
, "552 Unrecognized event \"%s\"\r\n",
998 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
999 smartlist_free(events
);
1002 event_mask
|= (1 << event_code
);
1004 SMARTLIST_FOREACH_END(ev
);
1005 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
1006 smartlist_free(events
);
1008 conn
->event_mask
= event_mask
;
1010 control_update_global_event_mask();
1011 send_control_done(conn
);
1015 /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
1016 * Return a smartlist of acceptable passwords (unterminated strings of
1017 * length S2K_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on failure.
1020 decode_hashed_passwords(config_line_t
*passwords
)
1024 smartlist_t
*sl
= smartlist_create();
1026 tor_assert(passwords
);
1028 for (cl
= passwords
; cl
; cl
= cl
->next
) {
1029 const char *hashed
= cl
->value
;
1031 if (!strcmpstart(hashed
, "16:")) {
1032 if (base16_decode(decoded
, sizeof(decoded
), hashed
+3, strlen(hashed
+3))<0
1033 || strlen(hashed
+3) != (S2K_SPECIFIER_LEN
+DIGEST_LEN
)*2) {
1037 if (base64_decode(decoded
, sizeof(decoded
), hashed
, strlen(hashed
))
1038 != S2K_SPECIFIER_LEN
+DIGEST_LEN
) {
1042 smartlist_add(sl
, tor_memdup(decoded
, S2K_SPECIFIER_LEN
+DIGEST_LEN
));
1048 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
1053 /** Called when we get an AUTHENTICATE message. Check whether the
1054 * authentication is valid, and if so, update the connection's state to
1055 * OPEN. Reply with DONE or ERROR.
1058 handle_control_authenticate(control_connection_t
*conn
, uint32_t len
,
1061 int used_quoted_string
= 0;
1062 or_options_t
*options
= get_options();
1063 const char *errstr
= NULL
;
1065 size_t password_len
;
1068 int bad_cookie
=0, bad_password
=0;
1069 smartlist_t
*sl
= NULL
;
1071 if (TOR_ISXDIGIT(body
[0])) {
1073 while (TOR_ISXDIGIT(*cp
))
1075 i
= (int)(cp
- body
);
1078 password
= tor_malloc(password_len
+ 1);
1079 if (base16_decode(password
, password_len
+1, body
, i
)<0) {
1080 connection_write_str_to_buf(
1081 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1082 "password? If so, the standard requires that you put it in "
1083 "double quotes.\r\n", conn
);
1084 connection_mark_for_close(TO_CONN(conn
));
1088 } else if (TOR_ISSPACE(body
[0])) {
1089 password
= tor_strdup("");
1092 if (!decode_escaped_string(body
, len
, &password
, &password_len
)) {
1093 connection_write_str_to_buf("551 Invalid quoted string. You need "
1094 "to put the password in double quotes.\r\n", conn
);
1095 connection_mark_for_close(TO_CONN(conn
));
1098 used_quoted_string
= 1;
1101 if (!options
->CookieAuthentication
&& !options
->HashedControlPassword
&&
1102 !options
->HashedControlSessionPassword
) {
1103 /* if Tor doesn't demand any stronger authentication, then
1104 * the controller can get in with anything. */
1108 if (options
->CookieAuthentication
) {
1109 int also_password
= options
->HashedControlPassword
!= NULL
||
1110 options
->HashedControlSessionPassword
!= NULL
;
1111 if (password_len
!= AUTHENTICATION_COOKIE_LEN
) {
1112 if (!also_password
) {
1113 log_warn(LD_CONTROL
, "Got authentication cookie with wrong length "
1114 "(%d)", (int)password_len
);
1115 errstr
= "Wrong length on authentication cookie.";
1119 } else if (tor_memneq(authentication_cookie
, password
, password_len
)) {
1120 if (!also_password
) {
1121 log_warn(LD_CONTROL
, "Got mismatched authentication cookie");
1122 errstr
= "Authentication cookie did not match expected value.";
1131 if (options
->HashedControlPassword
||
1132 options
->HashedControlSessionPassword
) {
1134 smartlist_t
*sl_tmp
;
1135 char received
[DIGEST_LEN
];
1136 int also_cookie
= options
->CookieAuthentication
;
1137 sl
= smartlist_create();
1138 if (options
->HashedControlPassword
) {
1139 sl_tmp
= decode_hashed_passwords(options
->HashedControlPassword
);
1143 smartlist_add_all(sl
, sl_tmp
);
1144 smartlist_free(sl_tmp
);
1147 if (options
->HashedControlSessionPassword
) {
1148 sl_tmp
= decode_hashed_passwords(options
->HashedControlSessionPassword
);
1152 smartlist_add_all(sl
, sl_tmp
);
1153 smartlist_free(sl_tmp
);
1158 log_warn(LD_CONTROL
,
1159 "Couldn't decode HashedControlPassword: invalid base16");
1160 errstr
="Couldn't decode HashedControlPassword value in configuration.";
1163 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1166 SMARTLIST_FOREACH(sl
, char *, expected
,
1168 secret_to_key(received
,DIGEST_LEN
,password
,password_len
,expected
);
1169 if (tor_memeq(expected
+S2K_SPECIFIER_LEN
, received
, DIGEST_LEN
))
1172 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1175 if (used_quoted_string
)
1176 errstr
= "Password did not match HashedControlPassword value from "
1179 errstr
= "Password did not match HashedControlPassword value from "
1180 "configuration. Maybe you tried a plain text password? "
1181 "If so, the standard requires that you put it in double quotes.";
1188 /** We only get here if both kinds of authentication failed. */
1189 tor_assert(bad_password
&& bad_cookie
);
1190 log_warn(LD_CONTROL
, "Bad password or authentication cookie on controller.");
1191 errstr
= "Password did not match HashedControlPassword *or* authentication "
1196 connection_printf_to_buf(conn
, "515 Authentication failed: %s\r\n",
1197 errstr
? errstr
: "Unknown reason.");
1198 connection_mark_for_close(TO_CONN(conn
));
1201 log_info(LD_CONTROL
, "Authenticated control connection (%d)", conn
->_base
.s
);
1202 send_control_done(conn
);
1203 conn
->_base
.state
= CONTROL_CONN_STATE_OPEN
;
1205 if (sl
) { /* clean up */
1206 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1212 /** Called when we get a SAVECONF command. Try to flush the current options to
1213 * disk, and report success or failure. */
1215 handle_control_saveconf(control_connection_t
*conn
, uint32_t len
,
1220 if (options_save_current()<0) {
1221 connection_write_str_to_buf(
1222 "551 Unable to write configuration to disk.\r\n", conn
);
1224 send_control_done(conn
);
1229 /** Called when we get a SIGNAL command. React to the provided signal, and
1230 * report success or failure. (If the signal results in a shutdown, success
1231 * may not be reported.) */
1233 handle_control_signal(control_connection_t
*conn
, uint32_t len
,
1242 while (body
[n
] && ! TOR_ISSPACE(body
[n
]))
1244 s
= tor_strndup(body
, n
);
1245 if (!strcasecmp(s
, "RELOAD") || !strcasecmp(s
, "HUP"))
1247 else if (!strcasecmp(s
, "SHUTDOWN") || !strcasecmp(s
, "INT"))
1249 else if (!strcasecmp(s
, "DUMP") || !strcasecmp(s
, "USR1"))
1251 else if (!strcasecmp(s
, "DEBUG") || !strcasecmp(s
, "USR2"))
1253 else if (!strcasecmp(s
, "HALT") || !strcasecmp(s
, "TERM"))
1255 else if (!strcasecmp(s
, "NEWNYM"))
1257 else if (!strcasecmp(s
, "CLEARDNSCACHE"))
1258 sig
= SIGCLEARDNSCACHE
;
1260 connection_printf_to_buf(conn
, "552 Unrecognized signal code \"%s\"\r\n",
1268 send_control_done(conn
);
1269 /* Flush the "done" first if the signal might make us shut down. */
1270 if (sig
== SIGTERM
|| sig
== SIGINT
)
1271 connection_handle_write(TO_CONN(conn
), 1);
1273 process_signal(sig
);
1278 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1279 * and report success or failure. */
1281 handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
1289 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
1291 lines
= smartlist_create();
1292 elts
= smartlist_create();
1293 reply
= smartlist_create();
1294 smartlist_split_string(lines
, body
, " ",
1295 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1296 SMARTLIST_FOREACH(lines
, char *, line
,
1299 smartlist_split_string(elts
, line
, "=", 0, 2);
1300 if (smartlist_len(elts
) == 2) {
1301 const char *from
= smartlist_get(elts
,0);
1302 const char *to
= smartlist_get(elts
,1);
1303 size_t anslen
= strlen(line
)+512;
1304 char *ans
= tor_malloc(anslen
);
1305 if (address_is_invalid_destination(to
, 1)) {
1306 tor_snprintf(ans
, anslen
,
1307 "512-syntax error: invalid address '%s'", to
);
1308 smartlist_add(reply
, ans
);
1309 log_warn(LD_CONTROL
,
1310 "Skipping invalid argument '%s' in MapAddress msg", to
);
1311 } else if (!strcmp(from
, ".") || !strcmp(from
, "0.0.0.0")) {
1312 const char *address
= addressmap_register_virtual_address(
1313 !strcmp(from
,".") ? RESOLVED_TYPE_HOSTNAME
: RESOLVED_TYPE_IPV4
,
1316 tor_snprintf(ans
, anslen
,
1317 "451-resource exhausted: skipping '%s'", line
);
1318 smartlist_add(reply
, ans
);
1319 log_warn(LD_CONTROL
,
1320 "Unable to allocate address for '%s' in MapAddress msg",
1321 safe_str_client(line
));
1323 tor_snprintf(ans
, anslen
, "250-%s=%s", address
, to
);
1324 smartlist_add(reply
, ans
);
1327 addressmap_register(from
, tor_strdup(to
), 1, ADDRMAPSRC_CONTROLLER
);
1328 tor_snprintf(ans
, anslen
, "250-%s", line
);
1329 smartlist_add(reply
, ans
);
1332 size_t anslen
= strlen(line
)+256;
1333 char *ans
= tor_malloc(anslen
);
1334 tor_snprintf(ans
, anslen
, "512-syntax error: mapping '%s' is "
1335 "not of expected form 'foo=bar'.", line
);
1336 smartlist_add(reply
, ans
);
1337 log_info(LD_CONTROL
, "Skipping MapAddress '%s': wrong "
1339 safe_str_client(line
));
1341 SMARTLIST_FOREACH(elts
, char *, cp
, tor_free(cp
));
1342 smartlist_clear(elts
);
1344 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
1345 smartlist_free(lines
);
1346 smartlist_free(elts
);
1348 if (smartlist_len(reply
)) {
1349 ((char*)smartlist_get(reply
,smartlist_len(reply
)-1))[3] = ' ';
1350 r
= smartlist_join_strings(reply
, "\r\n", 1, &sz
);
1351 connection_write_to_buf(r
, sz
, TO_CONN(conn
));
1354 const char *response
=
1355 "512 syntax error: not enough arguments to mapaddress.\r\n";
1356 connection_write_to_buf(response
, strlen(response
), TO_CONN(conn
));
1359 SMARTLIST_FOREACH(reply
, char *, cp
, tor_free(cp
));
1360 smartlist_free(reply
);
1364 /** Implementation helper for GETINFO: knows the answers for various
1365 * trivial-to-implement questions. */
1367 getinfo_helper_misc(control_connection_t
*conn
, const char *question
,
1368 char **answer
, const char **errmsg
)
1371 if (!strcmp(question
, "version")) {
1372 *answer
= tor_strdup(get_version());
1373 } else if (!strcmp(question
, "config-file")) {
1374 *answer
= tor_strdup(get_torrc_fname());
1375 } else if (!strcmp(question
, "config-text")) {
1376 *answer
= options_dump(get_options(), 1);
1377 } else if (!strcmp(question
, "info/names")) {
1378 *answer
= list_getinfo_options();
1379 } else if (!strcmp(question
, "events/names")) {
1380 *answer
= tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
1381 "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
1382 "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
1383 "GUARD STREAM_BW CLIENTS_SEEN NEWCONSENSUS");
1384 } else if (!strcmp(question
, "features/names")) {
1385 *answer
= tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1386 } else if (!strcmp(question
, "address")) {
1388 if (router_pick_published_address(get_options(), &addr
) < 0) {
1389 *errmsg
= "Address unknown";
1392 *answer
= tor_dup_ip(addr
);
1393 } else if (!strcmp(question
, "dir-usage")) {
1394 *answer
= directory_dump_request_log();
1395 } else if (!strcmp(question
, "fingerprint")) {
1396 routerinfo_t
*me
= router_get_my_routerinfo();
1398 *errmsg
= "No routerdesc known; am I really a server?";
1401 *answer
= tor_malloc(HEX_DIGEST_LEN
+1);
1402 base16_encode(*answer
, HEX_DIGEST_LEN
+1, me
->cache_info
.identity_digest
,
1408 /** Awful hack: return a newly allocated string based on a routerinfo and
1409 * (possibly) an extrainfo, sticking the read-history and write-history from
1410 * <b>ei</b> into the resulting string. The thing you get back won't
1411 * necessarily have a valid signature.
1413 * New code should never use this; it's for backward compatibility.
1415 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1416 * not be NUL-terminated. */
1418 munge_extrainfo_into_routerinfo(const char *ri_body
, signed_descriptor_t
*ri
,
1419 signed_descriptor_t
*ei
)
1421 char *out
= NULL
, *outp
;
1423 const char *router_sig
;
1424 const char *ei_body
= signed_descriptor_get_body(ei
);
1425 size_t ri_len
= ri
->signed_descriptor_len
;
1426 size_t ei_len
= ei
->signed_descriptor_len
;
1430 outp
= out
= tor_malloc(ri_len
+ei_len
+1);
1431 if (!(router_sig
= tor_memstr(ri_body
, ri_len
, "\nrouter-signature")))
1434 memcpy(out
, ri_body
, router_sig
-ri_body
);
1435 outp
+= router_sig
-ri_body
;
1437 for (i
=0; i
< 2; ++i
) {
1438 const char *kwd
= i
?"\nwrite-history ":"\nread-history ";
1439 const char *cp
, *eol
;
1440 if (!(cp
= tor_memstr(ei_body
, ei_len
, kwd
)))
1443 eol
= memchr(cp
, '\n', ei_len
- (cp
-ei_body
));
1444 memcpy(outp
, cp
, eol
-cp
+1);
1447 memcpy(outp
, router_sig
, ri_len
- (router_sig
-ri_body
));
1449 tor_assert(outp
-out
< (int)(ri_len
+ei_len
+1));
1454 return tor_strndup(ri_body
, ri
->signed_descriptor_len
);
1457 /** Implementation helper for GETINFO: answers requests for information about
1458 * which ports are bound. */
1460 getinfo_helper_listeners(control_connection_t
*control_conn
,
1461 const char *question
,
1462 char **answer
, const char **errmsg
)
1470 if (!strcmp(question
, "net/listeners/or"))
1471 type
= CONN_TYPE_OR_LISTENER
;
1472 else if (!strcmp(question
, "net/listeners/dir"))
1473 type
= CONN_TYPE_DIR_LISTENER
;
1474 else if (!strcmp(question
, "net/listeners/socks"))
1475 type
= CONN_TYPE_AP_LISTENER
;
1476 else if (!strcmp(question
, "net/listeners/trans"))
1477 type
= CONN_TYPE_AP_TRANS_LISTENER
;
1478 else if (!strcmp(question
, "net/listeners/natd"))
1479 type
= CONN_TYPE_AP_NATD_LISTENER
;
1480 else if (!strcmp(question
, "net/listeners/dns"))
1481 type
= CONN_TYPE_AP_DNS_LISTENER
;
1482 else if (!strcmp(question
, "net/listeners/control"))
1483 type
= CONN_TYPE_CONTROL_LISTENER
;
1485 return 0; /* unknown key */
1487 res
= smartlist_create();
1488 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t
*, conn
) {
1490 struct sockaddr_storage ss
;
1491 socklen_t ss_len
= sizeof(ss
);
1493 if (conn
->type
!= type
|| conn
->marked_for_close
|| !SOCKET_OK(conn
->s
))
1496 if (getsockname(conn
->s
, (struct sockaddr
*)&ss
, &ss_len
) < 0) {
1497 tor_asprintf(&addr
, "%s:%d", conn
->address
, (int)conn
->port
);
1499 char *tmp
= tor_sockaddr_to_str((struct sockaddr
*)&ss
);
1500 addr
= esc_for_log(tmp
);
1504 smartlist_add(res
, addr
);
1505 } SMARTLIST_FOREACH_END(conn
);
1507 *answer
= smartlist_join_strings(res
, " ", 0, NULL
);
1509 SMARTLIST_FOREACH(res
, char *, cp
, tor_free(cp
));
1510 smartlist_free(res
);
1514 /** Implementation helper for GETINFO: knows the answers for questions about
1515 * directory information. */
1517 getinfo_helper_dir(control_connection_t
*control_conn
,
1518 const char *question
, char **answer
,
1519 const char **errmsg
)
1521 (void) control_conn
;
1522 if (!strcmpstart(question
, "desc/id/")) {
1523 routerinfo_t
*ri
= router_get_by_hexdigest(question
+strlen("desc/id/"));
1525 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1527 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
1529 } else if (!strcmpstart(question
, "desc/name/")) {
1530 routerinfo_t
*ri
= router_get_by_nickname(question
+strlen("desc/name/"),1);
1532 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1534 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
1536 } else if (!strcmp(question
, "desc/all-recent")) {
1537 routerlist_t
*routerlist
= router_get_routerlist();
1538 smartlist_t
*sl
= smartlist_create();
1539 if (routerlist
&& routerlist
->routers
) {
1540 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
1542 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1545 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
1548 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
1549 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
1551 } else if (!strcmp(question
, "desc/all-recent-extrainfo-hack")) {
1552 /* XXXX Remove this once Torstat asks for extrainfos. */
1553 routerlist_t
*routerlist
= router_get_routerlist();
1554 smartlist_t
*sl
= smartlist_create();
1555 if (routerlist
&& routerlist
->routers
) {
1556 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
1558 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1559 signed_descriptor_t
*ei
= extrainfo_get_by_descriptor_digest(
1560 ri
->cache_info
.extra_info_digest
);
1562 smartlist_add(sl
, munge_extrainfo_into_routerinfo(body
,
1563 &ri
->cache_info
, ei
));
1566 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 (!strcmpstart(question
, "desc-annotations/id/")) {
1574 routerinfo_t
*ri
= router_get_by_hexdigest(question
+
1575 strlen("desc-annotations/id/"));
1577 const char *annotations
=
1578 signed_descriptor_get_annotations(&ri
->cache_info
);
1580 *answer
= tor_strndup(annotations
,
1581 ri
->cache_info
.annotations_len
);
1583 } else if (!strcmpstart(question
, "dir/server/")) {
1584 size_t answer_len
= 0, url_len
= strlen(question
)+2;
1585 char *url
= tor_malloc(url_len
);
1586 smartlist_t
*descs
= smartlist_create();
1590 tor_snprintf(url
, url_len
, "/tor/%s", question
+4);
1591 res
= dirserv_get_routerdescs(descs
, url
, &msg
);
1593 log_warn(LD_CONTROL
, "getinfo '%s': %s", question
, msg
);
1594 smartlist_free(descs
);
1599 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
1600 answer_len
+= sd
->signed_descriptor_len
);
1601 cp
= *answer
= tor_malloc(answer_len
+1);
1602 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
1604 memcpy(cp
, signed_descriptor_get_body(sd
),
1605 sd
->signed_descriptor_len
);
1606 cp
+= sd
->signed_descriptor_len
;
1610 smartlist_free(descs
);
1611 } else if (!strcmpstart(question
, "dir/status/")) {
1612 if (directory_permits_controller_requests(get_options())) {
1615 smartlist_t
*status_list
= smartlist_create();
1616 dirserv_get_networkstatus_v2(status_list
,
1617 question
+strlen("dir/status/"));
1618 SMARTLIST_FOREACH(status_list
, cached_dir_t
*, d
, len
+= d
->dir_len
);
1619 cp
= *answer
= tor_malloc(len
+1);
1620 SMARTLIST_FOREACH(status_list
, cached_dir_t
*, d
, {
1621 memcpy(cp
, d
->dir
, d
->dir_len
);
1625 smartlist_free(status_list
);
1627 smartlist_t
*fp_list
= smartlist_create();
1628 smartlist_t
*status_list
= smartlist_create();
1629 dirserv_get_networkstatus_v2_fingerprints(
1630 fp_list
, question
+strlen("dir/status/"));
1631 SMARTLIST_FOREACH(fp_list
, const char *, fp
, {
1633 char *fname
= networkstatus_get_cache_filename(fp
);
1634 s
= read_file_to_str(fname
, 0, NULL
);
1636 smartlist_add(status_list
, s
);
1639 SMARTLIST_FOREACH(fp_list
, char *, fp
, tor_free(fp
));
1640 smartlist_free(fp_list
);
1641 *answer
= smartlist_join_strings(status_list
, "", 0, NULL
);
1642 SMARTLIST_FOREACH(status_list
, char *, s
, tor_free(s
));
1643 smartlist_free(status_list
);
1645 } else if (!strcmp(question
, "dir/status-vote/current/consensus")) { /* v3 */
1646 if (directory_caches_dir_info(get_options())) {
1647 const cached_dir_t
*consensus
= dirserv_get_consensus("ns");
1649 *answer
= tor_strdup(consensus
->dir
);
1651 if (!*answer
) { /* try loading it from disk */
1652 char *filename
= get_datadir_fname("cached-consensus");
1653 *answer
= read_file_to_str(filename
, RFTS_IGNORE_MISSING
, NULL
);
1656 } else if (!strcmp(question
, "network-status")) { /* v1 */
1657 routerlist_t
*routerlist
= router_get_routerlist();
1658 if (!routerlist
|| !routerlist
->routers
||
1659 list_server_status_v1(routerlist
->routers
, answer
, 1) < 0) {
1662 } else if (!strcmpstart(question
, "extra-info/digest/")) {
1663 question
+= strlen("extra-info/digest/");
1664 if (strlen(question
) == HEX_DIGEST_LEN
) {
1666 signed_descriptor_t
*sd
= NULL
;
1667 if (base16_decode(d
, sizeof(d
), question
, strlen(question
))==0) {
1668 /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
1669 * but I don't want to risk affecting other parts of the code,
1670 * especially since the rules for using our own extrainfo (including
1671 * when it might be freed) are different from those for using one
1672 * we have downloaded. */
1673 if (router_extrainfo_digest_is_me(d
))
1674 sd
= &(router_get_my_extrainfo()->cache_info
);
1676 sd
= extrainfo_get_by_descriptor_digest(d
);
1679 const char *body
= signed_descriptor_get_body(sd
);
1681 *answer
= tor_strndup(body
, sd
->signed_descriptor_len
);
1689 /** Implementation helper for GETINFO: knows how to generate summaries of the
1690 * current states of things we send events about. */
1692 getinfo_helper_events(control_connection_t
*control_conn
,
1693 const char *question
, char **answer
,
1694 const char **errmsg
)
1696 (void) control_conn
;
1697 if (!strcmp(question
, "circuit-status")) {
1699 smartlist_t
*status
= smartlist_create();
1700 for (circ
= _circuit_get_global_list(); circ
; circ
= circ
->next
) {
1704 const char *purpose
;
1705 if (! CIRCUIT_IS_ORIGIN(circ
) || circ
->marked_for_close
)
1708 path
= circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ
));
1710 if (circ
->state
== CIRCUIT_STATE_OPEN
)
1712 else if (strlen(path
))
1717 purpose
= circuit_purpose_to_controller_string(circ
->purpose
);
1718 slen
= strlen(path
)+strlen(state
)+strlen(purpose
)+30;
1719 s
= tor_malloc(slen
+1);
1720 tor_snprintf(s
, slen
, "%lu %s%s%s PURPOSE=%s",
1721 (unsigned long)TO_ORIGIN_CIRCUIT(circ
)->global_identifier
,
1722 state
, *path
? " " : "", path
, purpose
);
1723 smartlist_add(status
, s
);
1726 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1727 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1728 smartlist_free(status
);
1729 } else if (!strcmp(question
, "stream-status")) {
1730 smartlist_t
*conns
= get_connection_array();
1731 smartlist_t
*status
= smartlist_create();
1733 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
1735 edge_connection_t
*conn
;
1739 origin_circuit_t
*origin_circ
= NULL
;
1740 if (base_conn
->type
!= CONN_TYPE_AP
||
1741 base_conn
->marked_for_close
||
1742 base_conn
->state
== AP_CONN_STATE_SOCKS_WAIT
||
1743 base_conn
->state
== AP_CONN_STATE_NATD_WAIT
)
1745 conn
= TO_EDGE_CONN(base_conn
);
1746 switch (conn
->_base
.state
)
1748 case AP_CONN_STATE_CONTROLLER_WAIT
:
1749 case AP_CONN_STATE_CIRCUIT_WAIT
:
1750 if (conn
->socks_request
&&
1751 SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
))
1752 state
= "NEWRESOLVE";
1756 case AP_CONN_STATE_RENDDESC_WAIT
:
1757 case AP_CONN_STATE_CONNECT_WAIT
:
1758 state
= "SENTCONNECT"; break;
1759 case AP_CONN_STATE_RESOLVE_WAIT
:
1760 state
= "SENTRESOLVE"; break;
1761 case AP_CONN_STATE_OPEN
:
1762 state
= "SUCCEEDED"; break;
1764 log_warn(LD_BUG
, "Asked for stream in unknown state %d",
1768 circ
= circuit_get_by_edge_conn(conn
);
1769 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
1770 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
1771 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
1772 slen
= strlen(buf
)+strlen(state
)+32;
1773 s
= tor_malloc(slen
+1);
1774 tor_snprintf(s
, slen
, "%lu %s %lu %s",
1775 (unsigned long) conn
->_base
.global_identifier
,state
,
1777 (unsigned long)origin_circ
->global_identifier
: 0ul,
1779 smartlist_add(status
, s
);
1780 } SMARTLIST_FOREACH_END(base_conn
);
1781 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1782 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1783 smartlist_free(status
);
1784 } else if (!strcmp(question
, "orconn-status")) {
1785 smartlist_t
*conns
= get_connection_array();
1786 smartlist_t
*status
= smartlist_create();
1787 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
1792 or_connection_t
*conn
;
1793 if (base_conn
->type
!= CONN_TYPE_OR
|| base_conn
->marked_for_close
)
1795 conn
= TO_OR_CONN(base_conn
);
1796 if (conn
->_base
.state
== OR_CONN_STATE_OPEN
)
1797 state
= "CONNECTED";
1798 else if (conn
->nickname
)
1802 orconn_target_get_name(name
, sizeof(name
), conn
);
1803 slen
= strlen(name
)+strlen(state
)+2;
1804 s
= tor_malloc(slen
+1);
1805 tor_snprintf(s
, slen
, "%s %s", name
, state
);
1806 smartlist_add(status
, s
);
1807 } SMARTLIST_FOREACH_END(base_conn
);
1808 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1809 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1810 smartlist_free(status
);
1811 } else if (!strcmpstart(question
, "address-mappings/")) {
1812 time_t min_e
, max_e
;
1813 smartlist_t
*mappings
;
1814 question
+= strlen("address-mappings/");
1815 if (!strcmp(question
, "all")) {
1816 min_e
= 0; max_e
= TIME_MAX
;
1817 } else if (!strcmp(question
, "cache")) {
1818 min_e
= 2; max_e
= TIME_MAX
;
1819 } else if (!strcmp(question
, "config")) {
1820 min_e
= 0; max_e
= 0;
1821 } else if (!strcmp(question
, "control")) {
1822 min_e
= 1; max_e
= 1;
1826 mappings
= smartlist_create();
1827 addressmap_get_mappings(mappings
, min_e
, max_e
, 1);
1828 *answer
= smartlist_join_strings(mappings
, "\r\n", 0, NULL
);
1829 SMARTLIST_FOREACH(mappings
, char *, cp
, tor_free(cp
));
1830 smartlist_free(mappings
);
1831 } else if (!strcmpstart(question
, "status/")) {
1832 /* Note that status/ is not a catch-all for events; there's only supposed
1833 * to be a status GETINFO if there's a corresponding STATUS event. */
1834 if (!strcmp(question
, "status/circuit-established")) {
1835 *answer
= tor_strdup(can_complete_circuit
? "1" : "0");
1836 } else if (!strcmp(question
, "status/enough-dir-info")) {
1837 *answer
= tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
1838 } else if (!strcmp(question
, "status/good-server-descriptor") ||
1839 !strcmp(question
, "status/accepted-server-descriptor")) {
1840 /* They're equivalent for now, until we can figure out how to make
1841 * good-server-descriptor be what we want. See comment in
1842 * control-spec.txt. */
1843 *answer
= tor_strdup(directories_have_accepted_server_descriptor()
1845 } else if (!strcmp(question
, "status/reachability-succeeded/or")) {
1846 *answer
= tor_strdup(check_whether_orport_reachable() ? "1" : "0");
1847 } else if (!strcmp(question
, "status/reachability-succeeded/dir")) {
1848 *answer
= tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
1849 } else if (!strcmp(question
, "status/reachability-succeeded")) {
1850 *answer
= tor_malloc(16);
1851 tor_snprintf(*answer
, 16, "OR=%d DIR=%d",
1852 check_whether_orport_reachable() ? 1 : 0,
1853 check_whether_dirport_reachable() ? 1 : 0);
1854 } else if (!strcmp(question
, "status/bootstrap-phase")) {
1855 *answer
= tor_strdup(last_sent_bootstrap_message
);
1856 } else if (!strcmpstart(question
, "status/version/")) {
1857 int is_server
= server_mode(get_options());
1858 networkstatus_t
*c
= networkstatus_get_latest_consensus();
1859 version_status_t status
;
1860 const char *recommended
;
1862 recommended
= is_server
? c
->server_versions
: c
->client_versions
;
1863 status
= tor_version_is_obsolete(VERSION
, recommended
);
1866 status
= VS_UNKNOWN
;
1869 if (!strcmp(question
, "status/version/recommended")) {
1870 *answer
= tor_strdup(recommended
);
1873 if (!strcmp(question
, "status/version/current")) {
1876 case VS_RECOMMENDED
: *answer
= tor_strdup("recommended"); break;
1877 case VS_OLD
: *answer
= tor_strdup("obsolete"); break;
1878 case VS_NEW
: *answer
= tor_strdup("new"); break;
1879 case VS_NEW_IN_SERIES
: *answer
= tor_strdup("new in series"); break;
1880 case VS_UNRECOMMENDED
: *answer
= tor_strdup("unrecommended"); break;
1881 case VS_EMPTY
: *answer
= tor_strdup("none recommended"); break;
1882 case VS_UNKNOWN
: *answer
= tor_strdup("unknown"); break;
1883 default: tor_fragile_assert();
1885 } else if (!strcmp(question
, "status/version/num-versioning") ||
1886 !strcmp(question
, "status/version/num-concurring")) {
1888 tor_snprintf(s
, sizeof(s
), "%d", get_n_authorities(V3_AUTHORITY
));
1889 *answer
= tor_strdup(s
);
1890 log_warn(LD_GENERAL
, "%s is deprecated; it no longer gives useful "
1891 "information", question
);
1893 } else if (!strcmp(question
, "status/clients-seen")) {
1894 char *bridge_stats
= geoip_get_bridge_stats_controller(time(NULL
));
1895 if (!bridge_stats
) {
1896 *errmsg
= "No bridge-client stats available";
1899 *answer
= bridge_stats
;
1907 /** Callback function for GETINFO: on a given control connection, try to
1908 * answer the question <b>q</b> and store the newly-allocated answer in
1909 * *<b>a</b>. If an internal error occurs, return -1 and optionally set
1910 * *<b>error_out</b> to point to an error message to be delivered to the
1911 * controller. On success, _or if the key is not recognized_, return 0. Do not
1912 * set <b>a</b> if the key is not recognized.
1914 typedef int (*getinfo_helper_t
)(control_connection_t
*,
1915 const char *q
, char **a
,
1916 const char **error_out
);
1918 /** A single item for the GETINFO question-to-answer-function table. */
1919 typedef struct getinfo_item_t
{
1920 const char *varname
; /**< The value (or prefix) of the question. */
1921 getinfo_helper_t fn
; /**< The function that knows the answer: NULL if
1922 * this entry is documentation-only. */
1923 const char *desc
; /**< Description of the variable. */
1924 int is_prefix
; /** Must varname match exactly, or must it be a prefix? */
1927 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
1928 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
1929 #define DOC(name, desc) { name, NULL, desc, 0 }
1931 /** Table mapping questions accepted by GETINFO to the functions that know how
1932 * to answer them. */
1933 static const getinfo_item_t getinfo_items
[] = {
1934 ITEM("version", misc
, "The current version of Tor."),
1935 ITEM("config-file", misc
, "Current location of the \"torrc\" file."),
1936 ITEM("config-text", misc
,
1937 "Return the string that would be written by a saveconf command."),
1938 ITEM("accounting/bytes", accounting
,
1939 "Number of bytes read/written so far in the accounting interval."),
1940 ITEM("accounting/bytes-left", accounting
,
1941 "Number of bytes left to write/read so far in the accounting interval."),
1942 ITEM("accounting/enabled", accounting
, "Is accounting currently enabled?"),
1943 ITEM("accounting/hibernating", accounting
, "Are we hibernating or awake?"),
1944 ITEM("accounting/interval-start", accounting
,
1945 "Time when the accounting period starts."),
1946 ITEM("accounting/interval-end", accounting
,
1947 "Time when the accounting period ends."),
1948 ITEM("accounting/interval-wake", accounting
,
1949 "Time to wake up in this accounting period."),
1950 ITEM("helper-nodes", entry_guards
, NULL
), /* deprecated */
1951 ITEM("entry-guards", entry_guards
,
1952 "Which nodes are we using as entry guards?"),
1953 ITEM("fingerprint", misc
, NULL
),
1954 PREFIX("config/", config
, "Current configuration values."),
1956 "List of configuration options, types, and documentation."),
1957 ITEM("info/names", misc
,
1958 "List of GETINFO options, types, and documentation."),
1959 ITEM("events/names", misc
,
1960 "Events that the controller can ask for with SETEVENTS."),
1961 ITEM("features/names", misc
, "What arguments can USEFEATURE take?"),
1962 PREFIX("desc/id/", dir
, "Router descriptors by ID."),
1963 PREFIX("desc/name/", dir
, "Router descriptors by nickname."),
1964 ITEM("desc/all-recent", dir
,
1965 "All non-expired, non-superseded router descriptors."),
1966 ITEM("desc/all-recent-extrainfo-hack", dir
, NULL
), /* Hack. */
1967 PREFIX("extra-info/digest/", dir
, "Extra-info documents by digest."),
1968 PREFIX("net/listeners/", listeners
, "Bound addresses by type"),
1969 ITEM("ns/all", networkstatus
,
1970 "Brief summary of router status (v2 directory format)"),
1971 PREFIX("ns/id/", networkstatus
,
1972 "Brief summary of router status by ID (v2 directory format)."),
1973 PREFIX("ns/name/", networkstatus
,
1974 "Brief summary of router status by nickname (v2 directory format)."),
1975 PREFIX("ns/purpose/", networkstatus
,
1976 "Brief summary of router status by purpose (v2 directory format)."),
1978 ITEM("network-status", dir
,
1979 "Brief summary of router status (v1 directory format)"),
1980 ITEM("circuit-status", events
, "List of current circuits originating here."),
1981 ITEM("stream-status", events
,"List of current streams."),
1982 ITEM("orconn-status", events
, "A list of current OR connections."),
1983 PREFIX("address-mappings/", events
, NULL
),
1984 DOC("address-mappings/all", "Current address mappings."),
1985 DOC("address-mappings/cache", "Current cached DNS replies."),
1986 DOC("address-mappings/config",
1987 "Current address mappings from configuration."),
1988 DOC("address-mappings/control", "Current address mappings from controller."),
1989 PREFIX("status/", events
, NULL
),
1990 DOC("status/circuit-established",
1991 "Whether we think client functionality is working."),
1992 DOC("status/enough-dir-info",
1993 "Whether we have enough up-to-date directory information to build "
1995 DOC("status/bootstrap-phase",
1996 "The last bootstrap phase status event that Tor sent."),
1997 DOC("status/clients-seen",
1998 "Breakdown of client countries seen by a bridge."),
1999 DOC("status/version/recommended", "List of currently recommended versions."),
2000 DOC("status/version/current", "Status of the current version."),
2001 DOC("status/version/num-versioning", "Number of versioning authorities."),
2002 DOC("status/version/num-concurring",
2003 "Number of versioning authorities agreeing on the status of the "
2005 ITEM("address", misc
, "IP address of this Tor host, if we can guess it."),
2006 ITEM("dir-usage", misc
, "Breakdown of bytes transferred over DirPort."),
2007 PREFIX("desc-annotations/id/", dir
, "Router annotations by hexdigest."),
2008 PREFIX("dir/server/", dir
,"Router descriptors as retrieved from a DirPort."),
2009 PREFIX("dir/status/", dir
,
2010 "v2 networkstatus docs as retrieved from a DirPort."),
2011 ITEM("dir/status-vote/current/consensus", dir
,
2012 "v3 Networkstatus consensus as retrieved from a DirPort."),
2013 PREFIX("exit-policy/default", policies
,
2014 "The default value appended to the configured exit policy."),
2015 PREFIX("ip-to-country/", geoip
, "Perform a GEOIP lookup"),
2016 { NULL
, NULL
, NULL
, 0 }
2019 /** Allocate and return a list of recognized GETINFO options. */
2021 list_getinfo_options(void)
2025 smartlist_t
*lines
= smartlist_create();
2027 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
2028 if (!getinfo_items
[i
].desc
)
2031 tor_asprintf(&buf
, "%s%s -- %s\n",
2032 getinfo_items
[i
].varname
,
2033 getinfo_items
[i
].is_prefix
? "*" : "",
2034 getinfo_items
[i
].desc
);
2035 smartlist_add(lines
, buf
);
2037 smartlist_sort_strings(lines
);
2039 ans
= smartlist_join_strings(lines
, "", 0, NULL
);
2040 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
2041 smartlist_free(lines
);
2046 /** Lookup the 'getinfo' entry <b>question</b>, and return
2047 * the answer in <b>*answer</b> (or NULL if key not recognized).
2048 * Return 0 if success or unrecognized, or -1 if recognized but
2049 * internal error. */
2051 handle_getinfo_helper(control_connection_t
*control_conn
,
2052 const char *question
, char **answer
,
2053 const char **err_out
)
2056 *answer
= NULL
; /* unrecognized key by default */
2058 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
2060 if (getinfo_items
[i
].is_prefix
)
2061 match
= !strcmpstart(question
, getinfo_items
[i
].varname
);
2063 match
= !strcmp(question
, getinfo_items
[i
].varname
);
2065 tor_assert(getinfo_items
[i
].fn
);
2066 return getinfo_items
[i
].fn(control_conn
, question
, answer
, err_out
);
2070 return 0; /* unrecognized */
2073 /** Called when we receive a GETINFO command. Try to fetch all requested
2074 * information, and reply with information or error message. */
2076 handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
2079 smartlist_t
*questions
= smartlist_create();
2080 smartlist_t
*answers
= smartlist_create();
2081 smartlist_t
*unrecognized
= smartlist_create();
2082 char *msg
= NULL
, *ans
= NULL
;
2084 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
2086 smartlist_split_string(questions
, body
, " ",
2087 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2088 SMARTLIST_FOREACH_BEGIN(questions
, const char *, q
) {
2089 const char *errmsg
= NULL
;
2090 if (handle_getinfo_helper(conn
, q
, &ans
, &errmsg
) < 0) {
2092 errmsg
= "Internal error";
2093 connection_printf_to_buf(conn
, "551 %s\r\n", errmsg
);
2097 smartlist_add(unrecognized
, (char*)q
);
2099 smartlist_add(answers
, tor_strdup(q
));
2100 smartlist_add(answers
, ans
);
2102 } SMARTLIST_FOREACH_END(q
);
2103 if (smartlist_len(unrecognized
)) {
2104 for (i
=0; i
< smartlist_len(unrecognized
)-1; ++i
)
2105 connection_printf_to_buf(conn
,
2106 "552-Unrecognized key \"%s\"\r\n",
2107 (char*)smartlist_get(unrecognized
, i
));
2108 connection_printf_to_buf(conn
,
2109 "552 Unrecognized key \"%s\"\r\n",
2110 (char*)smartlist_get(unrecognized
, i
));
2114 for (i
= 0; i
< smartlist_len(answers
); i
+= 2) {
2115 char *k
= smartlist_get(answers
, i
);
2116 char *v
= smartlist_get(answers
, i
+1);
2117 if (!strchr(v
, '\n') && !strchr(v
, '\r')) {
2118 connection_printf_to_buf(conn
, "250-%s=", k
);
2119 connection_write_str_to_buf(v
, conn
);
2120 connection_write_str_to_buf("\r\n", conn
);
2124 esc_len
= write_escaped_data(v
, strlen(v
), &esc
);
2125 connection_printf_to_buf(conn
, "250+%s=\r\n", k
);
2126 connection_write_to_buf(esc
, esc_len
, TO_CONN(conn
));
2130 connection_write_str_to_buf("250 OK\r\n", conn
);
2133 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
2134 smartlist_free(answers
);
2135 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
2136 smartlist_free(questions
);
2137 smartlist_free(unrecognized
);
2143 /** Given a string, convert it to a circuit purpose. */
2145 circuit_purpose_from_string(const char *string
)
2147 if (!strcasecmpstart(string
, "purpose="))
2148 string
+= strlen("purpose=");
2150 if (!strcasecmp(string
, "general"))
2151 return CIRCUIT_PURPOSE_C_GENERAL
;
2152 else if (!strcasecmp(string
, "controller"))
2153 return CIRCUIT_PURPOSE_CONTROLLER
;
2155 return CIRCUIT_PURPOSE_UNKNOWN
;
2158 /** Return a newly allocated smartlist containing the arguments to the command
2159 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
2160 * or if <b>max_args</b> is nonnegative and there are more than
2161 * <b>max_args</b> arguments, send a 512 error to the controller, using
2162 * <b>command</b> as the command name in the error message. */
2163 static smartlist_t
*
2164 getargs_helper(const char *command
, control_connection_t
*conn
,
2165 const char *body
, int min_args
, int max_args
)
2167 smartlist_t
*args
= smartlist_create();
2168 smartlist_split_string(args
, body
, " ",
2169 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2170 if (smartlist_len(args
) < min_args
) {
2171 connection_printf_to_buf(conn
, "512 Missing argument to %s\r\n",command
);
2173 } else if (max_args
>= 0 && smartlist_len(args
) > max_args
) {
2174 connection_printf_to_buf(conn
, "512 Too many arguments to %s\r\n",command
);
2179 SMARTLIST_FOREACH(args
, char *, s
, tor_free(s
));
2180 smartlist_free(args
);
2184 /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
2185 * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
2186 * such element exists. */
2188 find_element_starting_with(smartlist_t
*sl
, int start_at
, const char *prefix
)
2191 for (i
= start_at
; i
< smartlist_len(sl
); ++i
) {
2192 const char *elt
= smartlist_get(sl
, i
);
2193 if (!strcasecmpstart(elt
, prefix
))
2199 /** Helper. Return true iff s is an argument that we should treat as a
2200 * key-value pair. */
2202 is_keyval_pair(const char *s
)
2204 /* An argument is a key-value pair if it has an =, and it isn't of the form
2205 * $fingeprint=name */
2206 return strchr(s
, '=') && s
[0] != '$';
2209 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
2210 * circuit, and report success or failure. */
2212 handle_control_extendcircuit(control_connection_t
*conn
, uint32_t len
,
2215 smartlist_t
*router_nicknames
=NULL
, *routers
=NULL
;
2216 origin_circuit_t
*circ
= NULL
;
2218 uint8_t intended_purpose
= CIRCUIT_PURPOSE_C_GENERAL
;
2222 router_nicknames
= smartlist_create();
2224 args
= getargs_helper("EXTENDCIRCUIT", conn
, body
, 1, -1);
2228 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,0));
2231 const char *purp
= find_element_starting_with(args
, 1, "PURPOSE=");
2234 intended_purpose
= circuit_purpose_from_string(purp
);
2235 if (intended_purpose
== CIRCUIT_PURPOSE_UNKNOWN
) {
2236 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
2237 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2238 smartlist_free(args
);
2243 if ((smartlist_len(args
) == 1) ||
2244 (smartlist_len(args
) >= 2 && is_keyval_pair(smartlist_get(args
, 1)))) {
2245 // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
2246 circ
= circuit_launch_by_router(intended_purpose
, NULL
,
2247 CIRCLAUNCH_NEED_CAPACITY
);
2249 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
2251 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
2252 (unsigned long)circ
->global_identifier
);
2254 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2255 smartlist_free(args
);
2258 // "EXTENDCIRCUIT 0 router1,router2" ||
2259 // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
2262 if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
,0)))) {
2263 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2264 (char*)smartlist_get(args
, 0));
2265 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2266 smartlist_free(args
);
2270 smartlist_split_string(router_nicknames
, smartlist_get(args
,1), ",", 0, 0);
2272 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2273 smartlist_free(args
);
2275 routers
= smartlist_create();
2276 SMARTLIST_FOREACH(router_nicknames
, const char *, n
,
2278 routerinfo_t
*r
= router_get_by_nickname(n
, 1);
2280 connection_printf_to_buf(conn
, "552 No such router \"%s\"\r\n", n
);
2283 smartlist_add(routers
, r
);
2285 if (!smartlist_len(routers
)) {
2286 connection_write_str_to_buf("512 No router names provided\r\n", conn
);
2291 /* start a new circuit */
2292 circ
= origin_circuit_init(intended_purpose
, 0);
2295 /* now circ refers to something that is ready to be extended */
2296 SMARTLIST_FOREACH(routers
, routerinfo_t
*, r
,
2298 extend_info_t
*info
= extend_info_from_router(r
);
2299 circuit_append_new_exit(circ
, info
);
2300 extend_info_free(info
);
2303 /* now that we've populated the cpath, start extending */
2306 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
2307 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
2308 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
2312 if (circ
->_base
.state
== CIRCUIT_STATE_OPEN
) {
2314 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
2315 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
2316 log_info(LD_CONTROL
,
2317 "send_next_onion_skin failed; circuit marked for closing.");
2318 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
2319 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn
);
2325 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
2326 (unsigned long)circ
->global_identifier
);
2327 if (zero_circ
) /* send a 'launched' event, for completeness */
2328 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
2330 SMARTLIST_FOREACH(router_nicknames
, char *, n
, tor_free(n
));
2331 smartlist_free(router_nicknames
);
2332 smartlist_free(routers
);
2336 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
2337 * circuit and it's a valid purpose, change it. */
2339 handle_control_setcircuitpurpose(control_connection_t
*conn
,
2340 uint32_t len
, const char *body
)
2342 origin_circuit_t
*circ
= NULL
;
2343 uint8_t new_purpose
;
2345 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
2347 args
= getargs_helper("SETCIRCUITPURPOSE", conn
, body
, 2, -1);
2351 if (!(circ
= get_circ(smartlist_get(args
,0)))) {
2352 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2353 (char*)smartlist_get(args
, 0));
2358 const char *purp
= find_element_starting_with(args
,1,"PURPOSE=");
2359 new_purpose
= circuit_purpose_from_string(purp
);
2360 if (new_purpose
== CIRCUIT_PURPOSE_UNKNOWN
) {
2361 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
2366 circ
->_base
.purpose
= new_purpose
;
2367 connection_write_str_to_buf("250 OK\r\n", conn
);
2371 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2372 smartlist_free(args
);
2377 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
2378 * stream, and report success or failure. */
2380 handle_control_attachstream(control_connection_t
*conn
, uint32_t len
,
2383 edge_connection_t
*ap_conn
= NULL
;
2384 origin_circuit_t
*circ
= NULL
;
2387 crypt_path_t
*cpath
=NULL
;
2388 int hop
=0, hop_line_ok
=1;
2391 args
= getargs_helper("ATTACHSTREAM", conn
, body
, 2, -1);
2395 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,1));
2397 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))) {
2398 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2399 (char*)smartlist_get(args
, 0));
2400 } else if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
, 1)))) {
2401 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2402 (char*)smartlist_get(args
, 1));
2404 const char *hopstring
= find_element_starting_with(args
,2,"HOP=");
2406 hopstring
+= strlen("HOP=");
2407 hop
= (int) tor_parse_ulong(hopstring
, 10, 0, INT_MAX
,
2408 &hop_line_ok
, NULL
);
2409 if (!hop_line_ok
) { /* broken hop line */
2410 connection_printf_to_buf(conn
, "552 Bad value hop=%s\r\n", hopstring
);
2414 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2415 smartlist_free(args
);
2416 if (!ap_conn
|| (!zero_circ
&& !circ
) || !hop_line_ok
)
2419 if (ap_conn
->_base
.state
!= AP_CONN_STATE_CONTROLLER_WAIT
&&
2420 ap_conn
->_base
.state
!= AP_CONN_STATE_CONNECT_WAIT
&&
2421 ap_conn
->_base
.state
!= AP_CONN_STATE_RESOLVE_WAIT
) {
2422 connection_write_str_to_buf(
2423 "555 Connection is not managed by controller.\r\n",
2428 /* Do we need to detach it first? */
2429 if (ap_conn
->_base
.state
!= AP_CONN_STATE_CONTROLLER_WAIT
) {
2430 circuit_t
*tmpcirc
= circuit_get_by_edge_conn(ap_conn
);
2431 connection_edge_end(ap_conn
, END_STREAM_REASON_TIMEOUT
);
2432 /* Un-mark it as ending, since we're going to reuse it. */
2433 ap_conn
->edge_has_sent_end
= 0;
2434 ap_conn
->end_reason
= 0;
2436 circuit_detach_stream(tmpcirc
,ap_conn
);
2437 ap_conn
->_base
.state
= AP_CONN_STATE_CONTROLLER_WAIT
;
2440 if (circ
&& (circ
->_base
.state
!= CIRCUIT_STATE_OPEN
)) {
2441 connection_write_str_to_buf(
2442 "551 Can't attach stream to non-open origin circuit\r\n",
2446 /* Is this a single hop circuit? */
2447 if (circ
&& (circuit_get_cpath_len(circ
)<2 || hop
==1)) {
2448 routerinfo_t
*r
= NULL
;
2450 if (circ
->build_state
&&
2451 circ
->build_state
->chosen_exit
&&
2452 !tor_digest_is_zero(circ
->build_state
->chosen_exit
->identity_digest
)) {
2453 exit_digest
= circ
->build_state
->chosen_exit
->identity_digest
;
2454 r
= router_get_by_digest(exit_digest
);
2456 /* Do both the client and relay allow one-hop exit circuits? */
2457 if (!r
|| !r
->allow_single_hop_exits
||
2458 !get_options()->AllowSingleHopCircuits
) {
2459 connection_write_str_to_buf(
2460 "551 Can't attach stream to this one-hop circuit.\r\n", conn
);
2463 ap_conn
->chosen_exit_name
= tor_strdup(hex_str(exit_digest
, DIGEST_LEN
));
2466 if (circ
&& hop
>0) {
2467 /* find this hop in the circuit, and set cpath */
2468 cpath
= circuit_get_cpath_hop(circ
, hop
);
2470 connection_printf_to_buf(conn
,
2471 "551 Circuit doesn't have %d hops.\r\n", hop
);
2475 if (connection_ap_handshake_rewrite_and_attach(ap_conn
, circ
, cpath
) < 0) {
2476 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn
);
2479 send_control_done(conn
);
2483 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
2484 * descriptor, and report success or failure. */
2486 handle_control_postdescriptor(control_connection_t
*conn
, uint32_t len
,
2490 const char *msg
=NULL
;
2491 uint8_t purpose
= ROUTER_PURPOSE_GENERAL
;
2492 int cache
= 0; /* eventually, we may switch this to 1 */
2494 char *cp
= memchr(body
, '\n', len
);
2495 smartlist_t
*args
= smartlist_create();
2499 smartlist_split_string(args
, body
, " ",
2500 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2501 SMARTLIST_FOREACH(args
, char *, option
,
2503 if (!strcasecmpstart(option
, "purpose=")) {
2504 option
+= strlen("purpose=");
2505 purpose
= router_purpose_from_string(option
);
2506 if (purpose
== ROUTER_PURPOSE_UNKNOWN
) {
2507 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n",
2511 } else if (!strcasecmpstart(option
, "cache=")) {
2512 option
+= strlen("cache=");
2513 if (!strcasecmp(option
, "no"))
2515 else if (!strcasecmp(option
, "yes"))
2518 connection_printf_to_buf(conn
, "552 Unknown cache request \"%s\"\r\n",
2522 } else { /* unrecognized argument? */
2523 connection_printf_to_buf(conn
,
2524 "512 Unexpected argument \"%s\" to postdescriptor\r\n", option
);
2529 read_escaped_data(cp
, len
-(cp
-body
), &desc
);
2531 switch (router_load_single_router(desc
, purpose
, cache
, &msg
)) {
2533 if (!msg
) msg
= "Could not parse descriptor";
2534 connection_printf_to_buf(conn
, "554 %s\r\n", msg
);
2537 if (!msg
) msg
= "Descriptor not added";
2538 connection_printf_to_buf(conn
, "251 %s\r\n",msg
);
2541 send_control_done(conn
);
2547 SMARTLIST_FOREACH(args
, char *, arg
, tor_free(arg
));
2548 smartlist_free(args
);
2552 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
2553 * address of the named AP stream, and report success or failure. */
2555 handle_control_redirectstream(control_connection_t
*conn
, uint32_t len
,
2558 edge_connection_t
*ap_conn
= NULL
;
2559 char *new_addr
= NULL
;
2560 uint16_t new_port
= 0;
2564 args
= getargs_helper("REDIRECTSTREAM", conn
, body
, 2, -1);
2568 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))
2569 || !ap_conn
->socks_request
) {
2570 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2571 (char*)smartlist_get(args
, 0));
2574 if (smartlist_len(args
) > 2) { /* they included a port too */
2575 new_port
= (uint16_t) tor_parse_ulong(smartlist_get(args
, 2),
2576 10, 1, 65535, &ok
, NULL
);
2579 connection_printf_to_buf(conn
, "512 Cannot parse port \"%s\"\r\n",
2580 (char*)smartlist_get(args
, 2));
2582 new_addr
= tor_strdup(smartlist_get(args
, 1));
2586 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2587 smartlist_free(args
);
2591 strlcpy(ap_conn
->socks_request
->address
, new_addr
,
2592 sizeof(ap_conn
->socks_request
->address
));
2594 ap_conn
->socks_request
->port
= new_port
;
2596 send_control_done(conn
);
2600 /** Called when we get a CLOSESTREAM command; try to close the named stream
2601 * and report success or failure. */
2603 handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
2606 edge_connection_t
*ap_conn
=NULL
;
2612 args
= getargs_helper("CLOSESTREAM", conn
, body
, 2, -1);
2616 else if (!(ap_conn
= get_stream(smartlist_get(args
, 0))))
2617 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2618 (char*)smartlist_get(args
, 0));
2620 reason
= (uint8_t) tor_parse_ulong(smartlist_get(args
,1), 10, 0, 255,
2623 connection_printf_to_buf(conn
, "552 Unrecognized reason \"%s\"\r\n",
2624 (char*)smartlist_get(args
, 1));
2628 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2629 smartlist_free(args
);
2633 connection_mark_unattached_ap(ap_conn
, reason
);
2634 send_control_done(conn
);
2638 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
2639 * and report success or failure. */
2641 handle_control_closecircuit(control_connection_t
*conn
, uint32_t len
,
2644 origin_circuit_t
*circ
= NULL
;
2649 args
= getargs_helper("CLOSECIRCUIT", conn
, body
, 1, -1);
2653 if (!(circ
=get_circ(smartlist_get(args
, 0))))
2654 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2655 (char*)smartlist_get(args
, 0));
2658 for (i
=1; i
< smartlist_len(args
); ++i
) {
2659 if (!strcasecmp(smartlist_get(args
, i
), "IfUnused"))
2662 log_info(LD_CONTROL
, "Skipping unknown option %s",
2663 (char*)smartlist_get(args
,i
));
2666 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2667 smartlist_free(args
);
2671 if (!safe
|| !circ
->p_streams
) {
2672 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_REQUESTED
);
2675 send_control_done(conn
);
2679 /** Called when we get a RESOLVE command: start trying to resolve
2680 * the listed addresses. */
2682 handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
2685 smartlist_t
*args
, *failed
;
2687 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
2689 if (!(conn
->event_mask
& ((uint32_t)1L<<EVENT_ADDRMAP
))) {
2690 log_warn(LD_CONTROL
, "Controller asked us to resolve an address, but "
2691 "isn't listening for ADDRMAP events. It probably won't see "
2694 args
= smartlist_create();
2695 smartlist_split_string(args
, body
, " ",
2696 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2698 const char *modearg
= find_element_starting_with(args
, 0, "mode=");
2699 if (modearg
&& !strcasecmp(modearg
, "mode=reverse"))
2702 failed
= smartlist_create();
2703 SMARTLIST_FOREACH(args
, const char *, arg
, {
2704 if (!is_keyval_pair(arg
)) {
2705 if (dnsserv_launch_request(arg
, is_reverse
)<0)
2706 smartlist_add(failed
, (char*)arg
);
2710 send_control_done(conn
);
2711 SMARTLIST_FOREACH(failed
, const char *, arg
, {
2712 control_event_address_mapped(arg
, arg
, time(NULL
),
2713 "Unable to launch resolve request");
2716 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2717 smartlist_free(args
);
2718 smartlist_free(failed
);
2722 /** Called when we get a PROTOCOLINFO command: send back a reply. */
2724 handle_control_protocolinfo(control_connection_t
*conn
, uint32_t len
,
2727 const char *bad_arg
= NULL
;
2731 conn
->have_sent_protocolinfo
= 1;
2732 args
= smartlist_create();
2733 smartlist_split_string(args
, body
, " ",
2734 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2735 SMARTLIST_FOREACH(args
, const char *, arg
, {
2737 tor_parse_long(arg
, 10, 0, LONG_MAX
, &ok
, NULL
);
2744 connection_printf_to_buf(conn
, "513 No such version %s\r\n",
2746 /* Don't tolerate bad arguments when not authenticated. */
2747 if (!STATE_IS_OPEN(TO_CONN(conn
)->state
))
2748 connection_mark_for_close(TO_CONN(conn
));
2751 or_options_t
*options
= get_options();
2752 int cookies
= options
->CookieAuthentication
;
2753 char *cfile
= get_cookie_file();
2754 char *esc_cfile
= esc_for_log(cfile
);
2757 int passwd
= (options
->HashedControlPassword
!= NULL
||
2758 options
->HashedControlSessionPassword
!= NULL
);
2759 smartlist_t
*mlist
= smartlist_create();
2761 smartlist_add(mlist
, (char*)"COOKIE");
2763 smartlist_add(mlist
, (char*)"HASHEDPASSWORD");
2764 if (!cookies
&& !passwd
)
2765 smartlist_add(mlist
, (char*)"NULL");
2766 methods
= smartlist_join_strings(mlist
, ",", 0, NULL
);
2767 smartlist_free(mlist
);
2770 connection_printf_to_buf(conn
,
2771 "250-PROTOCOLINFO 1\r\n"
2772 "250-AUTH METHODS=%s%s%s\r\n"
2773 "250-VERSION Tor=%s\r\n"
2776 cookies
?" COOKIEFILE=":"",
2777 cookies
?esc_cfile
:"",
2781 tor_free(esc_cfile
);
2784 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2785 smartlist_free(args
);
2789 /** Called when we get a USEFEATURE command: parse the feature list, and
2790 * set up the control_connection's options properly. */
2792 handle_control_usefeature(control_connection_t
*conn
,
2798 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
2799 args
= smartlist_create();
2800 smartlist_split_string(args
, body
, " ",
2801 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2802 SMARTLIST_FOREACH(args
, const char *, arg
, {
2803 if (!strcasecmp(arg
, "VERBOSE_NAMES"))
2805 else if (!strcasecmp(arg
, "EXTENDED_EVENTS"))
2808 connection_printf_to_buf(conn
, "552 Unrecognized feature \"%s\"\r\n",
2816 send_control_done(conn
);
2819 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2820 smartlist_free(args
);
2824 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
2826 connection_control_finished_flushing(control_connection_t
*conn
)
2830 connection_stop_writing(TO_CONN(conn
));
2834 /** Called when <b>conn</b> has gotten its socket closed. */
2836 connection_control_reached_eof(control_connection_t
*conn
)
2840 log_info(LD_CONTROL
,"Control connection reached EOF. Closing.");
2841 connection_mark_for_close(TO_CONN(conn
));
2845 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
2846 * stage of the protocol. */
2848 is_valid_initial_command(control_connection_t
*conn
, const char *cmd
)
2850 if (conn
->_base
.state
== CONTROL_CONN_STATE_OPEN
)
2852 if (!strcasecmp(cmd
, "PROTOCOLINFO"))
2853 return !conn
->have_sent_protocolinfo
;
2854 if (!strcasecmp(cmd
, "AUTHENTICATE") ||
2855 !strcasecmp(cmd
, "QUIT"))
2860 /** Do not accept any control command of more than 1MB in length. Anything
2861 * that needs to be anywhere near this long probably means that one of our
2862 * interfaces is broken. */
2863 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
2865 /** Called when data has arrived on a v1 control connection: Try to fetch
2866 * commands from conn->inbuf, and execute them.
2869 connection_control_process_inbuf(control_connection_t
*conn
)
2872 uint32_t cmd_data_len
;
2877 tor_assert(conn
->_base
.state
== CONTROL_CONN_STATE_OPEN
||
2878 conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH
);
2880 if (!conn
->incoming_cmd
) {
2881 conn
->incoming_cmd
= tor_malloc(1024);
2882 conn
->incoming_cmd_len
= 1024;
2883 conn
->incoming_cmd_cur_len
= 0;
2886 if (conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
2887 peek_buf_has_control0_command(conn
->_base
.inbuf
)) {
2888 /* Detect v0 commands and send a "no more v0" message. */
2891 set_uint16(buf
+2, htons(0x0000)); /* type == error */
2892 set_uint16(buf
+4, htons(0x0001)); /* code == internal error */
2893 strlcpy(buf
+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
2894 "and later; upgrade your controller.",
2896 body_len
= 2+strlen(buf
+6)+2; /* code, msg, nul. */
2897 set_uint16(buf
+0, htons(body_len
));
2898 connection_write_to_buf(buf
, 4+body_len
, TO_CONN(conn
));
2899 connection_mark_for_close(TO_CONN(conn
));
2900 conn
->_base
.hold_open_until_flushed
= 1;
2908 /* First, fetch a line. */
2910 data_len
= conn
->incoming_cmd_len
- conn
->incoming_cmd_cur_len
;
2911 r
= fetch_from_buf_line(conn
->_base
.inbuf
,
2912 conn
->incoming_cmd
+conn
->incoming_cmd_cur_len
,
2915 /* Line not all here yet. Wait. */
2918 if (data_len
+ conn
->incoming_cmd_cur_len
> MAX_COMMAND_LINE_LENGTH
) {
2919 connection_write_str_to_buf("500 Line too long.\r\n", conn
);
2920 connection_stop_reading(TO_CONN(conn
));
2921 connection_mark_for_close(TO_CONN(conn
));
2922 conn
->_base
.hold_open_until_flushed
= 1;
2924 while (conn
->incoming_cmd_len
< data_len
+conn
->incoming_cmd_cur_len
)
2925 conn
->incoming_cmd_len
*= 2;
2926 conn
->incoming_cmd
= tor_realloc(conn
->incoming_cmd
,
2927 conn
->incoming_cmd_len
);
2931 tor_assert(data_len
);
2933 last_idx
= conn
->incoming_cmd_cur_len
;
2934 conn
->incoming_cmd_cur_len
+= (int)data_len
;
2936 /* We have appended a line to incoming_cmd. Is the command done? */
2937 if (last_idx
== 0 && *conn
->incoming_cmd
!= '+')
2938 /* One line command, didn't start with '+'. */
2940 /* XXXX this code duplication is kind of dumb. */
2941 if (last_idx
+3 == conn
->incoming_cmd_cur_len
&&
2942 tor_memeq(conn
->incoming_cmd
+ last_idx
, ".\r\n", 3)) {
2943 /* Just appended ".\r\n"; we're done. Remove it. */
2944 conn
->incoming_cmd
[last_idx
] = '\0';
2945 conn
->incoming_cmd_cur_len
-= 3;
2947 } else if (last_idx
+2 == conn
->incoming_cmd_cur_len
&&
2948 tor_memeq(conn
->incoming_cmd
+ last_idx
, ".\n", 2)) {
2949 /* Just appended ".\n"; we're done. Remove it. */
2950 conn
->incoming_cmd
[last_idx
] = '\0';
2951 conn
->incoming_cmd_cur_len
-= 2;
2954 /* Otherwise, read another line. */
2956 data_len
= conn
->incoming_cmd_cur_len
;
2957 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
2961 while ((size_t)cmd_len
< data_len
2962 && !TOR_ISSPACE(conn
->incoming_cmd
[cmd_len
]))
2965 conn
->incoming_cmd
[cmd_len
]='\0';
2966 args
= conn
->incoming_cmd
+cmd_len
+1;
2967 tor_assert(data_len
>(size_t)cmd_len
);
2968 data_len
-= (cmd_len
+1); /* skip the command and NUL we added after it */
2969 while (*args
== ' ' || *args
== '\t') {
2974 /* If the connection is already closing, ignore further commands */
2975 if (TO_CONN(conn
)->marked_for_close
) {
2979 /* Otherwise, Quit is always valid. */
2980 if (!strcasecmp(conn
->incoming_cmd
, "QUIT")) {
2981 connection_write_str_to_buf("250 closing connection\r\n", conn
);
2982 connection_mark_for_close(TO_CONN(conn
));
2983 conn
->_base
.hold_open_until_flushed
= 1;
2987 if (conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
2988 !is_valid_initial_command(conn
, conn
->incoming_cmd
)) {
2989 connection_write_str_to_buf("514 Authentication required.\r\n", conn
);
2990 connection_mark_for_close(TO_CONN(conn
));
2994 if (data_len
>= UINT32_MAX
) {
2995 connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn
);
2996 connection_mark_for_close(TO_CONN(conn
));
3000 cmd_data_len
= (uint32_t)data_len
;
3001 if (!strcasecmp(conn
->incoming_cmd
, "SETCONF")) {
3002 if (handle_control_setconf(conn
, cmd_data_len
, args
))
3004 } else if (!strcasecmp(conn
->incoming_cmd
, "RESETCONF")) {
3005 if (handle_control_resetconf(conn
, cmd_data_len
, args
))
3007 } else if (!strcasecmp(conn
->incoming_cmd
, "GETCONF")) {
3008 if (handle_control_getconf(conn
, cmd_data_len
, args
))
3010 } else if (!strcasecmp(conn
->incoming_cmd
, "+LOADCONF")) {
3011 if (handle_control_loadconf(conn
, cmd_data_len
, args
))
3013 } else if (!strcasecmp(conn
->incoming_cmd
, "SETEVENTS")) {
3014 if (handle_control_setevents(conn
, cmd_data_len
, args
))
3016 } else if (!strcasecmp(conn
->incoming_cmd
, "AUTHENTICATE")) {
3017 if (handle_control_authenticate(conn
, cmd_data_len
, args
))
3019 } else if (!strcasecmp(conn
->incoming_cmd
, "SAVECONF")) {
3020 if (handle_control_saveconf(conn
, cmd_data_len
, args
))
3022 } else if (!strcasecmp(conn
->incoming_cmd
, "SIGNAL")) {
3023 if (handle_control_signal(conn
, cmd_data_len
, args
))
3025 } else if (!strcasecmp(conn
->incoming_cmd
, "MAPADDRESS")) {
3026 if (handle_control_mapaddress(conn
, cmd_data_len
, args
))
3028 } else if (!strcasecmp(conn
->incoming_cmd
, "GETINFO")) {
3029 if (handle_control_getinfo(conn
, cmd_data_len
, args
))
3031 } else if (!strcasecmp(conn
->incoming_cmd
, "EXTENDCIRCUIT")) {
3032 if (handle_control_extendcircuit(conn
, cmd_data_len
, args
))
3034 } else if (!strcasecmp(conn
->incoming_cmd
, "SETCIRCUITPURPOSE")) {
3035 if (handle_control_setcircuitpurpose(conn
, cmd_data_len
, args
))
3037 } else if (!strcasecmp(conn
->incoming_cmd
, "SETROUTERPURPOSE")) {
3038 connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn
);
3039 } else if (!strcasecmp(conn
->incoming_cmd
, "ATTACHSTREAM")) {
3040 if (handle_control_attachstream(conn
, cmd_data_len
, args
))
3042 } else if (!strcasecmp(conn
->incoming_cmd
, "+POSTDESCRIPTOR")) {
3043 if (handle_control_postdescriptor(conn
, cmd_data_len
, args
))
3045 } else if (!strcasecmp(conn
->incoming_cmd
, "REDIRECTSTREAM")) {
3046 if (handle_control_redirectstream(conn
, cmd_data_len
, args
))
3048 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSESTREAM")) {
3049 if (handle_control_closestream(conn
, cmd_data_len
, args
))
3051 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSECIRCUIT")) {
3052 if (handle_control_closecircuit(conn
, cmd_data_len
, args
))
3054 } else if (!strcasecmp(conn
->incoming_cmd
, "USEFEATURE")) {
3055 if (handle_control_usefeature(conn
, cmd_data_len
, args
))
3057 } else if (!strcasecmp(conn
->incoming_cmd
, "RESOLVE")) {
3058 if (handle_control_resolve(conn
, cmd_data_len
, args
))
3060 } else if (!strcasecmp(conn
->incoming_cmd
, "PROTOCOLINFO")) {
3061 if (handle_control_protocolinfo(conn
, cmd_data_len
, args
))
3064 connection_printf_to_buf(conn
, "510 Unrecognized command \"%s\"\r\n",
3065 conn
->incoming_cmd
);
3068 conn
->incoming_cmd_cur_len
= 0;
3072 /** Something has happened to circuit <b>circ</b>: tell any interested
3073 * control connections. */
3075 control_event_circuit_status(origin_circuit_t
*circ
, circuit_status_event_t tp
,
3079 char extended_buf
[96];
3080 int providing_reason
=0;
3081 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS
))
3087 case CIRC_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
3088 case CIRC_EVENT_BUILT
: status
= "BUILT"; break;
3089 case CIRC_EVENT_EXTENDED
: status
= "EXTENDED"; break;
3090 case CIRC_EVENT_FAILED
: status
= "FAILED"; break;
3091 case CIRC_EVENT_CLOSED
: status
= "CLOSED"; break;
3093 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3097 tor_snprintf(extended_buf
, sizeof(extended_buf
), "PURPOSE=%s",
3098 circuit_purpose_to_controller_string(circ
->_base
.purpose
));
3100 if (tp
== CIRC_EVENT_FAILED
|| tp
== CIRC_EVENT_CLOSED
) {
3101 const char *reason_str
= circuit_end_reason_to_control_string(reason_code
);
3102 char *reason
= NULL
;
3103 size_t n
=strlen(extended_buf
);
3106 reason
= tor_malloc(16);
3107 tor_snprintf(reason
, 16, "UNKNOWN_%d", reason_code
);
3108 reason_str
= reason
;
3110 if (reason_code
> 0 && reason_code
& END_CIRC_REASON_FLAG_REMOTE
) {
3111 tor_snprintf(extended_buf
+n
, sizeof(extended_buf
)-n
,
3112 " REASON=DESTROYED REMOTE_REASON=%s", reason_str
);
3114 tor_snprintf(extended_buf
+n
, sizeof(extended_buf
)-n
,
3115 " REASON=%s", reason_str
);
3121 char *vpath
= circuit_list_path_for_controller(circ
);
3122 const char *sp
= strlen(vpath
) ? " " : "";
3123 send_control_event(EVENT_CIRCUIT_STATUS
, ALL_FORMATS
,
3124 "650 CIRC %lu %s%s%s %s\r\n",
3125 (unsigned long)circ
->global_identifier
,
3126 status
, sp
, vpath
, extended_buf
);
3133 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
3134 * <b>buf</b>, determine the address:port combination requested on
3135 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
3138 write_stream_target_to_buf(edge_connection_t
*conn
, char *buf
, size_t len
)
3141 if (conn
->chosen_exit_name
)
3142 if (tor_snprintf(buf2
, sizeof(buf2
), ".%s.exit", conn
->chosen_exit_name
)<0)
3144 if (!conn
->socks_request
)
3146 if (tor_snprintf(buf
, len
, "%s%s%s:%d",
3147 conn
->socks_request
->address
,
3148 conn
->chosen_exit_name
? buf2
: "",
3149 !conn
->chosen_exit_name
&&
3150 connection_edge_is_rendezvous_stream(conn
) ? ".onion" : "",
3151 conn
->socks_request
->port
)<0)
3156 /** Something has happened to the stream associated with AP connection
3157 * <b>conn</b>: tell any interested control connections. */
3159 control_event_stream_status(edge_connection_t
*conn
, stream_status_event_t tp
,
3162 char reason_buf
[64];
3163 char addrport_buf
[64];
3166 origin_circuit_t
*origin_circ
= NULL
;
3168 const char *purpose
= "";
3169 tor_assert(conn
->socks_request
);
3171 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS
))
3174 if (tp
== STREAM_EVENT_CLOSED
&&
3175 (reason_code
& END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
))
3178 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
3180 reason_buf
[0] = '\0';
3183 case STREAM_EVENT_SENT_CONNECT
: status
= "SENTCONNECT"; break;
3184 case STREAM_EVENT_SENT_RESOLVE
: status
= "SENTRESOLVE"; break;
3185 case STREAM_EVENT_SUCCEEDED
: status
= "SUCCEEDED"; break;
3186 case STREAM_EVENT_FAILED
: status
= "FAILED"; break;
3187 case STREAM_EVENT_CLOSED
: status
= "CLOSED"; break;
3188 case STREAM_EVENT_NEW
: status
= "NEW"; break;
3189 case STREAM_EVENT_NEW_RESOLVE
: status
= "NEWRESOLVE"; break;
3190 case STREAM_EVENT_FAILED_RETRIABLE
: status
= "DETACHED"; break;
3191 case STREAM_EVENT_REMAP
: status
= "REMAP"; break;
3193 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3196 if (reason_code
&& (tp
== STREAM_EVENT_FAILED
||
3197 tp
== STREAM_EVENT_CLOSED
||
3198 tp
== STREAM_EVENT_FAILED_RETRIABLE
)) {
3199 const char *reason_str
= stream_end_reason_to_control_string(reason_code
);
3203 tor_snprintf(r
, 16, " UNKNOWN_%d", reason_code
);
3206 if (reason_code
& END_STREAM_REASON_FLAG_REMOTE
)
3207 tor_snprintf(reason_buf
, sizeof(reason_buf
),
3208 " REASON=END REMOTE_REASON=%s", reason_str
);
3210 tor_snprintf(reason_buf
, sizeof(reason_buf
),
3211 " REASON=%s", reason_str
);
3213 } else if (reason_code
&& tp
== STREAM_EVENT_REMAP
) {
3214 switch (reason_code
) {
3215 case REMAP_STREAM_SOURCE_CACHE
:
3216 strlcpy(reason_buf
, " SOURCE=CACHE", sizeof(reason_buf
));
3218 case REMAP_STREAM_SOURCE_EXIT
:
3219 strlcpy(reason_buf
, " SOURCE=EXIT", sizeof(reason_buf
));
3222 tor_snprintf(reason_buf
, sizeof(reason_buf
), " REASON=UNKNOWN_%d",
3224 /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
3229 if (tp
== STREAM_EVENT_NEW
) {
3230 tor_snprintf(addrport_buf
,sizeof(addrport_buf
), " SOURCE_ADDR=%s:%d",
3231 TO_CONN(conn
)->address
, TO_CONN(conn
)->port
);
3233 addrport_buf
[0] = '\0';
3236 if (tp
== STREAM_EVENT_NEW_RESOLVE
) {
3237 purpose
= " PURPOSE=DNS_REQUEST";
3238 } else if (tp
== STREAM_EVENT_NEW
) {
3239 if (conn
->is_dns_request
||
3240 (conn
->socks_request
&&
3241 SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
)))
3242 purpose
= " PURPOSE=DNS_REQUEST";
3243 else if (conn
->use_begindir
) {
3244 connection_t
*linked
= TO_CONN(conn
)->linked_conn
;
3245 int linked_dir_purpose
= -1;
3246 if (linked
&& linked
->type
== CONN_TYPE_DIR
)
3247 linked_dir_purpose
= linked
->purpose
;
3248 if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose
))
3249 purpose
= " PURPOSE=DIR_UPLOAD";
3251 purpose
= " PURPOSE=DIR_FETCH";
3253 purpose
= " PURPOSE=USER";
3256 circ
= circuit_get_by_edge_conn(conn
);
3257 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
3258 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
3259 send_control_event(EVENT_STREAM_STATUS
, ALL_FORMATS
,
3260 "650 STREAM "U64_FORMAT
" %s %lu %s%s%s%s\r\n",
3261 U64_PRINTF_ARG(conn
->_base
.global_identifier
), status
,
3263 (unsigned long)origin_circ
->global_identifier
: 0ul,
3264 buf
, reason_buf
, addrport_buf
, purpose
);
3266 /* XXX need to specify its intended exit, etc? */
3271 /** Figure out the best name for the target router of an OR connection
3272 * <b>conn</b>, and write it into the <b>len</b>-character buffer
3275 orconn_target_get_name(char *name
, size_t len
, or_connection_t
*conn
)
3277 routerinfo_t
*ri
= router_get_by_digest(conn
->identity_digest
);
3279 tor_assert(len
> MAX_VERBOSE_NICKNAME_LEN
);
3280 router_get_verbose_nickname(name
, ri
);
3281 } else if (! tor_digest_is_zero(conn
->identity_digest
)) {
3283 base16_encode(name
+1, len
-1, conn
->identity_digest
,
3286 tor_snprintf(name
, len
, "%s:%d",
3287 conn
->_base
.address
, conn
->_base
.port
);
3291 /** Called when the status of an OR connection <b>conn</b> changes: tell any
3292 * interested control connections. <b>tp</b> is the new status for the
3293 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
3294 * may be the reason why.
3297 control_event_or_conn_status(or_connection_t
*conn
, or_conn_status_event_t tp
,
3303 char ncircs_buf
[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
3305 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS
))
3310 case OR_CONN_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
3311 case OR_CONN_EVENT_CONNECTED
: status
= "CONNECTED"; break;
3312 case OR_CONN_EVENT_FAILED
: status
= "FAILED"; break;
3313 case OR_CONN_EVENT_CLOSED
: status
= "CLOSED"; break;
3314 case OR_CONN_EVENT_NEW
: status
= "NEW"; break;
3316 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3319 ncircs
= circuit_count_pending_on_or_conn(conn
);
3320 ncircs
+= conn
->n_circuits
;
3321 if (ncircs
&& (tp
== OR_CONN_EVENT_FAILED
|| tp
== OR_CONN_EVENT_CLOSED
)) {
3322 tor_snprintf(ncircs_buf
, sizeof(ncircs_buf
), "%sNCIRCS=%d",
3323 reason
? " " : "", ncircs
);
3326 orconn_target_get_name(name
, sizeof(name
), conn
);
3327 send_control_event(EVENT_OR_CONN_STATUS
, ALL_FORMATS
,
3328 "650 ORCONN %s %s %s%s%s\r\n",
3330 reason
? "REASON=" : "",
3331 orconn_end_reason_to_control_string(reason
),
3338 * Print out STREAM_BW event for a single conn
3341 control_event_stream_bandwidth(edge_connection_t
*edge_conn
)
3343 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED
)) {
3344 if (!edge_conn
->n_read
&& !edge_conn
->n_written
)
3347 send_control_event(EVENT_STREAM_BANDWIDTH_USED
, ALL_FORMATS
,
3348 "650 STREAM_BW "U64_FORMAT
" %lu %lu\r\n",
3349 U64_PRINTF_ARG(edge_conn
->_base
.global_identifier
),
3350 (unsigned long)edge_conn
->n_read
,
3351 (unsigned long)edge_conn
->n_written
);
3353 edge_conn
->n_written
= edge_conn
->n_read
= 0;
3359 /** A second or more has elapsed: tell any interested control
3360 * connections how much bandwidth streams have used. */
3362 control_event_stream_bandwidth_used(void)
3364 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED
)) {
3365 smartlist_t
*conns
= get_connection_array();
3366 edge_connection_t
*edge_conn
;
3368 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
)
3370 if (conn
->type
!= CONN_TYPE_AP
)
3372 edge_conn
= TO_EDGE_CONN(conn
);
3373 if (!edge_conn
->n_read
&& !edge_conn
->n_written
)
3376 send_control_event(EVENT_STREAM_BANDWIDTH_USED
, ALL_FORMATS
,
3377 "650 STREAM_BW "U64_FORMAT
" %lu %lu\r\n",
3378 U64_PRINTF_ARG(edge_conn
->_base
.global_identifier
),
3379 (unsigned long)edge_conn
->n_read
,
3380 (unsigned long)edge_conn
->n_written
);
3382 edge_conn
->n_written
= edge_conn
->n_read
= 0;
3384 SMARTLIST_FOREACH_END(conn
);
3390 /** A second or more has elapsed: tell any interested control
3391 * connections how much bandwidth we used. */
3393 control_event_bandwidth_used(uint32_t n_read
, uint32_t n_written
)
3395 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED
)) {
3396 send_control_event(EVENT_BANDWIDTH_USED
, ALL_FORMATS
,
3397 "650 BW %lu %lu\r\n",
3398 (unsigned long)n_read
,
3399 (unsigned long)n_written
);
3405 /** Called when we are sending a log message to the controllers: suspend
3406 * sending further log messages to the controllers until we're done. Used by
3407 * CONN_LOG_PROTECT. */
3409 disable_control_logging(void)
3411 ++disable_log_messages
;
3414 /** We're done sending a log message to the controllers: re-enable controller
3415 * logging. Used by CONN_LOG_PROTECT. */
3417 enable_control_logging(void)
3419 if (--disable_log_messages
< 0)
3423 /** We got a log message: tell any interested control connections. */
3425 control_event_logmsg(int severity
, uint32_t domain
, const char *msg
)
3429 /* Don't even think of trying to add stuff to a buffer from a cpuworker
3431 if (! in_main_thread())
3434 if (disable_log_messages
)
3437 if (domain
== LD_BUG
&& EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
) &&
3438 severity
<= LOG_NOTICE
) {
3439 char *esc
= esc_for_log(msg
);
3440 ++disable_log_messages
;
3441 control_event_general_status(severity
, "BUG REASON=\"%s\"", esc
);
3442 --disable_log_messages
;
3446 event
= log_severity_to_event(severity
);
3447 if (event
>= 0 && EVENT_IS_INTERESTING(event
)) {
3450 if (strchr(msg
, '\n')) {
3452 b
= tor_strdup(msg
);
3453 for (cp
= b
; *cp
; ++cp
)
3454 if (*cp
== '\r' || *cp
== '\n')
3458 case LOG_DEBUG
: s
= "DEBUG"; break;
3459 case LOG_INFO
: s
= "INFO"; break;
3460 case LOG_NOTICE
: s
= "NOTICE"; break;
3461 case LOG_WARN
: s
= "WARN"; break;
3462 case LOG_ERR
: s
= "ERR"; break;
3463 default: s
= "UnknownLogSeverity"; break;
3465 ++disable_log_messages
;
3466 send_control_event(event
, ALL_FORMATS
, "650 %s %s\r\n", s
, b
?b
:msg
);
3467 --disable_log_messages
;
3472 /** Called whenever we receive new router descriptors: tell any
3473 * interested control connections. <b>routers</b> is a list of
3477 control_event_descriptors_changed(smartlist_t
*routers
)
3481 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC
))
3485 smartlist_t
*names
= smartlist_create();
3488 SMARTLIST_FOREACH(routers
, routerinfo_t
*, ri
, {
3489 char *b
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
3490 router_get_verbose_nickname(b
, ri
);
3491 smartlist_add(names
, b
);
3493 ids
= smartlist_join_strings(names
, " ", 0, &names_len
);
3494 names_len
= strlen(ids
)+32;
3495 msg
= tor_malloc(names_len
);
3496 tor_snprintf(msg
, names_len
, "650 NEWDESC %s\r\n", ids
);
3497 send_control_event_string(EVENT_NEW_DESC
, ALL_FORMATS
, msg
);
3500 SMARTLIST_FOREACH(names
, char *, cp
, tor_free(cp
));
3501 smartlist_free(names
);
3506 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
3507 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
3508 * <b>error</b> is non-NULL, it is an error code describing the failure
3509 * mode of the mapping.
3512 control_event_address_mapped(const char *from
, const char *to
, time_t expires
,
3515 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP
))
3518 if (expires
< 3 || expires
== TIME_MAX
)
3519 send_control_event(EVENT_ADDRMAP
, ALL_FORMATS
,
3520 "650 ADDRMAP %s %s NEVER %s\r\n", from
, to
,
3523 char buf
[ISO_TIME_LEN
+1];
3524 char buf2
[ISO_TIME_LEN
+1];
3525 format_local_iso_time(buf
,expires
);
3526 format_iso_time(buf2
,expires
);
3527 send_control_event(EVENT_ADDRMAP
, ALL_FORMATS
,
3528 "650 ADDRMAP %s %s \"%s\""
3529 " %s%sEXPIRES=\"%s\"\r\n",
3531 error
?error
:"", error
?" ":"",
3538 /** The authoritative dirserver has received a new descriptor that
3539 * has passed basic syntax checks and is properly self-signed.
3541 * Notify any interested party of the new descriptor and what has
3542 * been done with it, and also optionally give an explanation/reason. */
3544 control_event_or_authdir_new_descriptor(const char *action
,
3545 const char *desc
, size_t desclen
,
3548 char firstline
[1024];
3554 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS
))
3557 tor_snprintf(firstline
, sizeof(firstline
),
3558 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
3562 /* Escape the server descriptor properly */
3563 esclen
= write_escaped_data(desc
, desclen
, &esc
);
3565 totallen
= strlen(firstline
) + esclen
+ 1;
3566 buf
= tor_malloc(totallen
);
3567 strlcpy(buf
, firstline
, totallen
);
3568 strlcpy(buf
+strlen(firstline
), esc
, totallen
);
3569 send_control_event_string(EVENT_AUTHDIR_NEWDESCS
, ALL_FORMATS
,
3571 send_control_event_string(EVENT_AUTHDIR_NEWDESCS
, ALL_FORMATS
,
3579 /** Helper function for NS-style events. Constructs and sends an event
3580 * of type <b>event</b> with string <b>event_string</b> out of the set of
3581 * networkstatuses <b>statuses</b>. Currently it is used for NS events
3582 * and NEWCONSENSUS events. */
3584 control_event_networkstatus_changed_helper(smartlist_t
*statuses
,
3586 const char *event_string
)
3589 char *s
, *esc
= NULL
;
3590 if (!EVENT_IS_INTERESTING(event
) || !smartlist_len(statuses
))
3593 strs
= smartlist_create();
3594 smartlist_add(strs
, tor_strdup("650+"));
3595 smartlist_add(strs
, tor_strdup(event_string
));
3596 smartlist_add(strs
, tor_strdup("\r\n"));
3597 SMARTLIST_FOREACH(statuses
, routerstatus_t
*, rs
,
3599 s
= networkstatus_getinfo_helper_single(rs
);
3601 smartlist_add(strs
, s
);
3604 s
= smartlist_join_strings(strs
, "", 0, NULL
);
3605 write_escaped_data(s
, strlen(s
), &esc
);
3606 SMARTLIST_FOREACH(strs
, char *, cp
, tor_free(cp
));
3607 smartlist_free(strs
);
3609 send_control_event_string(event
, ALL_FORMATS
, esc
);
3610 send_control_event_string(event
, ALL_FORMATS
,
3617 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
3618 * an NS event to any controller that cares. */
3620 control_event_networkstatus_changed(smartlist_t
*statuses
)
3622 return control_event_networkstatus_changed_helper(statuses
, EVENT_NS
, "NS");
3625 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
3626 * event consisting of an NS-style line for each relay in the consensus. */
3628 control_event_newconsensus(const networkstatus_t
*consensus
)
3630 if (!control_event_is_interesting(EVENT_NEWCONSENSUS
))
3632 return control_event_networkstatus_changed_helper(
3633 consensus
->routerstatus_list
, EVENT_NEWCONSENSUS
, "NEWCONSENSUS");
3636 /** Called when we compute a new circuitbuildtimeout */
3638 control_event_buildtimeout_set(const circuit_build_times_t
*cbt
,
3639 buildtimeout_set_event_t type
)
3641 const char *type_string
= NULL
;
3642 double qnt
= circuit_build_times_quantile_cutoff();
3644 if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET
))
3648 case BUILDTIMEOUT_SET_EVENT_COMPUTED
:
3649 type_string
= "COMPUTED";
3651 case BUILDTIMEOUT_SET_EVENT_RESET
:
3652 type_string
= "RESET";
3655 case BUILDTIMEOUT_SET_EVENT_SUSPENDED
:
3656 type_string
= "SUSPENDED";
3659 case BUILDTIMEOUT_SET_EVENT_DISCARD
:
3660 type_string
= "DISCARD";
3663 case BUILDTIMEOUT_SET_EVENT_RESUME
:
3664 type_string
= "RESUME";
3667 type_string
= "UNKNOWN";
3671 send_control_event(EVENT_BUILDTIMEOUT_SET
, ALL_FORMATS
,
3672 "650 BUILDTIMEOUT_SET %s TOTAL_TIMES=%lu "
3673 "TIMEOUT_MS=%lu XM=%lu ALPHA=%lf CUTOFF_QUANTILE=%lf "
3674 "TIMEOUT_RATE=%lf CLOSE_MS=%lu CLOSE_RATE=%lf\r\n",
3675 type_string
, (unsigned long)cbt
->total_build_times
,
3676 (unsigned long)cbt
->timeout_ms
,
3677 (unsigned long)cbt
->Xm
, cbt
->alpha
, qnt
,
3678 circuit_build_times_timeout_rate(cbt
),
3679 (unsigned long)cbt
->close_ms
,
3680 circuit_build_times_close_rate(cbt
));
3685 /** Called when a single local_routerstatus_t has changed: Sends an NS event
3686 * to any controller that cares. */
3688 control_event_networkstatus_changed_single(routerstatus_t
*rs
)
3690 smartlist_t
*statuses
;
3693 if (!EVENT_IS_INTERESTING(EVENT_NS
))
3696 statuses
= smartlist_create();
3697 smartlist_add(statuses
, rs
);
3698 r
= control_event_networkstatus_changed(statuses
);
3699 smartlist_free(statuses
);
3703 /** Our own router descriptor has changed; tell any controllers that care.
3706 control_event_my_descriptor_changed(void)
3708 send_control_event(EVENT_DESCCHANGED
, ALL_FORMATS
, "650 DESCCHANGED\r\n");
3712 /** Helper: sends a status event where <b>type</b> is one of
3713 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
3714 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
3715 * string corresponding to <b>args</b>. */
3717 control_event_status(int type
, int severity
, const char *format
, va_list args
)
3719 char format_buf
[160];
3720 const char *status
, *sev
;
3723 case EVENT_STATUS_GENERAL
:
3724 status
= "STATUS_GENERAL";
3726 case EVENT_STATUS_CLIENT
:
3727 status
= "STATUS_CLIENT";
3729 case EVENT_STATUS_SERVER
:
3730 status
= "STATUS_SERVER";
3733 log_warn(LD_BUG
, "Unrecognized status type %d", type
);
3747 log_warn(LD_BUG
, "Unrecognized status severity %d", severity
);
3750 if (tor_snprintf(format_buf
, sizeof(format_buf
), "650 %s %s %s\r\n",
3751 status
, sev
, format
)<0) {
3752 log_warn(LD_BUG
, "Format string too long.");
3756 send_control_event_impl(type
, ALL_FORMATS
, format_buf
, args
);
3760 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
3761 * by formatting the arguments using the printf-style <b>format</b>. */
3763 control_event_general_status(int severity
, const char *format
, ...)
3767 if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
))
3770 va_start(ap
, format
);
3771 r
= control_event_status(EVENT_STATUS_GENERAL
, severity
, format
, ap
);
3776 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
3777 * by formatting the arguments using the printf-style <b>format</b>. */
3779 control_event_client_status(int severity
, const char *format
, ...)
3783 if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT
))
3786 va_start(ap
, format
);
3787 r
= control_event_status(EVENT_STATUS_CLIENT
, severity
, format
, ap
);
3792 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
3793 * by formatting the arguments using the printf-style <b>format</b>. */
3795 control_event_server_status(int severity
, const char *format
, ...)
3799 if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER
))
3802 va_start(ap
, format
);
3803 r
= control_event_status(EVENT_STATUS_SERVER
, severity
, format
, ap
);
3808 /** Called when the status of an entry guard with the given <b>nickname</b>
3809 * and identity <b>digest</b> has changed to <b>status</b>: tells any
3810 * controllers that care. */
3812 control_event_guard(const char *nickname
, const char *digest
,
3815 char hbuf
[HEX_DIGEST_LEN
+1];
3816 base16_encode(hbuf
, sizeof(hbuf
), digest
, DIGEST_LEN
);
3817 if (!EVENT_IS_INTERESTING(EVENT_GUARD
))
3821 char buf
[MAX_VERBOSE_NICKNAME_LEN
+1];
3822 routerinfo_t
*ri
= router_get_by_digest(digest
);
3824 router_get_verbose_nickname(buf
, ri
);
3826 tor_snprintf(buf
, sizeof(buf
), "$%s~%s", hbuf
, nickname
);
3828 send_control_event(EVENT_GUARD
, ALL_FORMATS
,
3829 "650 GUARD ENTRY %s %s\r\n", buf
, status
);
3834 /** Helper: Return a newly allocated string containing a path to the
3835 * file where we store our authentication cookie. */
3837 get_cookie_file(void)
3839 or_options_t
*options
= get_options();
3840 if (options
->CookieAuthFile
&& strlen(options
->CookieAuthFile
)) {
3841 return tor_strdup(options
->CookieAuthFile
);
3843 return get_datadir_fname("control_auth_cookie");
3847 /** Choose a random authentication cookie and write it to disk.
3848 * Anybody who can read the cookie from disk will be considered
3849 * authorized to use the control connection. Return -1 if we can't
3850 * write the file, or 0 on success. */
3852 init_cookie_authentication(int enabled
)
3856 authentication_cookie_is_set
= 0;
3860 /* We don't want to generate a new cookie every time we call
3861 * options_act(). One should be enough. */
3862 if (authentication_cookie_is_set
)
3863 return 0; /* all set */
3865 fname
= get_cookie_file();
3866 crypto_rand(authentication_cookie
, AUTHENTICATION_COOKIE_LEN
);
3867 authentication_cookie_is_set
= 1;
3868 if (write_bytes_to_file(fname
, authentication_cookie
,
3869 AUTHENTICATION_COOKIE_LEN
, 1)) {
3870 log_warn(LD_FS
,"Error writing authentication cookie to %s.",
3876 if (get_options()->CookieAuthFileGroupReadable
) {
3877 if (chmod(fname
, 0640)) {
3878 log_warn(LD_FS
,"Unable to make %s group-readable.", escaped(fname
));
3887 /** Convert the name of a bootstrapping phase <b>s</b> into strings
3888 * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
3890 bootstrap_status_to_string(bootstrap_status_t s
, const char **tag
,
3891 const char **summary
)
3894 case BOOTSTRAP_STATUS_UNDEF
:
3896 *summary
= "Undefined";
3898 case BOOTSTRAP_STATUS_STARTING
:
3900 *summary
= "Starting";
3902 case BOOTSTRAP_STATUS_CONN_DIR
:
3904 *summary
= "Connecting to directory server";
3906 case BOOTSTRAP_STATUS_HANDSHAKE
:
3907 *tag
= "status_handshake";
3908 *summary
= "Finishing handshake";
3910 case BOOTSTRAP_STATUS_HANDSHAKE_DIR
:
3911 *tag
= "handshake_dir";
3912 *summary
= "Finishing handshake with directory server";
3914 case BOOTSTRAP_STATUS_ONEHOP_CREATE
:
3915 *tag
= "onehop_create";
3916 *summary
= "Establishing an encrypted directory connection";
3918 case BOOTSTRAP_STATUS_REQUESTING_STATUS
:
3919 *tag
= "requesting_status";
3920 *summary
= "Asking for networkstatus consensus";
3922 case BOOTSTRAP_STATUS_LOADING_STATUS
:
3923 *tag
= "loading_status";
3924 *summary
= "Loading networkstatus consensus";
3926 case BOOTSTRAP_STATUS_LOADING_KEYS
:
3927 *tag
= "loading_keys";
3928 *summary
= "Loading authority key certs";
3930 case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS
:
3931 *tag
= "requesting_descriptors";
3932 *summary
= "Asking for relay descriptors";
3934 case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS
:
3935 *tag
= "loading_descriptors";
3936 *summary
= "Loading relay descriptors";
3938 case BOOTSTRAP_STATUS_CONN_OR
:
3940 *summary
= "Connecting to the Tor network";
3942 case BOOTSTRAP_STATUS_HANDSHAKE_OR
:
3943 *tag
= "handshake_or";
3944 *summary
= "Finishing handshake with first hop";
3946 case BOOTSTRAP_STATUS_CIRCUIT_CREATE
:
3947 *tag
= "circuit_create";
3948 *summary
= "Establishing a Tor circuit";
3950 case BOOTSTRAP_STATUS_DONE
:
3955 // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
3956 *tag
= *summary
= "unknown";
3962 /** What percentage through the bootstrap process are we? We remember
3963 * this so we can avoid sending redundant bootstrap status events, and
3964 * so we can guess context for the bootstrap messages which are
3965 * ambiguous. It starts at 'undef', but gets set to 'starting' while
3966 * Tor initializes. */
3967 static int bootstrap_percent
= BOOTSTRAP_STATUS_UNDEF
;
3969 /** How many problems have we had getting to the next bootstrapping phase?
3970 * These include failure to establish a connection to a Tor relay,
3971 * failures to finish the TLS handshake, failures to validate the
3972 * consensus document, etc. */
3973 static int bootstrap_problems
= 0;
3975 /* We only tell the controller once we've hit a threshold of problems
3976 * for the current phase. */
3977 #define BOOTSTRAP_PROBLEM_THRESHOLD 10
3979 /** Called when Tor has made progress at bootstrapping its directory
3980 * information and initial circuits.
3982 * <b>status</b> is the new status, that is, what task we will be doing
3983 * next. <b>progress</b> is zero if we just started this task, else it
3984 * represents progress on the task. */
3986 control_event_bootstrap(bootstrap_status_t status
, int progress
)
3988 const char *tag
, *summary
;
3989 char buf
[BOOTSTRAP_MSG_LEN
];
3991 if (bootstrap_percent
== BOOTSTRAP_STATUS_DONE
)
3992 return; /* already bootstrapped; nothing to be done here. */
3994 /* special case for handshaking status, since our TLS handshaking code
3995 * can't distinguish what the connection is going to be for. */
3996 if (status
== BOOTSTRAP_STATUS_HANDSHAKE
) {
3997 if (bootstrap_percent
< BOOTSTRAP_STATUS_CONN_OR
) {
3998 status
= BOOTSTRAP_STATUS_HANDSHAKE_DIR
;
4000 status
= BOOTSTRAP_STATUS_HANDSHAKE_OR
;
4004 if (status
> bootstrap_percent
||
4005 (progress
&& progress
> bootstrap_percent
)) {
4006 bootstrap_status_to_string(status
, &tag
, &summary
);
4007 log(status
? LOG_NOTICE
: LOG_INFO
, LD_CONTROL
,
4008 "Bootstrapped %d%%: %s.", progress
? progress
: status
, summary
);
4009 tor_snprintf(buf
, sizeof(buf
),
4010 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
4011 progress
? progress
: status
, tag
, summary
);
4012 tor_snprintf(last_sent_bootstrap_message
,
4013 sizeof(last_sent_bootstrap_message
),
4015 control_event_client_status(LOG_NOTICE
, "%s", buf
);
4016 if (status
> bootstrap_percent
) {
4017 bootstrap_percent
= status
; /* new milestone reached */
4019 if (progress
> bootstrap_percent
) {
4020 /* incremental progress within a milestone */
4021 bootstrap_percent
= progress
;
4022 bootstrap_problems
= 0; /* Progress! Reset our problem counter. */
4027 /** Called when Tor has failed to make bootstrapping progress in a way
4028 * that indicates a problem. <b>warn</b> gives a hint as to why, and
4029 * <b>reason</b> provides an "or_conn_end_reason" tag.
4032 control_event_bootstrap_problem(const char *warn
, int reason
)
4034 int status
= bootstrap_percent
;
4035 const char *tag
, *summary
;
4036 char buf
[BOOTSTRAP_MSG_LEN
];
4037 const char *recommendation
= "ignore";
4039 /* bootstrap_percent must not be in "undefined" state here. */
4040 tor_assert(status
>= 0);
4042 if (bootstrap_percent
== 100)
4043 return; /* already bootstrapped; nothing to be done here. */
4045 bootstrap_problems
++;
4047 if (bootstrap_problems
>= BOOTSTRAP_PROBLEM_THRESHOLD
)
4048 recommendation
= "warn";
4050 if (reason
== END_OR_CONN_REASON_NO_ROUTE
)
4051 recommendation
= "warn";
4053 if (get_options()->UseBridges
&&
4054 !any_bridge_descriptors_known() &&
4055 !any_pending_bridge_descriptor_fetches())
4056 recommendation
= "warn";
4058 while (status
>=0 && bootstrap_status_to_string(status
, &tag
, &summary
) < 0)
4059 status
--; /* find a recognized status string based on current progress */
4060 status
= bootstrap_percent
; /* set status back to the actual number */
4062 log_fn(!strcmp(recommendation
, "warn") ? LOG_WARN
: LOG_INFO
,
4063 LD_CONTROL
, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
4064 "count %d; recommendation %s)",
4065 status
, summary
, warn
,
4066 orconn_end_reason_to_control_string(reason
),
4067 bootstrap_problems
, recommendation
);
4068 tor_snprintf(buf
, sizeof(buf
),
4069 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
4070 "COUNT=%d RECOMMENDATION=%s",
4071 bootstrap_percent
, tag
, summary
, warn
,
4072 orconn_end_reason_to_control_string(reason
), bootstrap_problems
,
4074 tor_snprintf(last_sent_bootstrap_message
,
4075 sizeof(last_sent_bootstrap_message
),
4077 control_event_client_status(LOG_WARN
, "%s", buf
);
4080 /** We just generated a new summary of which countries we've seen clients
4081 * from recently. Send a copy to the controller in case it wants to
4082 * display it for the user. */
4084 control_event_clients_seen(const char *controller_str
)
4086 send_control_event(EVENT_CLIENTS_SEEN
, 0,
4087 "650 CLIENTS_SEEN %s\r\n", controller_str
);