2 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2017, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
8 * \brief Implementation for Tor's control-socket interface.
10 * A "controller" is an external program that monitors and controls a Tor
11 * instance via a text-based protocol. It connects to Tor via a connection
14 * The protocol is line-driven. The controller sends commands terminated by a
15 * CRLF. Tor sends lines that are either <em>replies</em> to what the
16 * controller has said, or <em>events</em> that Tor sends to the controller
17 * asynchronously based on occurrences in the Tor network model.
19 * See the control-spec.txt file in the torspec.git repository for full
20 * details on protocol.
22 * This module generally has two kinds of entry points: those based on having
23 * received a command on a controller socket, which are handled in
24 * connection_control_process_inbuf(), and dispatched to individual functions
25 * with names like control_handle_COMMANDNAME(); and those based on events
26 * that occur elsewhere in Tor, which are handled by functions with names like
27 * control_event_EVENTTYPE().
29 * Controller events are not sent immediately; rather, they are inserted into
30 * the queued_control_events array, and flushed later from
31 * flush_queued_events_cb(). Doing this simplifies our callgraph greatly,
32 * by limiting the number of places in Tor that can call back into the network
36 #define CONTROL_PRIVATE
39 #include "addressmap.h"
43 #include "channeltls.h"
44 #include "circuitbuild.h"
45 #include "circuitlist.h"
46 #include "circuitstats.h"
47 #include "circuituse.h"
49 #include "compat_libevent.h"
51 #include "confparse.h"
52 #include "connection.h"
53 #include "connection_edge.h"
54 #include "connection_or.h"
56 #include "crypto_rand.h"
57 #include "crypto_util.h"
58 #include "directory.h"
61 #include "entrynodes.h"
63 #include "hibernate.h"
65 #include "hs_common.h"
66 #include "hs_control.h"
68 #include "microdesc.h"
69 #include "networkstatus.h"
72 #include "proto_control0.h"
73 #include "proto_http.h"
75 #include "rendclient.h"
76 #include "rendcommon.h"
77 #include "rendservice.h"
80 #include "routerlist.h"
81 #include "routerparse.h"
82 #include "shared_random_client.h"
86 #include <sys/resource.h>
89 #include "crypto_s2k.h"
92 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
93 * finished authentication and is accepting commands. */
94 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
96 /** Bitfield: The bit 1<<e is set if <b>any</b> open control
97 * connection is interested in events of type <b>e</b>. We use this
98 * so that we can decide to skip generating event messages that nobody
99 * has interest in without having to walk over the global connection
102 typedef uint64_t event_mask_t
;
104 /** An event mask of all the events that any controller is interested in
106 static event_mask_t global_event_mask
= 0;
108 /** True iff we have disabled log messages from being sent to the controller */
109 static int disable_log_messages
= 0;
111 /** Macro: true if any control connection is interested in events of type
113 #define EVENT_IS_INTERESTING(e) \
114 (!! (global_event_mask & EVENT_MASK_(e)))
116 /** Macro: true if any event from the bitfield 'e' is interesting. */
117 #define ANY_EVENT_IS_INTERESTING(e) \
118 (!! (global_event_mask & (e)))
120 /** If we're using cookie-type authentication, how long should our cookies be?
122 #define AUTHENTICATION_COOKIE_LEN 32
124 /** If true, we've set authentication_cookie to a secret code and
125 * stored it to disk. */
126 static int authentication_cookie_is_set
= 0;
127 /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
128 * and which we're using to authenticate controllers. (If the controller can
129 * read it off disk, it has permission to connect.) */
130 static uint8_t *authentication_cookie
= NULL
;
132 #define SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT \
133 "Tor safe cookie authentication server-to-controller hash"
134 #define SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT \
135 "Tor safe cookie authentication controller-to-server hash"
136 #define SAFECOOKIE_SERVER_NONCE_LEN DIGEST256_LEN
138 /** The list of onion services that have been added via ADD_ONION that do not
139 * belong to any particular control connection.
141 static smartlist_t
*detached_onion_services
= NULL
;
143 /** A sufficiently large size to record the last bootstrap phase string. */
144 #define BOOTSTRAP_MSG_LEN 1024
146 /** What was the last bootstrap phase message we sent? We keep track
147 * of this so we can respond to getinfo status/bootstrap-phase queries. */
148 static char last_sent_bootstrap_message
[BOOTSTRAP_MSG_LEN
];
150 static void connection_printf_to_buf(control_connection_t
*conn
,
151 const char *format
, ...)
153 static void send_control_event_impl(uint16_t event
,
154 const char *format
, va_list ap
)
156 static int control_event_status(int type
, int severity
, const char *format
,
160 static void send_control_done(control_connection_t
*conn
);
161 static void send_control_event(uint16_t event
,
162 const char *format
, ...)
164 static int handle_control_setconf(control_connection_t
*conn
, uint32_t len
,
166 static int handle_control_resetconf(control_connection_t
*conn
, uint32_t len
,
168 static int handle_control_getconf(control_connection_t
*conn
, uint32_t len
,
170 static int handle_control_loadconf(control_connection_t
*conn
, uint32_t len
,
172 static int handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
174 static int handle_control_authenticate(control_connection_t
*conn
,
177 static int handle_control_signal(control_connection_t
*conn
, uint32_t len
,
179 static int handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
181 static char *list_getinfo_options(void);
182 static int handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
184 static int handle_control_extendcircuit(control_connection_t
*conn
,
187 static int handle_control_setcircuitpurpose(control_connection_t
*conn
,
188 uint32_t len
, const char *body
);
189 static int handle_control_attachstream(control_connection_t
*conn
,
192 static int handle_control_postdescriptor(control_connection_t
*conn
,
195 static int handle_control_redirectstream(control_connection_t
*conn
,
198 static int handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
200 static int handle_control_closecircuit(control_connection_t
*conn
,
203 static int handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
205 static int handle_control_usefeature(control_connection_t
*conn
,
208 static int handle_control_hsfetch(control_connection_t
*conn
, uint32_t len
,
210 static int handle_control_hspost(control_connection_t
*conn
, uint32_t len
,
212 static int handle_control_add_onion(control_connection_t
*conn
, uint32_t len
,
214 static int handle_control_del_onion(control_connection_t
*conn
, uint32_t len
,
216 static int write_stream_target_to_buf(entry_connection_t
*conn
, char *buf
,
218 static void orconn_target_get_name(char *buf
, size_t len
,
219 or_connection_t
*conn
);
221 static int get_cached_network_liveness(void);
222 static void set_cached_network_liveness(int liveness
);
224 static void flush_queued_events_cb(mainloop_event_t
*event
, void *arg
);
226 static char * download_status_to_string(const download_status_t
*dl
);
227 static void control_get_bytes_rw_last_sec(uint64_t *r
, uint64_t *w
);
229 /** Given a control event code for a message event, return the corresponding
232 event_to_log_severity(int event
)
235 case EVENT_DEBUG_MSG
: return LOG_DEBUG
;
236 case EVENT_INFO_MSG
: return LOG_INFO
;
237 case EVENT_NOTICE_MSG
: return LOG_NOTICE
;
238 case EVENT_WARN_MSG
: return LOG_WARN
;
239 case EVENT_ERR_MSG
: return LOG_ERR
;
244 /** Given a log severity, return the corresponding control event code. */
246 log_severity_to_event(int severity
)
249 case LOG_DEBUG
: return EVENT_DEBUG_MSG
;
250 case LOG_INFO
: return EVENT_INFO_MSG
;
251 case LOG_NOTICE
: return EVENT_NOTICE_MSG
;
252 case LOG_WARN
: return EVENT_WARN_MSG
;
253 case LOG_ERR
: return EVENT_ERR_MSG
;
258 /** Helper: clear bandwidth counters of all origin circuits. */
260 clear_circ_bw_fields(void)
262 origin_circuit_t
*ocirc
;
263 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t
*, circ
) {
264 if (!CIRCUIT_IS_ORIGIN(circ
))
266 ocirc
= TO_ORIGIN_CIRCUIT(circ
);
267 ocirc
->n_written_circ_bw
= ocirc
->n_read_circ_bw
= 0;
268 ocirc
->n_overhead_written_circ_bw
= ocirc
->n_overhead_read_circ_bw
= 0;
269 ocirc
->n_delivered_written_circ_bw
= ocirc
->n_delivered_read_circ_bw
= 0;
271 SMARTLIST_FOREACH_END(circ
);
274 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
275 * connection's event_mask field. */
277 control_update_global_event_mask(void)
279 smartlist_t
*conns
= get_connection_array();
280 event_mask_t old_mask
, new_mask
;
281 old_mask
= global_event_mask
;
282 int any_old_per_sec_events
= control_any_per_second_event_enabled();
284 global_event_mask
= 0;
285 SMARTLIST_FOREACH(conns
, connection_t
*, _conn
,
287 if (_conn
->type
== CONN_TYPE_CONTROL
&&
288 STATE_IS_OPEN(_conn
->state
)) {
289 control_connection_t
*conn
= TO_CONTROL_CONN(_conn
);
290 global_event_mask
|= conn
->event_mask
;
294 new_mask
= global_event_mask
;
296 /* Handle the aftermath. Set up the log callback to tell us only what
297 * we want to hear...*/
298 control_adjust_event_log_severity();
300 /* Macro: true if ev was false before and is true now. */
301 #define NEWLY_ENABLED(ev) \
302 (! (old_mask & (ev)) && (new_mask & (ev)))
304 /* ...then, if we've started logging stream or circ bw, clear the
305 * appropriate fields. */
306 if (NEWLY_ENABLED(EVENT_STREAM_BANDWIDTH_USED
)) {
307 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
309 if (conn
->type
== CONN_TYPE_AP
) {
310 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
311 edge_conn
->n_written
= edge_conn
->n_read
= 0;
315 if (NEWLY_ENABLED(EVENT_CIRC_BANDWIDTH_USED
)) {
316 clear_circ_bw_fields();
318 if (NEWLY_ENABLED(EVENT_BANDWIDTH_USED
)) {
320 control_get_bytes_rw_last_sec(&r
, &w
);
322 if (any_old_per_sec_events
!= control_any_per_second_event_enabled()) {
323 reschedule_per_second_timer();
329 /** Adjust the log severities that result in control_event_logmsg being called
330 * to match the severity of log messages that any controllers are interested
333 control_adjust_event_log_severity(void)
336 int min_log_event
=EVENT_ERR_MSG
, max_log_event
=EVENT_DEBUG_MSG
;
338 for (i
= EVENT_DEBUG_MSG
; i
<= EVENT_ERR_MSG
; ++i
) {
339 if (EVENT_IS_INTERESTING(i
)) {
344 for (i
= EVENT_ERR_MSG
; i
>= EVENT_DEBUG_MSG
; --i
) {
345 if (EVENT_IS_INTERESTING(i
)) {
350 if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
)) {
351 if (min_log_event
> EVENT_NOTICE_MSG
)
352 min_log_event
= EVENT_NOTICE_MSG
;
353 if (max_log_event
< EVENT_ERR_MSG
)
354 max_log_event
= EVENT_ERR_MSG
;
356 if (min_log_event
<= max_log_event
)
357 change_callback_log_severity(event_to_log_severity(min_log_event
),
358 event_to_log_severity(max_log_event
),
359 control_event_logmsg
);
361 change_callback_log_severity(LOG_ERR
, LOG_ERR
,
362 control_event_logmsg
);
365 /** Return true iff the event with code <b>c</b> is being sent to any current
366 * control connection. This is useful if the amount of work needed to prepare
367 * to call the appropriate control_event_...() function is high.
370 control_event_is_interesting(int event
)
372 return EVENT_IS_INTERESTING(event
);
375 /** Return true if any event that needs to fire once a second is enabled. */
377 control_any_per_second_event_enabled(void)
379 return ANY_EVENT_IS_INTERESTING(
380 EVENT_MASK_(EVENT_BANDWIDTH_USED
) |
381 EVENT_MASK_(EVENT_CELL_STATS
) |
382 EVENT_MASK_(EVENT_CIRC_BANDWIDTH_USED
) |
383 EVENT_MASK_(EVENT_CONN_BW
) |
384 EVENT_MASK_(EVENT_STREAM_BANDWIDTH_USED
)
388 /* The value of 'get_bytes_read()' the previous time that
389 * control_get_bytes_rw_last_sec() as called. */
390 static uint64_t stats_prev_n_read
= 0;
391 /* The value of 'get_bytes_written()' the previous time that
392 * control_get_bytes_rw_last_sec() as called. */
393 static uint64_t stats_prev_n_written
= 0;
396 * Set <b>n_read</b> and <b>n_written</b> to the total number of bytes read
397 * and written by Tor since the last call to this function.
399 * Call this only from the main thread.
402 control_get_bytes_rw_last_sec(uint64_t *n_read
,
405 const uint64_t stats_n_bytes_read
= get_bytes_read();
406 const uint64_t stats_n_bytes_written
= get_bytes_written();
408 *n_read
= stats_n_bytes_read
- stats_prev_n_read
;
409 *n_written
= stats_n_bytes_written
- stats_prev_n_written
;
410 stats_prev_n_read
= stats_n_bytes_read
;
411 stats_prev_n_written
= stats_n_bytes_written
;
415 * Run all the controller events (if any) that are scheduled to trigger once
419 control_per_second_events(void)
421 if (!control_any_per_second_event_enabled())
424 uint64_t bytes_read
, bytes_written
;
425 control_get_bytes_rw_last_sec(&bytes_read
, &bytes_written
);
426 control_event_bandwidth_used((uint32_t)bytes_read
,(uint32_t)bytes_written
);
428 control_event_stream_bandwidth_used();
429 control_event_conn_bandwidth_used();
430 control_event_circ_bandwidth_used();
431 control_event_circuit_cell_stats();
434 /** Append a NUL-terminated string <b>s</b> to the end of
435 * <b>conn</b>-\>outbuf.
438 connection_write_str_to_buf(const char *s
, control_connection_t
*conn
)
440 size_t len
= strlen(s
);
441 connection_buf_add(s
, len
, TO_CONN(conn
));
444 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
445 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
446 * contents of <b>data</b> into *<b>out</b>, adding a period before any period
447 * that appears at the start of a line, and adding a period-CRLF line at
448 * the end. Replace all LF characters sequences with CRLF. Return the number
449 * of bytes in *<b>out</b>.
452 write_escaped_data(const char *data
, size_t len
, char **out
)
454 tor_assert(len
< SIZE_MAX
- 9);
455 size_t sz_out
= len
+8+1;
457 const char *start
= data
, *end
;
460 for (i
=0; i
< len
; ++i
) {
461 if (data
[i
] == '\n') {
462 sz_out
+= 2; /* Maybe add a CR; maybe add a dot. */
463 if (sz_out
>= SIZE_T_CEILING
) {
464 log_warn(LD_BUG
, "Input to write_escaped_data was too long");
465 *out
= tor_strdup(".\r\n");
470 *out
= outp
= tor_malloc(sz_out
);
475 if (data
> start
&& data
[-1] != '\r')
478 } else if (*data
== '.') {
488 if (outp
< *out
+2 || fast_memcmp(outp
-2, "\r\n", 2)) {
495 *outp
= '\0'; /* NUL-terminate just in case. */
496 tor_assert(outp
>= *out
);
497 tor_assert((size_t)(outp
- *out
) <= sz_out
);
501 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
502 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
503 * the contents of <b>data</b> into *<b>out</b>, removing any period
504 * that appears at the start of a line, and replacing all CRLF sequences
505 * with LF. Return the number of
506 * bytes in *<b>out</b>. */
508 read_escaped_data(const char *data
, size_t len
, char **out
)
514 *out
= outp
= tor_malloc(len
+1);
519 /* we're at the start of a line. */
522 next
= memchr(data
, '\n', end
-data
);
524 size_t n_to_copy
= next
-data
;
525 /* Don't copy a CR that precedes this LF. */
526 if (n_to_copy
&& *(next
-1) == '\r')
528 memcpy(outp
, data
, n_to_copy
);
530 data
= next
+1; /* This will point at the start of the next line,
531 * or the end of the string, or a period. */
533 memcpy(outp
, data
, end
-data
);
545 /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
546 * double-quoted string with escaped characters, return the length of that
547 * string (as encoded, including quotes). Otherwise return -1. */
549 get_escaped_string_length(const char *start
, size_t in_len_max
,
552 const char *cp
, *end
;
559 end
= start
+in_len_max
;
561 /* Calculate length. */
564 return -1; /* Too long. */
565 } else if (*cp
== '\\') {
567 return -1; /* Can't escape EOS. */
570 } else if (*cp
== '\"') {
579 return (int)(cp
- start
+1);
582 /** As decode_escaped_string, but does not decode the string: copies the
583 * entire thing, including quotation marks. */
585 extract_escaped_string(const char *start
, size_t in_len_max
,
586 char **out
, size_t *out_len
)
588 int length
= get_escaped_string_length(start
, in_len_max
, NULL
);
592 *out
= tor_strndup(start
, *out_len
);
596 /** Given a pointer to a string starting at <b>start</b> containing
597 * <b>in_len_max</b> characters, decode a string beginning with one double
598 * quote, containing any number of non-quote characters or characters escaped
599 * with a backslash, and ending with a final double quote. Place the resulting
600 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
601 * store its length in <b>out_len</b>. On success, return a pointer to the
602 * character immediately following the escaped string. On failure, return
605 decode_escaped_string(const char *start
, size_t in_len_max
,
606 char **out
, size_t *out_len
)
608 const char *cp
, *end
;
610 int len
, n_chars
= 0;
612 len
= get_escaped_string_length(start
, in_len_max
, &n_chars
);
616 end
= start
+len
-1; /* Index of last quote. */
617 tor_assert(*end
== '\"');
618 outp
= *out
= tor_malloc(len
+1);
628 tor_assert((outp
- *out
) == (int)*out_len
);
633 /** Create and add a new controller connection on <b>sock</b>. If
634 * <b>CC_LOCAL_FD_IS_OWNER</b> is set in <b>flags</b>, this Tor process should
635 * exit when the connection closes. If <b>CC_LOCAL_FD_IS_AUTHENTICATED</b>
636 * is set, then the connection does not need to authenticate.
639 control_connection_add_local_fd(tor_socket_t sock
, unsigned flags
)
641 if (BUG(! SOCKET_OK(sock
)))
643 const int is_owner
= !!(flags
& CC_LOCAL_FD_IS_OWNER
);
644 const int is_authenticated
= !!(flags
& CC_LOCAL_FD_IS_AUTHENTICATED
);
645 control_connection_t
*control_conn
= control_connection_new(AF_UNSPEC
);
646 connection_t
*conn
= TO_CONN(control_conn
);
648 tor_addr_make_unspec(&conn
->addr
);
650 conn
->address
= tor_strdup("<local socket>");
652 /* We take ownership of this socket so that later, when we close it,
653 * we don't freak out. */
654 tor_take_socket_ownership(sock
);
656 if (set_socket_nonblocking(sock
) < 0 ||
657 connection_add(conn
) < 0) {
658 connection_free(conn
);
662 control_conn
->is_owning_control_connection
= is_owner
;
664 if (connection_init_accepted_conn(conn
, NULL
) < 0) {
665 connection_mark_for_close(conn
);
669 if (is_authenticated
) {
670 conn
->state
= CONTROL_CONN_STATE_OPEN
;
676 /** Acts like sprintf, but writes its formatted string to the end of
677 * <b>conn</b>-\>outbuf. */
679 connection_printf_to_buf(control_connection_t
*conn
, const char *format
, ...)
686 len
= tor_vasprintf(&buf
, format
, ap
);
690 log_err(LD_BUG
, "Unable to format string for controller.");
694 connection_buf_add(buf
, (size_t)len
, TO_CONN(conn
));
699 /** Write all of the open control ports to ControlPortWriteToFile */
701 control_ports_write_to_file(void)
705 const or_options_t
*options
= get_options();
707 if (!options
->ControlPortWriteToFile
)
710 lines
= smartlist_new();
712 SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t
*, conn
) {
713 if (conn
->type
!= CONN_TYPE_CONTROL_LISTENER
|| conn
->marked_for_close
)
716 if (conn
->socket_family
== AF_UNIX
) {
717 smartlist_add_asprintf(lines
, "UNIX_PORT=%s\n", conn
->address
);
720 #endif /* defined(AF_UNIX) */
721 smartlist_add_asprintf(lines
, "PORT=%s:%d\n", conn
->address
, conn
->port
);
722 } SMARTLIST_FOREACH_END(conn
);
724 joined
= smartlist_join_strings(lines
, "", 0, NULL
);
726 if (write_str_to_file(options
->ControlPortWriteToFile
, joined
, 0) < 0) {
727 log_warn(LD_CONTROL
, "Writing %s failed: %s",
728 options
->ControlPortWriteToFile
, strerror(errno
));
731 if (options
->ControlPortFileGroupReadable
) {
732 if (chmod(options
->ControlPortWriteToFile
, 0640)) {
733 log_warn(LD_FS
,"Unable to make %s group-readable.",
734 options
->ControlPortWriteToFile
);
737 #endif /* !defined(_WIN32) */
739 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
740 smartlist_free(lines
);
743 /** Send a "DONE" message down the control connection <b>conn</b>. */
745 send_control_done(control_connection_t
*conn
)
747 connection_write_str_to_buf("250 OK\r\n", conn
);
750 /** Represents an event that's queued to be sent to one or more
752 typedef struct queued_event_s
{
757 /** Pointer to int. If this is greater than 0, we don't allow new events to be
759 static tor_threadlocal_t block_event_queue_flag
;
761 /** Holds a smartlist of queued_event_t objects that may need to be sent
762 * to one or more controllers */
763 static smartlist_t
*queued_control_events
= NULL
;
765 /** True if the flush_queued_events_event is pending. */
766 static int flush_queued_event_pending
= 0;
768 /** Lock to protect the above fields. */
769 static tor_mutex_t
*queued_control_events_lock
= NULL
;
771 /** An event that should fire in order to flush the contents of
772 * queued_control_events. */
773 static mainloop_event_t
*flush_queued_events_event
= NULL
;
776 control_initialize_event_queue(void)
778 if (queued_control_events
== NULL
) {
779 queued_control_events
= smartlist_new();
782 if (flush_queued_events_event
== NULL
) {
783 struct event_base
*b
= tor_libevent_get_base();
785 flush_queued_events_event
=
786 mainloop_event_new(flush_queued_events_cb
, NULL
);
787 tor_assert(flush_queued_events_event
);
791 if (queued_control_events_lock
== NULL
) {
792 queued_control_events_lock
= tor_mutex_new();
793 tor_threadlocal_init(&block_event_queue_flag
);
798 get_block_event_queue(void)
800 int *val
= tor_threadlocal_get(&block_event_queue_flag
);
801 if (PREDICT_UNLIKELY(val
== NULL
)) {
802 val
= tor_malloc_zero(sizeof(int));
803 tor_threadlocal_set(&block_event_queue_flag
, val
);
808 /** Helper: inserts an event on the list of events queued to be sent to
809 * one or more controllers, and schedules the events to be flushed if needed.
811 * This function takes ownership of <b>msg</b>, and may free it.
813 * We queue these events rather than send them immediately in order to break
814 * the dependency in our callgraph from code that generates events for the
815 * controller, and the network layer at large. Otherwise, nearly every
816 * interesting part of Tor would potentially call every other interesting part
819 MOCK_IMPL(STATIC
void,
820 queue_control_event_string
,(uint16_t event
, char *msg
))
822 /* This is redundant with checks done elsewhere, but it's a last-ditch
823 * attempt to avoid queueing something we shouldn't have to queue. */
824 if (PREDICT_UNLIKELY( ! EVENT_IS_INTERESTING(event
) )) {
829 int *block_event_queue
= get_block_event_queue();
830 if (*block_event_queue
) {
835 queued_event_t
*ev
= tor_malloc(sizeof(*ev
));
839 /* No queueing an event while queueing an event */
840 ++*block_event_queue
;
842 tor_mutex_acquire(queued_control_events_lock
);
843 tor_assert(queued_control_events
);
844 smartlist_add(queued_control_events
, ev
);
846 int activate_event
= 0;
847 if (! flush_queued_event_pending
&& in_main_thread()) {
849 flush_queued_event_pending
= 1;
852 tor_mutex_release(queued_control_events_lock
);
854 --*block_event_queue
;
856 /* We just put an event on the queue; mark the queue to be
857 * flushed. We only do this from the main thread for now; otherwise,
858 * we'd need to incur locking overhead in Libevent or use a socket.
860 if (activate_event
) {
861 tor_assert(flush_queued_events_event
);
862 mainloop_event_activate(flush_queued_events_event
);
866 #define queued_event_free(ev) \
867 FREE_AND_NULL(queued_event_t, queued_event_free_, (ev))
869 /** Release all storage held by <b>ev</b>. */
871 queued_event_free_(queued_event_t
*ev
)
880 /** Send every queued event to every controller that's interested in it,
881 * and remove the events from the queue. If <b>force</b> is true,
882 * then make all controllers send their data out immediately, since we
883 * may be about to shut down. */
885 queued_events_flush_all(int force
)
887 /* Make sure that we get all the pending log events, if there are any. */
888 flush_pending_log_callbacks();
890 if (PREDICT_UNLIKELY(queued_control_events
== NULL
)) {
893 smartlist_t
*all_conns
= get_connection_array();
894 smartlist_t
*controllers
= smartlist_new();
895 smartlist_t
*queued_events
;
897 int *block_event_queue
= get_block_event_queue();
898 ++*block_event_queue
;
900 tor_mutex_acquire(queued_control_events_lock
);
901 /* No queueing an event while flushing events. */
902 flush_queued_event_pending
= 0;
903 queued_events
= queued_control_events
;
904 queued_control_events
= smartlist_new();
905 tor_mutex_release(queued_control_events_lock
);
907 /* Gather all the controllers that will care... */
908 SMARTLIST_FOREACH_BEGIN(all_conns
, connection_t
*, conn
) {
909 if (conn
->type
== CONN_TYPE_CONTROL
&&
910 !conn
->marked_for_close
&&
911 conn
->state
== CONTROL_CONN_STATE_OPEN
) {
912 control_connection_t
*control_conn
= TO_CONTROL_CONN(conn
);
914 smartlist_add(controllers
, control_conn
);
916 } SMARTLIST_FOREACH_END(conn
);
918 SMARTLIST_FOREACH_BEGIN(queued_events
, queued_event_t
*, ev
) {
919 const event_mask_t bit
= ((event_mask_t
)1) << ev
->event
;
920 const size_t msg_len
= strlen(ev
->msg
);
921 SMARTLIST_FOREACH_BEGIN(controllers
, control_connection_t
*,
923 if (control_conn
->event_mask
& bit
) {
924 connection_buf_add(ev
->msg
, msg_len
, TO_CONN(control_conn
));
926 } SMARTLIST_FOREACH_END(control_conn
);
928 queued_event_free(ev
);
929 } SMARTLIST_FOREACH_END(ev
);
932 SMARTLIST_FOREACH_BEGIN(controllers
, control_connection_t
*,
934 connection_flush(TO_CONN(control_conn
));
935 } SMARTLIST_FOREACH_END(control_conn
);
938 smartlist_free(queued_events
);
939 smartlist_free(controllers
);
941 --*block_event_queue
;
944 /** Libevent callback: Flushes pending events to controllers that are
945 * interested in them. */
947 flush_queued_events_cb(mainloop_event_t
*event
, void *arg
)
951 queued_events_flush_all(0);
954 /** Send an event to all v1 controllers that are listening for code
955 * <b>event</b>. The event's body is given by <b>msg</b>.
957 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
958 * respect to the EXTENDED_EVENTS feature. */
959 MOCK_IMPL(STATIC
void,
960 send_control_event_string
,(uint16_t event
,
963 tor_assert(event
>= EVENT_MIN_
&& event
<= EVENT_MAX_
);
964 queue_control_event_string(event
, tor_strdup(msg
));
967 /** Helper for send_control_event and control_event_status:
968 * Send an event to all v1 controllers that are listening for code
969 * <b>event</b>. The event's body is created by the printf-style format in
970 * <b>format</b>, and other arguments as provided. */
972 send_control_event_impl(uint16_t event
,
973 const char *format
, va_list ap
)
978 len
= tor_vasprintf(&buf
, format
, ap
);
980 log_warn(LD_BUG
, "Unable to format event for controller.");
984 queue_control_event_string(event
, buf
);
987 /** Send an event to all v1 controllers that are listening for code
988 * <b>event</b>. The event's body is created by the printf-style format in
989 * <b>format</b>, and other arguments as provided. */
991 send_control_event(uint16_t event
,
992 const char *format
, ...)
995 va_start(ap
, format
);
996 send_control_event_impl(event
, format
, ap
);
1000 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
1001 static origin_circuit_t
*
1002 get_circ(const char *id
)
1006 n_id
= (uint32_t) tor_parse_ulong(id
, 10, 0, UINT32_MAX
, &ok
, NULL
);
1009 return circuit_get_by_global_id(n_id
);
1012 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
1013 static entry_connection_t
*
1014 get_stream(const char *id
)
1019 n_id
= tor_parse_uint64(id
, 10, 0, UINT64_MAX
, &ok
, NULL
);
1022 conn
= connection_get_by_global_id(n_id
);
1023 if (!conn
|| conn
->type
!= CONN_TYPE_AP
|| conn
->marked_for_close
)
1025 return TO_ENTRY_CONN(conn
);
1028 /** Helper for setconf and resetconf. Acts like setconf, except
1029 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
1033 control_setconf_helper(control_connection_t
*conn
, uint32_t len
, char *body
,
1036 setopt_err_t opt_err
;
1037 config_line_t
*lines
=NULL
;
1039 char *errstring
= NULL
;
1040 const unsigned flags
=
1041 CAL_CLEAR_FIRST
| (use_defaults
? CAL_USE_DEFAULTS
: 0);
1044 smartlist_t
*entries
= smartlist_new();
1046 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
1047 * separated by space. break it into a list of configuration entries. */
1052 while (!TOR_ISSPACE(*eq
) && *eq
!= '=')
1054 key
= tor_strndup(body
, eq
-body
);
1059 if (*body
!= '\"') {
1060 char *val_start
= body
;
1061 while (!TOR_ISSPACE(*body
))
1063 val
= tor_strndup(val_start
, body
-val_start
);
1064 val_len
= strlen(val
);
1066 body
= (char*)extract_escaped_string(body
, (len
- (body
-start
)),
1069 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn
);
1070 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
1071 smartlist_free(entries
);
1076 tor_asprintf(&entry
, "%s %s", key
, val
);
1082 smartlist_add(entries
, entry
);
1083 while (TOR_ISSPACE(*body
))
1087 smartlist_add_strdup(entries
, "");
1088 config
= smartlist_join_strings(entries
, "\n", 0, NULL
);
1089 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
1090 smartlist_free(entries
);
1092 if (config_get_lines(config
, &lines
, 0) < 0) {
1093 log_warn(LD_CONTROL
,"Controller gave us config lines we can't parse.");
1094 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
1101 opt_err
= options_trial_assign(lines
, flags
, &errstring
);
1105 case SETOPT_ERR_MISC
:
1106 msg
= "552 Unrecognized option";
1108 case SETOPT_ERR_PARSE
:
1109 msg
= "513 Unacceptable option value";
1111 case SETOPT_ERR_TRANSITION
:
1112 msg
= "553 Transition not allowed";
1114 case SETOPT_ERR_SETTING
:
1116 msg
= "553 Unable to set option";
1119 config_free_lines(lines
);
1120 send_control_done(conn
);
1123 log_warn(LD_CONTROL
,
1124 "Controller gave us config lines that didn't validate: %s",
1126 connection_printf_to_buf(conn
, "%s: %s\r\n", msg
, errstring
);
1127 config_free_lines(lines
);
1128 tor_free(errstring
);
1133 /** Called when we receive a SETCONF message: parse the body and try
1134 * to update our configuration. Reply with a DONE or ERROR message.
1135 * Modifies the contents of body.*/
1137 handle_control_setconf(control_connection_t
*conn
, uint32_t len
, char *body
)
1139 return control_setconf_helper(conn
, len
, body
, 0);
1142 /** Called when we receive a RESETCONF message: parse the body and try
1143 * to update our configuration. Reply with a DONE or ERROR message.
1144 * Modifies the contents of body. */
1146 handle_control_resetconf(control_connection_t
*conn
, uint32_t len
, char *body
)
1148 return control_setconf_helper(conn
, len
, body
, 1);
1151 /** Called when we receive a GETCONF message. Parse the request, and
1152 * reply with a CONFVALUE or an ERROR message */
1154 handle_control_getconf(control_connection_t
*conn
, uint32_t body_len
,
1157 smartlist_t
*questions
= smartlist_new();
1158 smartlist_t
*answers
= smartlist_new();
1159 smartlist_t
*unrecognized
= smartlist_new();
1162 const or_options_t
*options
= get_options();
1165 (void) body_len
; /* body is NUL-terminated; so we can ignore len. */
1166 smartlist_split_string(questions
, body
, " ",
1167 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1168 SMARTLIST_FOREACH_BEGIN(questions
, const char *, q
) {
1169 if (!option_is_recognized(q
)) {
1170 smartlist_add(unrecognized
, (char*) q
);
1172 config_line_t
*answer
= option_get_assignment(options
,q
);
1174 const char *name
= option_get_canonical_name(q
);
1175 smartlist_add_asprintf(answers
, "250-%s\r\n", name
);
1179 config_line_t
*next
;
1180 smartlist_add_asprintf(answers
, "250-%s=%s\r\n",
1181 answer
->key
, answer
->value
);
1183 next
= answer
->next
;
1184 tor_free(answer
->key
);
1185 tor_free(answer
->value
);
1190 } SMARTLIST_FOREACH_END(q
);
1192 if ((len
= smartlist_len(unrecognized
))) {
1193 for (i
=0; i
< len
-1; ++i
)
1194 connection_printf_to_buf(conn
,
1195 "552-Unrecognized configuration key \"%s\"\r\n",
1196 (char*)smartlist_get(unrecognized
, i
));
1197 connection_printf_to_buf(conn
,
1198 "552 Unrecognized configuration key \"%s\"\r\n",
1199 (char*)smartlist_get(unrecognized
, len
-1));
1200 } else if ((len
= smartlist_len(answers
))) {
1201 char *tmp
= smartlist_get(answers
, len
-1);
1202 tor_assert(strlen(tmp
)>4);
1204 msg
= smartlist_join_strings(answers
, "", 0, &msg_len
);
1205 connection_buf_add(msg
, msg_len
, TO_CONN(conn
));
1207 connection_write_str_to_buf("250 OK\r\n", conn
);
1210 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
1211 smartlist_free(answers
);
1212 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
1213 smartlist_free(questions
);
1214 smartlist_free(unrecognized
);
1221 /** Called when we get a +LOADCONF message. */
1223 handle_control_loadconf(control_connection_t
*conn
, uint32_t len
,
1226 setopt_err_t retval
;
1227 char *errstring
= NULL
;
1228 const char *msg
= NULL
;
1231 retval
= options_init_from_string(NULL
, body
, CMD_RUN_TOR
, NULL
, &errstring
);
1233 if (retval
!= SETOPT_OK
)
1234 log_warn(LD_CONTROL
,
1235 "Controller gave us config file that didn't validate: %s",
1239 case SETOPT_ERR_PARSE
:
1240 msg
= "552 Invalid config file";
1242 case SETOPT_ERR_TRANSITION
:
1243 msg
= "553 Transition not allowed";
1245 case SETOPT_ERR_SETTING
:
1246 msg
= "553 Unable to set option";
1248 case SETOPT_ERR_MISC
:
1250 msg
= "550 Unable to load config";
1257 connection_printf_to_buf(conn
, "%s: %s\r\n", msg
, errstring
);
1259 connection_printf_to_buf(conn
, "%s\r\n", msg
);
1261 send_control_done(conn
);
1263 tor_free(errstring
);
1267 /** Helper structure: maps event values to their names. */
1268 struct control_event_t
{
1269 uint16_t event_code
;
1270 const char *event_name
;
1272 /** Table mapping event values to their names. Used to implement SETEVENTS
1273 * and GETINFO events/names, and to keep they in sync. */
1274 static const struct control_event_t control_event_table
[] = {
1275 { EVENT_CIRCUIT_STATUS
, "CIRC" },
1276 { EVENT_CIRCUIT_STATUS_MINOR
, "CIRC_MINOR" },
1277 { EVENT_STREAM_STATUS
, "STREAM" },
1278 { EVENT_OR_CONN_STATUS
, "ORCONN" },
1279 { EVENT_BANDWIDTH_USED
, "BW" },
1280 { EVENT_DEBUG_MSG
, "DEBUG" },
1281 { EVENT_INFO_MSG
, "INFO" },
1282 { EVENT_NOTICE_MSG
, "NOTICE" },
1283 { EVENT_WARN_MSG
, "WARN" },
1284 { EVENT_ERR_MSG
, "ERR" },
1285 { EVENT_NEW_DESC
, "NEWDESC" },
1286 { EVENT_ADDRMAP
, "ADDRMAP" },
1287 { EVENT_DESCCHANGED
, "DESCCHANGED" },
1289 { EVENT_STATUS_GENERAL
, "STATUS_GENERAL" },
1290 { EVENT_STATUS_CLIENT
, "STATUS_CLIENT" },
1291 { EVENT_STATUS_SERVER
, "STATUS_SERVER" },
1292 { EVENT_GUARD
, "GUARD" },
1293 { EVENT_STREAM_BANDWIDTH_USED
, "STREAM_BW" },
1294 { EVENT_CLIENTS_SEEN
, "CLIENTS_SEEN" },
1295 { EVENT_NEWCONSENSUS
, "NEWCONSENSUS" },
1296 { EVENT_BUILDTIMEOUT_SET
, "BUILDTIMEOUT_SET" },
1297 { EVENT_GOT_SIGNAL
, "SIGNAL" },
1298 { EVENT_CONF_CHANGED
, "CONF_CHANGED"},
1299 { EVENT_CONN_BW
, "CONN_BW" },
1300 { EVENT_CELL_STATS
, "CELL_STATS" },
1301 { EVENT_CIRC_BANDWIDTH_USED
, "CIRC_BW" },
1302 { EVENT_TRANSPORT_LAUNCHED
, "TRANSPORT_LAUNCHED" },
1303 { EVENT_HS_DESC
, "HS_DESC" },
1304 { EVENT_HS_DESC_CONTENT
, "HS_DESC_CONTENT" },
1305 { EVENT_NETWORK_LIVENESS
, "NETWORK_LIVENESS" },
1309 /** Called when we get a SETEVENTS message: update conn->event_mask,
1310 * and reply with DONE or ERROR. */
1312 handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
1316 event_mask_t event_mask
= 0;
1317 smartlist_t
*events
= smartlist_new();
1321 smartlist_split_string(events
, body
, " ",
1322 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1323 SMARTLIST_FOREACH_BEGIN(events
, const char *, ev
)
1325 if (!strcasecmp(ev
, "EXTENDED") ||
1326 !strcasecmp(ev
, "AUTHDIR_NEWDESCS")) {
1327 log_warn(LD_CONTROL
, "The \"%s\" SETEVENTS argument is no longer "
1334 for (i
= 0; control_event_table
[i
].event_name
!= NULL
; ++i
) {
1335 if (!strcasecmp(ev
, control_event_table
[i
].event_name
)) {
1336 event_code
= control_event_table
[i
].event_code
;
1341 if (event_code
== -1) {
1342 connection_printf_to_buf(conn
, "552 Unrecognized event \"%s\"\r\n",
1344 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
1345 smartlist_free(events
);
1349 event_mask
|= (((event_mask_t
)1) << event_code
);
1351 SMARTLIST_FOREACH_END(ev
);
1352 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
1353 smartlist_free(events
);
1355 conn
->event_mask
= event_mask
;
1357 control_update_global_event_mask();
1358 send_control_done(conn
);
1362 /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
1363 * Return a smartlist of acceptable passwords (unterminated strings of
1364 * length S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on
1368 decode_hashed_passwords(config_line_t
*passwords
)
1372 smartlist_t
*sl
= smartlist_new();
1374 tor_assert(passwords
);
1376 for (cl
= passwords
; cl
; cl
= cl
->next
) {
1377 const char *hashed
= cl
->value
;
1379 if (!strcmpstart(hashed
, "16:")) {
1380 if (base16_decode(decoded
, sizeof(decoded
), hashed
+3, strlen(hashed
+3))
1381 != S2K_RFC2440_SPECIFIER_LEN
+ DIGEST_LEN
1382 || strlen(hashed
+3) != (S2K_RFC2440_SPECIFIER_LEN
+DIGEST_LEN
)*2) {
1386 if (base64_decode(decoded
, sizeof(decoded
), hashed
, strlen(hashed
))
1387 != S2K_RFC2440_SPECIFIER_LEN
+DIGEST_LEN
) {
1392 tor_memdup(decoded
, S2K_RFC2440_SPECIFIER_LEN
+DIGEST_LEN
));
1398 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
1403 /** Called when we get an AUTHENTICATE message. Check whether the
1404 * authentication is valid, and if so, update the connection's state to
1405 * OPEN. Reply with DONE or ERROR.
1408 handle_control_authenticate(control_connection_t
*conn
, uint32_t len
,
1411 int used_quoted_string
= 0;
1412 const or_options_t
*options
= get_options();
1413 const char *errstr
= "Unknown error";
1415 size_t password_len
;
1418 int bad_cookie
=0, bad_password
=0;
1419 smartlist_t
*sl
= NULL
;
1422 password
= tor_strdup("");
1424 } else if (TOR_ISXDIGIT(body
[0])) {
1426 while (TOR_ISXDIGIT(*cp
))
1428 i
= (int)(cp
- body
);
1431 password
= tor_malloc(password_len
+ 1);
1432 if (base16_decode(password
, password_len
+1, body
, i
)
1433 != (int) password_len
) {
1434 connection_write_str_to_buf(
1435 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1436 "password? If so, the standard requires that you put it in "
1437 "double quotes.\r\n", conn
);
1438 connection_mark_for_close(TO_CONN(conn
));
1443 if (!decode_escaped_string(body
, len
, &password
, &password_len
)) {
1444 connection_write_str_to_buf("551 Invalid quoted string. You need "
1445 "to put the password in double quotes.\r\n", conn
);
1446 connection_mark_for_close(TO_CONN(conn
));
1449 used_quoted_string
= 1;
1452 if (conn
->safecookie_client_hash
!= NULL
) {
1453 /* The controller has chosen safe cookie authentication; the only
1454 * acceptable authentication value is the controller-to-server
1457 tor_assert(authentication_cookie_is_set
);
1459 if (password_len
!= DIGEST256_LEN
) {
1460 log_warn(LD_CONTROL
,
1461 "Got safe cookie authentication response with wrong length "
1462 "(%d)", (int)password_len
);
1463 errstr
= "Wrong length for safe cookie response.";
1467 if (tor_memneq(conn
->safecookie_client_hash
, password
, DIGEST256_LEN
)) {
1468 log_warn(LD_CONTROL
,
1469 "Got incorrect safe cookie authentication response");
1470 errstr
= "Safe cookie response did not match expected value.";
1474 tor_free(conn
->safecookie_client_hash
);
1478 if (!options
->CookieAuthentication
&& !options
->HashedControlPassword
&&
1479 !options
->HashedControlSessionPassword
) {
1480 /* if Tor doesn't demand any stronger authentication, then
1481 * the controller can get in with anything. */
1485 if (options
->CookieAuthentication
) {
1486 int also_password
= options
->HashedControlPassword
!= NULL
||
1487 options
->HashedControlSessionPassword
!= NULL
;
1488 if (password_len
!= AUTHENTICATION_COOKIE_LEN
) {
1489 if (!also_password
) {
1490 log_warn(LD_CONTROL
, "Got authentication cookie with wrong length "
1491 "(%d)", (int)password_len
);
1492 errstr
= "Wrong length on authentication cookie.";
1496 } else if (tor_memneq(authentication_cookie
, password
, password_len
)) {
1497 if (!also_password
) {
1498 log_warn(LD_CONTROL
, "Got mismatched authentication cookie");
1499 errstr
= "Authentication cookie did not match expected value.";
1508 if (options
->HashedControlPassword
||
1509 options
->HashedControlSessionPassword
) {
1511 smartlist_t
*sl_tmp
;
1512 char received
[DIGEST_LEN
];
1513 int also_cookie
= options
->CookieAuthentication
;
1514 sl
= smartlist_new();
1515 if (options
->HashedControlPassword
) {
1516 sl_tmp
= decode_hashed_passwords(options
->HashedControlPassword
);
1520 smartlist_add_all(sl
, sl_tmp
);
1521 smartlist_free(sl_tmp
);
1524 if (options
->HashedControlSessionPassword
) {
1525 sl_tmp
= decode_hashed_passwords(options
->HashedControlSessionPassword
);
1529 smartlist_add_all(sl
, sl_tmp
);
1530 smartlist_free(sl_tmp
);
1536 "Couldn't decode HashedControlPassword: invalid base16");
1537 errstr
="Couldn't decode HashedControlPassword value in configuration.";
1541 SMARTLIST_FOREACH(sl
, char *, str
, tor_free(str
));
1545 SMARTLIST_FOREACH(sl
, char *, expected
,
1547 secret_to_key_rfc2440(received
,DIGEST_LEN
,
1548 password
,password_len
,expected
);
1549 if (tor_memeq(expected
+ S2K_RFC2440_SPECIFIER_LEN
,
1550 received
, DIGEST_LEN
))
1553 SMARTLIST_FOREACH(sl
, char *, str
, tor_free(str
));
1557 if (used_quoted_string
)
1558 errstr
= "Password did not match HashedControlPassword value from "
1561 errstr
= "Password did not match HashedControlPassword value from "
1562 "configuration. Maybe you tried a plain text password? "
1563 "If so, the standard requires that you put it in double quotes.";
1570 /** We only get here if both kinds of authentication failed. */
1571 tor_assert(bad_password
&& bad_cookie
);
1572 log_warn(LD_CONTROL
, "Bad password or authentication cookie on controller.");
1573 errstr
= "Password did not match HashedControlPassword *or* authentication "
1578 connection_printf_to_buf(conn
, "515 Authentication failed: %s\r\n", errstr
);
1579 connection_mark_for_close(TO_CONN(conn
));
1580 if (sl
) { /* clean up */
1581 SMARTLIST_FOREACH(sl
, char *, str
, tor_free(str
));
1586 log_info(LD_CONTROL
, "Authenticated control connection ("TOR_SOCKET_T_FORMAT
1587 ")", conn
->base_
.s
);
1588 send_control_done(conn
);
1589 conn
->base_
.state
= CONTROL_CONN_STATE_OPEN
;
1591 if (sl
) { /* clean up */
1592 SMARTLIST_FOREACH(sl
, char *, str
, tor_free(str
));
1598 /** Called when we get a SAVECONF command. Try to flush the current options to
1599 * disk, and report success or failure. */
1601 handle_control_saveconf(control_connection_t
*conn
, uint32_t len
,
1606 int force
= !strcmpstart(body
, "FORCE");
1607 const or_options_t
*options
= get_options();
1608 if ((!force
&& options
->IncludeUsed
) || options_save_current() < 0) {
1609 connection_write_str_to_buf(
1610 "551 Unable to write configuration to disk.\r\n", conn
);
1612 send_control_done(conn
);
1619 const char *signal_name
;
1622 static const struct signal_t signal_table
[] = {
1623 { SIGHUP
, "RELOAD" },
1625 { SIGINT
, "SHUTDOWN" },
1626 { SIGUSR1
, "DUMP" },
1627 { SIGUSR1
, "USR1" },
1628 { SIGUSR2
, "DEBUG" },
1629 { SIGUSR2
, "USR2" },
1630 { SIGTERM
, "HALT" },
1631 { SIGTERM
, "TERM" },
1633 { SIGNEWNYM
, "NEWNYM" },
1634 { SIGCLEARDNSCACHE
, "CLEARDNSCACHE"},
1635 { SIGHEARTBEAT
, "HEARTBEAT"},
1639 /** Called when we get a SIGNAL command. React to the provided signal, and
1640 * report success or failure. (If the signal results in a shutdown, success
1641 * may not be reported.) */
1643 handle_control_signal(control_connection_t
*conn
, uint32_t len
,
1653 while (body
[n
] && ! TOR_ISSPACE(body
[n
]))
1655 s
= tor_strndup(body
, n
);
1657 for (i
= 0; signal_table
[i
].signal_name
!= NULL
; ++i
) {
1658 if (!strcasecmp(s
, signal_table
[i
].signal_name
)) {
1659 sig
= signal_table
[i
].sig
;
1665 connection_printf_to_buf(conn
, "552 Unrecognized signal code \"%s\"\r\n",
1671 send_control_done(conn
);
1672 /* Flush the "done" first if the signal might make us shut down. */
1673 if (sig
== SIGTERM
|| sig
== SIGINT
)
1674 connection_flush(TO_CONN(conn
));
1676 activate_signal(sig
);
1681 /** Called when we get a TAKEOWNERSHIP command. Mark this connection
1682 * as an owning connection, so that we will exit if the connection
1685 handle_control_takeownership(control_connection_t
*conn
, uint32_t len
,
1691 conn
->is_owning_control_connection
= 1;
1693 log_info(LD_CONTROL
, "Control connection %d has taken ownership of this "
1695 (int)(conn
->base_
.s
));
1697 send_control_done(conn
);
1701 /** Return true iff <b>addr</b> is unusable as a mapaddress target because of
1702 * containing funny characters. */
1704 address_is_invalid_mapaddress_target(const char *addr
)
1706 if (!strcmpstart(addr
, "*."))
1707 return address_is_invalid_destination(addr
+2, 1);
1709 return address_is_invalid_destination(addr
, 1);
1712 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1713 * and report success or failure. */
1715 handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
1723 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
1725 lines
= smartlist_new();
1726 elts
= smartlist_new();
1727 reply
= smartlist_new();
1728 smartlist_split_string(lines
, body
, " ",
1729 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1730 SMARTLIST_FOREACH_BEGIN(lines
, char *, line
) {
1732 smartlist_split_string(elts
, line
, "=", 0, 2);
1733 if (smartlist_len(elts
) == 2) {
1734 const char *from
= smartlist_get(elts
,0);
1735 const char *to
= smartlist_get(elts
,1);
1736 if (address_is_invalid_mapaddress_target(to
)) {
1737 smartlist_add_asprintf(reply
,
1738 "512-syntax error: invalid address '%s'", to
);
1739 log_warn(LD_CONTROL
,
1740 "Skipping invalid argument '%s' in MapAddress msg", to
);
1741 } else if (!strcmp(from
, ".") || !strcmp(from
, "0.0.0.0") ||
1742 !strcmp(from
, "::")) {
1744 !strcmp(from
,".") ? RESOLVED_TYPE_HOSTNAME
:
1745 (!strcmp(from
, "0.0.0.0") ? RESOLVED_TYPE_IPV4
: RESOLVED_TYPE_IPV6
);
1746 const char *address
= addressmap_register_virtual_address(
1747 type
, tor_strdup(to
));
1749 smartlist_add_asprintf(reply
,
1750 "451-resource exhausted: skipping '%s'", line
);
1751 log_warn(LD_CONTROL
,
1752 "Unable to allocate address for '%s' in MapAddress msg",
1753 safe_str_client(line
));
1755 smartlist_add_asprintf(reply
, "250-%s=%s", address
, to
);
1759 if (addressmap_register_auto(from
, to
, 1,
1760 ADDRMAPSRC_CONTROLLER
, &msg
) < 0) {
1761 smartlist_add_asprintf(reply
,
1762 "512-syntax error: invalid address mapping "
1763 " '%s': %s", line
, msg
);
1764 log_warn(LD_CONTROL
,
1765 "Skipping invalid argument '%s' in MapAddress msg: %s",
1768 smartlist_add_asprintf(reply
, "250-%s", line
);
1772 smartlist_add_asprintf(reply
, "512-syntax error: mapping '%s' is "
1773 "not of expected form 'foo=bar'.", line
);
1774 log_info(LD_CONTROL
, "Skipping MapAddress '%s': wrong "
1776 safe_str_client(line
));
1778 SMARTLIST_FOREACH(elts
, char *, cp
, tor_free(cp
));
1779 smartlist_clear(elts
);
1780 } SMARTLIST_FOREACH_END(line
);
1781 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
1782 smartlist_free(lines
);
1783 smartlist_free(elts
);
1785 if (smartlist_len(reply
)) {
1786 ((char*)smartlist_get(reply
,smartlist_len(reply
)-1))[3] = ' ';
1787 r
= smartlist_join_strings(reply
, "\r\n", 1, &sz
);
1788 connection_buf_add(r
, sz
, TO_CONN(conn
));
1791 const char *response
=
1792 "512 syntax error: not enough arguments to mapaddress.\r\n";
1793 connection_buf_add(response
, strlen(response
), TO_CONN(conn
));
1796 SMARTLIST_FOREACH(reply
, char *, cp
, tor_free(cp
));
1797 smartlist_free(reply
);
1801 /** Implementation helper for GETINFO: knows the answers for various
1802 * trivial-to-implement questions. */
1804 getinfo_helper_misc(control_connection_t
*conn
, const char *question
,
1805 char **answer
, const char **errmsg
)
1808 if (!strcmp(question
, "version")) {
1809 *answer
= tor_strdup(get_version());
1810 } else if (!strcmp(question
, "bw-event-cache")) {
1811 *answer
= get_bw_samples();
1812 } else if (!strcmp(question
, "config-file")) {
1813 const char *a
= get_torrc_fname(0);
1815 *answer
= tor_strdup(a
);
1816 } else if (!strcmp(question
, "config-defaults-file")) {
1817 const char *a
= get_torrc_fname(1);
1819 *answer
= tor_strdup(a
);
1820 } else if (!strcmp(question
, "config-text")) {
1821 *answer
= options_dump(get_options(), OPTIONS_DUMP_MINIMAL
);
1822 } else if (!strcmp(question
, "config-can-saveconf")) {
1823 *answer
= tor_strdup(get_options()->IncludeUsed
? "0" : "1");
1824 } else if (!strcmp(question
, "info/names")) {
1825 *answer
= list_getinfo_options();
1826 } else if (!strcmp(question
, "dormant")) {
1827 int dormant
= rep_hist_circbuilding_dormant(time(NULL
));
1828 *answer
= tor_strdup(dormant
? "1" : "0");
1829 } else if (!strcmp(question
, "events/names")) {
1831 smartlist_t
*event_names
= smartlist_new();
1833 for (i
= 0; control_event_table
[i
].event_name
!= NULL
; ++i
) {
1834 smartlist_add(event_names
, (char *)control_event_table
[i
].event_name
);
1837 *answer
= smartlist_join_strings(event_names
, " ", 0, NULL
);
1839 smartlist_free(event_names
);
1840 } else if (!strcmp(question
, "signal/names")) {
1841 smartlist_t
*signal_names
= smartlist_new();
1843 for (j
= 0; signal_table
[j
].signal_name
!= NULL
; ++j
) {
1844 smartlist_add(signal_names
, (char*)signal_table
[j
].signal_name
);
1847 *answer
= smartlist_join_strings(signal_names
, " ", 0, NULL
);
1849 smartlist_free(signal_names
);
1850 } else if (!strcmp(question
, "features/names")) {
1851 *answer
= tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1852 } else if (!strcmp(question
, "address")) {
1854 if (router_pick_published_address(get_options(), &addr
, 0) < 0) {
1855 *errmsg
= "Address unknown";
1858 *answer
= tor_dup_ip(addr
);
1859 } else if (!strcmp(question
, "traffic/read")) {
1860 tor_asprintf(answer
, U64_FORMAT
, U64_PRINTF_ARG(get_bytes_read()));
1861 } else if (!strcmp(question
, "traffic/written")) {
1862 tor_asprintf(answer
, U64_FORMAT
, U64_PRINTF_ARG(get_bytes_written()));
1863 } else if (!strcmp(question
, "process/pid")) {
1872 tor_asprintf(answer
, "%d", myPid
);
1873 } else if (!strcmp(question
, "process/uid")) {
1875 *answer
= tor_strdup("-1");
1877 int myUid
= geteuid();
1878 tor_asprintf(answer
, "%d", myUid
);
1879 #endif /* defined(_WIN32) */
1880 } else if (!strcmp(question
, "process/user")) {
1882 *answer
= tor_strdup("");
1884 int myUid
= geteuid();
1885 const struct passwd
*myPwEntry
= tor_getpwuid(myUid
);
1888 *answer
= tor_strdup(myPwEntry
->pw_name
);
1890 *answer
= tor_strdup("");
1892 #endif /* defined(_WIN32) */
1893 } else if (!strcmp(question
, "process/descriptor-limit")) {
1894 int max_fds
= get_max_sockets();
1895 tor_asprintf(answer
, "%d", max_fds
);
1896 } else if (!strcmp(question
, "limits/max-mem-in-queues")) {
1897 tor_asprintf(answer
, U64_FORMAT
,
1898 U64_PRINTF_ARG(get_options()->MaxMemInQueues
));
1899 } else if (!strcmp(question
, "fingerprint")) {
1900 crypto_pk_t
*server_key
;
1901 if (!server_mode(get_options())) {
1902 *errmsg
= "Not running in server mode";
1905 server_key
= get_server_identity_key();
1906 *answer
= tor_malloc(HEX_DIGEST_LEN
+1);
1907 crypto_pk_get_fingerprint(server_key
, *answer
, 0);
1912 /** Awful hack: return a newly allocated string based on a routerinfo and
1913 * (possibly) an extrainfo, sticking the read-history and write-history from
1914 * <b>ei</b> into the resulting string. The thing you get back won't
1915 * necessarily have a valid signature.
1917 * New code should never use this; it's for backward compatibility.
1919 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1920 * not be NUL-terminated. */
1922 munge_extrainfo_into_routerinfo(const char *ri_body
,
1923 const signed_descriptor_t
*ri
,
1924 const signed_descriptor_t
*ei
)
1926 char *out
= NULL
, *outp
;
1928 const char *router_sig
;
1929 const char *ei_body
= signed_descriptor_get_body(ei
);
1930 size_t ri_len
= ri
->signed_descriptor_len
;
1931 size_t ei_len
= ei
->signed_descriptor_len
;
1935 outp
= out
= tor_malloc(ri_len
+ei_len
+1);
1936 if (!(router_sig
= tor_memstr(ri_body
, ri_len
, "\nrouter-signature")))
1939 memcpy(out
, ri_body
, router_sig
-ri_body
);
1940 outp
+= router_sig
-ri_body
;
1942 for (i
=0; i
< 2; ++i
) {
1943 const char *kwd
= i
? "\nwrite-history " : "\nread-history ";
1944 const char *cp
, *eol
;
1945 if (!(cp
= tor_memstr(ei_body
, ei_len
, kwd
)))
1948 if (!(eol
= memchr(cp
, '\n', ei_len
- (cp
-ei_body
))))
1950 memcpy(outp
, cp
, eol
-cp
+1);
1953 memcpy(outp
, router_sig
, ri_len
- (router_sig
-ri_body
));
1955 tor_assert(outp
-out
< (int)(ri_len
+ei_len
+1));
1960 return tor_strndup(ri_body
, ri
->signed_descriptor_len
);
1963 /** Implementation helper for GETINFO: answers requests for information about
1964 * which ports are bound. */
1966 getinfo_helper_listeners(control_connection_t
*control_conn
,
1967 const char *question
,
1968 char **answer
, const char **errmsg
)
1976 if (!strcmp(question
, "net/listeners/or"))
1977 type
= CONN_TYPE_OR_LISTENER
;
1978 else if (!strcmp(question
, "net/listeners/extor"))
1979 type
= CONN_TYPE_EXT_OR_LISTENER
;
1980 else if (!strcmp(question
, "net/listeners/dir"))
1981 type
= CONN_TYPE_DIR_LISTENER
;
1982 else if (!strcmp(question
, "net/listeners/socks"))
1983 type
= CONN_TYPE_AP_LISTENER
;
1984 else if (!strcmp(question
, "net/listeners/trans"))
1985 type
= CONN_TYPE_AP_TRANS_LISTENER
;
1986 else if (!strcmp(question
, "net/listeners/natd"))
1987 type
= CONN_TYPE_AP_NATD_LISTENER
;
1988 else if (!strcmp(question
, "net/listeners/httptunnel"))
1989 type
= CONN_TYPE_AP_HTTP_CONNECT_LISTENER
;
1990 else if (!strcmp(question
, "net/listeners/dns"))
1991 type
= CONN_TYPE_AP_DNS_LISTENER
;
1992 else if (!strcmp(question
, "net/listeners/control"))
1993 type
= CONN_TYPE_CONTROL_LISTENER
;
1995 return 0; /* unknown key */
1997 res
= smartlist_new();
1998 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t
*, conn
) {
1999 struct sockaddr_storage ss
;
2000 socklen_t ss_len
= sizeof(ss
);
2002 if (conn
->type
!= type
|| conn
->marked_for_close
|| !SOCKET_OK(conn
->s
))
2005 if (getsockname(conn
->s
, (struct sockaddr
*)&ss
, &ss_len
) < 0) {
2006 smartlist_add_asprintf(res
, "%s:%d", conn
->address
, (int)conn
->port
);
2008 char *tmp
= tor_sockaddr_to_str((struct sockaddr
*)&ss
);
2009 smartlist_add(res
, esc_for_log(tmp
));
2013 } SMARTLIST_FOREACH_END(conn
);
2015 *answer
= smartlist_join_strings(res
, " ", 0, NULL
);
2017 SMARTLIST_FOREACH(res
, char *, cp
, tor_free(cp
));
2018 smartlist_free(res
);
2022 /** Implementation helper for GETINFO: answers requests for information about
2023 * the current time in both local and UTF forms. */
2025 getinfo_helper_current_time(control_connection_t
*control_conn
,
2026 const char *question
,
2027 char **answer
, const char **errmsg
)
2033 tor_gettimeofday(&now
);
2034 char timebuf
[ISO_TIME_LEN
+1];
2036 if (!strcmp(question
, "current-time/local"))
2037 format_local_iso_time_nospace(timebuf
, (time_t)now
.tv_sec
);
2038 else if (!strcmp(question
, "current-time/utc"))
2039 format_iso_time_nospace(timebuf
, (time_t)now
.tv_sec
);
2043 *answer
= tor_strdup(timebuf
);
2047 /** Implementation helper for GETINFO: knows the answers for questions about
2048 * directory information. */
2050 getinfo_helper_dir(control_connection_t
*control_conn
,
2051 const char *question
, char **answer
,
2052 const char **errmsg
)
2054 (void) control_conn
;
2055 if (!strcmpstart(question
, "desc/id/")) {
2056 const routerinfo_t
*ri
= NULL
;
2057 const node_t
*node
= node_get_by_hex_id(question
+strlen("desc/id/"), 0);
2061 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
2063 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
2064 } else if (! we_fetch_router_descriptors(get_options())) {
2065 /* Descriptors won't be available, provide proper error */
2066 *errmsg
= "We fetch microdescriptors, not router "
2067 "descriptors. You'll need to use md/id/* "
2068 "instead of desc/id/*.";
2071 } else if (!strcmpstart(question
, "desc/name/")) {
2072 const routerinfo_t
*ri
= NULL
;
2073 /* XXX Setting 'warn_if_unnamed' here is a bit silly -- the
2074 * warning goes to the user, not to the controller. */
2075 const node_t
*node
=
2076 node_get_by_nickname(question
+strlen("desc/name/"), 0);
2080 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
2082 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
2083 } else if (! we_fetch_router_descriptors(get_options())) {
2084 /* Descriptors won't be available, provide proper error */
2085 *errmsg
= "We fetch microdescriptors, not router "
2086 "descriptors. You'll need to use md/name/* "
2087 "instead of desc/name/*.";
2090 } else if (!strcmp(question
, "desc/download-enabled")) {
2091 int r
= we_fetch_router_descriptors(get_options());
2092 tor_asprintf(answer
, "%d", !!r
);
2093 } else if (!strcmp(question
, "desc/all-recent")) {
2094 routerlist_t
*routerlist
= router_get_routerlist();
2095 smartlist_t
*sl
= smartlist_new();
2096 if (routerlist
&& routerlist
->routers
) {
2097 SMARTLIST_FOREACH(routerlist
->routers
, const routerinfo_t
*, ri
,
2099 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
2102 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
2105 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
2106 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
2108 } else if (!strcmp(question
, "desc/all-recent-extrainfo-hack")) {
2109 /* XXXX Remove this once Torstat asks for extrainfos. */
2110 routerlist_t
*routerlist
= router_get_routerlist();
2111 smartlist_t
*sl
= smartlist_new();
2112 if (routerlist
&& routerlist
->routers
) {
2113 SMARTLIST_FOREACH_BEGIN(routerlist
->routers
, const routerinfo_t
*, ri
) {
2114 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
2115 signed_descriptor_t
*ei
= extrainfo_get_by_descriptor_digest(
2116 ri
->cache_info
.extra_info_digest
);
2118 smartlist_add(sl
, munge_extrainfo_into_routerinfo(body
,
2119 &ri
->cache_info
, ei
));
2122 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
2124 } SMARTLIST_FOREACH_END(ri
);
2126 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
2127 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
2129 } else if (!strcmpstart(question
, "hs/client/desc/id/")) {
2130 hostname_type_t addr_type
;
2132 question
+= strlen("hs/client/desc/id/");
2133 if (rend_valid_v2_service_id(question
)) {
2134 addr_type
= ONION_V2_HOSTNAME
;
2135 } else if (hs_address_is_valid(question
)) {
2136 addr_type
= ONION_V3_HOSTNAME
;
2138 *errmsg
= "Invalid address";
2142 if (addr_type
== ONION_V2_HOSTNAME
) {
2143 rend_cache_entry_t
*e
= NULL
;
2144 if (!rend_cache_lookup_entry(question
, -1, &e
)) {
2145 /* Descriptor found in cache */
2146 *answer
= tor_strdup(e
->desc
);
2148 *errmsg
= "Not found in cache";
2152 ed25519_public_key_t service_pk
;
2155 /* The check before this if/else makes sure of this. */
2156 tor_assert(addr_type
== ONION_V3_HOSTNAME
);
2158 if (hs_parse_address(question
, &service_pk
, NULL
, NULL
) < 0) {
2159 *errmsg
= "Invalid v3 address";
2163 desc
= hs_cache_lookup_encoded_as_client(&service_pk
);
2165 *answer
= tor_strdup(desc
);
2167 *errmsg
= "Not found in cache";
2171 } else if (!strcmpstart(question
, "hs/service/desc/id/")) {
2172 hostname_type_t addr_type
;
2174 question
+= strlen("hs/service/desc/id/");
2175 if (rend_valid_v2_service_id(question
)) {
2176 addr_type
= ONION_V2_HOSTNAME
;
2177 } else if (hs_address_is_valid(question
)) {
2178 addr_type
= ONION_V3_HOSTNAME
;
2180 *errmsg
= "Invalid address";
2183 rend_cache_entry_t
*e
= NULL
;
2185 if (addr_type
== ONION_V2_HOSTNAME
) {
2186 if (!rend_cache_lookup_v2_desc_as_service(question
, &e
)) {
2187 /* Descriptor found in cache */
2188 *answer
= tor_strdup(e
->desc
);
2190 *errmsg
= "Not found in cache";
2194 ed25519_public_key_t service_pk
;
2197 /* The check before this if/else makes sure of this. */
2198 tor_assert(addr_type
== ONION_V3_HOSTNAME
);
2200 if (hs_parse_address(question
, &service_pk
, NULL
, NULL
) < 0) {
2201 *errmsg
= "Invalid v3 address";
2205 desc
= hs_service_lookup_current_desc(&service_pk
);
2207 /* Newly allocated string, we have ownership. */
2210 *errmsg
= "Not found in cache";
2214 } else if (!strcmpstart(question
, "md/id/")) {
2215 const node_t
*node
= node_get_by_hex_id(question
+strlen("md/id/"), 0);
2216 const microdesc_t
*md
= NULL
;
2217 if (node
) md
= node
->md
;
2218 if (md
&& md
->body
) {
2219 *answer
= tor_strndup(md
->body
, md
->bodylen
);
2221 } else if (!strcmpstart(question
, "md/name/")) {
2222 /* XXX Setting 'warn_if_unnamed' here is a bit silly -- the
2223 * warning goes to the user, not to the controller. */
2224 const node_t
*node
= node_get_by_nickname(question
+strlen("md/name/"), 0);
2225 /* XXXX duplicated code */
2226 const microdesc_t
*md
= NULL
;
2227 if (node
) md
= node
->md
;
2228 if (md
&& md
->body
) {
2229 *answer
= tor_strndup(md
->body
, md
->bodylen
);
2231 } else if (!strcmp(question
, "md/download-enabled")) {
2232 int r
= we_fetch_microdescriptors(get_options());
2233 tor_asprintf(answer
, "%d", !!r
);
2234 } else if (!strcmpstart(question
, "desc-annotations/id/")) {
2235 const routerinfo_t
*ri
= NULL
;
2236 const node_t
*node
=
2237 node_get_by_hex_id(question
+strlen("desc-annotations/id/"), 0);
2241 const char *annotations
=
2242 signed_descriptor_get_annotations(&ri
->cache_info
);
2244 *answer
= tor_strndup(annotations
,
2245 ri
->cache_info
.annotations_len
);
2247 } else if (!strcmpstart(question
, "dir/server/")) {
2248 size_t answer_len
= 0;
2250 smartlist_t
*descs
= smartlist_new();
2254 tor_asprintf(&url
, "/tor/%s", question
+4);
2255 res
= dirserv_get_routerdescs(descs
, url
, &msg
);
2257 log_warn(LD_CONTROL
, "getinfo '%s': %s", question
, msg
);
2258 smartlist_free(descs
);
2263 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
2264 answer_len
+= sd
->signed_descriptor_len
);
2265 cp
= *answer
= tor_malloc(answer_len
+1);
2266 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
2268 memcpy(cp
, signed_descriptor_get_body(sd
),
2269 sd
->signed_descriptor_len
);
2270 cp
+= sd
->signed_descriptor_len
;
2274 smartlist_free(descs
);
2275 } else if (!strcmpstart(question
, "dir/status/")) {
2276 *answer
= tor_strdup("");
2277 } else if (!strcmp(question
, "dir/status-vote/current/consensus")) { /* v3 */
2278 if (we_want_to_fetch_flavor(get_options(), FLAV_NS
)) {
2279 const cached_dir_t
*consensus
= dirserv_get_consensus("ns");
2281 *answer
= tor_strdup(consensus
->dir
);
2283 if (!*answer
) { /* try loading it from disk */
2284 char *filename
= get_cachedir_fname("cached-consensus");
2285 *answer
= read_file_to_str(filename
, RFTS_IGNORE_MISSING
, NULL
);
2287 if (!*answer
) { /* generate an error */
2288 *errmsg
= "Could not open cached consensus. "
2289 "Make sure FetchUselessDescriptors is set to 1.";
2293 } else if (!strcmp(question
, "network-status")) { /* v1 */
2294 static int network_status_warned
= 0;
2295 if (!network_status_warned
) {
2296 log_warn(LD_CONTROL
, "GETINFO network-status is deprecated; it will "
2297 "go away in a future version of Tor.");
2298 network_status_warned
= 1;
2300 routerlist_t
*routerlist
= router_get_routerlist();
2301 if (!routerlist
|| !routerlist
->routers
||
2302 list_server_status_v1(routerlist
->routers
, answer
, 1) < 0) {
2305 } else if (!strcmpstart(question
, "extra-info/digest/")) {
2306 question
+= strlen("extra-info/digest/");
2307 if (strlen(question
) == HEX_DIGEST_LEN
) {
2309 signed_descriptor_t
*sd
= NULL
;
2310 if (base16_decode(d
, sizeof(d
), question
, strlen(question
))
2312 /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
2313 * but I don't want to risk affecting other parts of the code,
2314 * especially since the rules for using our own extrainfo (including
2315 * when it might be freed) are different from those for using one
2316 * we have downloaded. */
2317 if (router_extrainfo_digest_is_me(d
))
2318 sd
= &(router_get_my_extrainfo()->cache_info
);
2320 sd
= extrainfo_get_by_descriptor_digest(d
);
2323 const char *body
= signed_descriptor_get_body(sd
);
2325 *answer
= tor_strndup(body
, sd
->signed_descriptor_len
);
2333 /** Given a smartlist of 20-byte digests, return a newly allocated string
2334 * containing each of those digests in order, formatted in HEX, and terminated
2335 * with a newline. */
2337 digest_list_to_string(const smartlist_t
*sl
)
2342 /* Allow for newlines, and a \0 at the end */
2343 len
= smartlist_len(sl
) * (HEX_DIGEST_LEN
+ 1) + 1;
2344 result
= tor_malloc_zero(len
);
2347 SMARTLIST_FOREACH_BEGIN(sl
, const char *, digest
) {
2348 base16_encode(s
, HEX_DIGEST_LEN
+ 1, digest
, DIGEST_LEN
);
2349 s
[HEX_DIGEST_LEN
] = '\n';
2350 s
+= HEX_DIGEST_LEN
+ 1;
2351 } SMARTLIST_FOREACH_END(digest
);
2357 /** Turn a download_status_t into a human-readable description in a newly
2358 * allocated string. The format is specified in control-spec.txt, under
2359 * the documentation for "GETINFO download/..." . */
2361 download_status_to_string(const download_status_t
*dl
)
2364 char tbuf
[ISO_TIME_LEN
+1];
2365 const char *schedule_str
, *want_authority_str
;
2366 const char *increment_on_str
, *backoff_str
;
2369 /* Get some substrings of the eventual output ready */
2370 format_iso_time(tbuf
, download_status_get_next_attempt_at(dl
));
2372 switch (dl
->schedule
) {
2373 case DL_SCHED_GENERIC
:
2374 schedule_str
= "DL_SCHED_GENERIC";
2376 case DL_SCHED_CONSENSUS
:
2377 schedule_str
= "DL_SCHED_CONSENSUS";
2379 case DL_SCHED_BRIDGE
:
2380 schedule_str
= "DL_SCHED_BRIDGE";
2383 schedule_str
= "unknown";
2387 switch (dl
->want_authority
) {
2388 case DL_WANT_ANY_DIRSERVER
:
2389 want_authority_str
= "DL_WANT_ANY_DIRSERVER";
2391 case DL_WANT_AUTHORITY
:
2392 want_authority_str
= "DL_WANT_AUTHORITY";
2395 want_authority_str
= "unknown";
2399 switch (dl
->increment_on
) {
2400 case DL_SCHED_INCREMENT_FAILURE
:
2401 increment_on_str
= "DL_SCHED_INCREMENT_FAILURE";
2403 case DL_SCHED_INCREMENT_ATTEMPT
:
2404 increment_on_str
= "DL_SCHED_INCREMENT_ATTEMPT";
2407 increment_on_str
= "unknown";
2411 backoff_str
= "DL_SCHED_RANDOM_EXPONENTIAL";
2413 /* Now assemble them */
2415 "next-attempt-at %s\n"
2416 "n-download-failures %u\n"
2417 "n-download-attempts %u\n"
2419 "want-authority %s\n"
2422 "last-backoff-position %u\n"
2423 "last-delay-used %d\n",
2425 dl
->n_download_failures
,
2426 dl
->n_download_attempts
,
2431 dl
->last_backoff_position
,
2432 dl
->last_delay_used
);
2438 /** Handle the consensus download cases for getinfo_helper_downloads() */
2440 getinfo_helper_downloads_networkstatus(const char *flavor
,
2441 download_status_t
**dl_to_emit
,
2442 const char **errmsg
)
2445 * We get the one for the current bootstrapped status by default, or
2446 * take an extra /bootstrap or /running suffix
2448 if (strcmp(flavor
, "ns") == 0) {
2449 *dl_to_emit
= networkstatus_get_dl_status_by_flavor(FLAV_NS
);
2450 } else if (strcmp(flavor
, "ns/bootstrap") == 0) {
2451 *dl_to_emit
= networkstatus_get_dl_status_by_flavor_bootstrap(FLAV_NS
);
2452 } else if (strcmp(flavor
, "ns/running") == 0 ) {
2453 *dl_to_emit
= networkstatus_get_dl_status_by_flavor_running(FLAV_NS
);
2454 } else if (strcmp(flavor
, "microdesc") == 0) {
2455 *dl_to_emit
= networkstatus_get_dl_status_by_flavor(FLAV_MICRODESC
);
2456 } else if (strcmp(flavor
, "microdesc/bootstrap") == 0) {
2458 networkstatus_get_dl_status_by_flavor_bootstrap(FLAV_MICRODESC
);
2459 } else if (strcmp(flavor
, "microdesc/running") == 0) {
2461 networkstatus_get_dl_status_by_flavor_running(FLAV_MICRODESC
);
2463 *errmsg
= "Unknown flavor";
2467 /** Handle the cert download cases for getinfo_helper_downloads() */
2469 getinfo_helper_downloads_cert(const char *fp_sk_req
,
2470 download_status_t
**dl_to_emit
,
2471 smartlist_t
**digest_list
,
2472 const char **errmsg
)
2475 char id_digest
[DIGEST_LEN
];
2476 char sk_digest
[DIGEST_LEN
];
2479 * We have to handle four cases; fp_sk_req is the request with
2480 * a prefix of "downloads/cert/" snipped off.
2482 * Case 1: fp_sk_req = "fps"
2483 * - We should emit a digest_list with a list of all the identity
2484 * fingerprints that can be queried for certificate download status;
2485 * get it by calling list_authority_ids_with_downloads().
2487 * Case 2: fp_sk_req = "fp/<fp>" for some fingerprint fp
2488 * - We want the default certificate for this identity fingerprint's
2489 * download status; this is the download we get from URLs starting
2490 * in /fp/ on the directory server. We can get it with
2491 * id_only_download_status_for_authority_id().
2493 * Case 3: fp_sk_req = "fp/<fp>/sks" for some fingerprint fp
2494 * - We want a list of all signing key digests for this identity
2495 * fingerprint which can be queried for certificate download status.
2496 * Get it with list_sk_digests_for_authority_id().
2498 * Case 4: fp_sk_req = "fp/<fp>/<sk>" for some fingerprint fp and
2499 * signing key digest sk
2500 * - We want the download status for the certificate for this specific
2501 * signing key and fingerprint. These correspond to the ones we get
2502 * from URLs starting in /fp-sk/ on the directory server. Get it with
2503 * list_sk_digests_for_authority_id().
2506 if (strcmp(fp_sk_req
, "fps") == 0) {
2507 *digest_list
= list_authority_ids_with_downloads();
2508 if (!(*digest_list
)) {
2509 *errmsg
= "Failed to get list of authority identity digests (!)";
2511 } else if (!strcmpstart(fp_sk_req
, "fp/")) {
2512 fp_sk_req
+= strlen("fp/");
2513 /* Okay, look for another / to tell the fp from fp-sk cases */
2514 sk_req
= strchr(fp_sk_req
, '/');
2516 /* okay, split it here and try to parse <fp> */
2517 if (base16_decode(id_digest
, DIGEST_LEN
,
2518 fp_sk_req
, sk_req
- fp_sk_req
) == DIGEST_LEN
) {
2519 /* Skip past the '/' */
2521 if (strcmp(sk_req
, "sks") == 0) {
2522 /* We're asking for the list of signing key fingerprints */
2523 *digest_list
= list_sk_digests_for_authority_id(id_digest
);
2524 if (!(*digest_list
)) {
2525 *errmsg
= "Failed to get list of signing key digests for this "
2526 "authority identity digest";
2529 /* We've got a signing key digest */
2530 if (base16_decode(sk_digest
, DIGEST_LEN
,
2531 sk_req
, strlen(sk_req
)) == DIGEST_LEN
) {
2533 download_status_for_authority_id_and_sk(id_digest
, sk_digest
);
2534 if (!(*dl_to_emit
)) {
2535 *errmsg
= "Failed to get download status for this identity/"
2536 "signing key digest pair";
2539 *errmsg
= "That didn't look like a signing key digest";
2543 *errmsg
= "That didn't look like an identity digest";
2546 /* We're either in downloads/certs/fp/<fp>, or we can't parse <fp> */
2547 if (strlen(fp_sk_req
) == HEX_DIGEST_LEN
) {
2548 if (base16_decode(id_digest
, DIGEST_LEN
,
2549 fp_sk_req
, strlen(fp_sk_req
)) == DIGEST_LEN
) {
2550 *dl_to_emit
= id_only_download_status_for_authority_id(id_digest
);
2551 if (!(*dl_to_emit
)) {
2552 *errmsg
= "Failed to get download status for this authority "
2556 *errmsg
= "That didn't look like a digest";
2559 *errmsg
= "That didn't look like a digest";
2563 *errmsg
= "Unknown certificate download status query";
2567 /** Handle the routerdesc download cases for getinfo_helper_downloads() */
2569 getinfo_helper_downloads_desc(const char *desc_req
,
2570 download_status_t
**dl_to_emit
,
2571 smartlist_t
**digest_list
,
2572 const char **errmsg
)
2574 char desc_digest
[DIGEST_LEN
];
2576 * Two cases to handle here:
2578 * Case 1: desc_req = "descs"
2579 * - Emit a list of all router descriptor digests, which we get by
2580 * calling router_get_descriptor_digests(); this can return NULL
2581 * if we have no current ns-flavor consensus.
2583 * Case 2: desc_req = <fp>
2584 * - Check on the specified fingerprint and emit its download_status_t
2585 * using router_get_dl_status_by_descriptor_digest().
2588 if (strcmp(desc_req
, "descs") == 0) {
2589 *digest_list
= router_get_descriptor_digests();
2590 if (!(*digest_list
)) {
2591 *errmsg
= "We don't seem to have a networkstatus-flavored consensus";
2594 * Microdescs don't use the download_status_t mechanism, so we don't
2595 * answer queries about their downloads here; see microdesc.c.
2597 } else if (strlen(desc_req
) == HEX_DIGEST_LEN
) {
2598 if (base16_decode(desc_digest
, DIGEST_LEN
,
2599 desc_req
, strlen(desc_req
)) == DIGEST_LEN
) {
2600 /* Okay we got a digest-shaped thing; try asking for it */
2601 *dl_to_emit
= router_get_dl_status_by_descriptor_digest(desc_digest
);
2602 if (!(*dl_to_emit
)) {
2603 *errmsg
= "No such descriptor digest found";
2606 *errmsg
= "That didn't look like a digest";
2609 *errmsg
= "Unknown router descriptor download status query";
2613 /** Handle the bridge download cases for getinfo_helper_downloads() */
2615 getinfo_helper_downloads_bridge(const char *bridge_req
,
2616 download_status_t
**dl_to_emit
,
2617 smartlist_t
**digest_list
,
2618 const char **errmsg
)
2620 char bridge_digest
[DIGEST_LEN
];
2622 * Two cases to handle here:
2624 * Case 1: bridge_req = "bridges"
2625 * - Emit a list of all bridge identity digests, which we get by
2626 * calling list_bridge_identities(); this can return NULL if we are
2627 * not using bridges.
2629 * Case 2: bridge_req = <fp>
2630 * - Check on the specified fingerprint and emit its download_status_t
2631 * using get_bridge_dl_status_by_id().
2634 if (strcmp(bridge_req
, "bridges") == 0) {
2635 *digest_list
= list_bridge_identities();
2636 if (!(*digest_list
)) {
2637 *errmsg
= "We don't seem to be using bridges";
2639 } else if (strlen(bridge_req
) == HEX_DIGEST_LEN
) {
2640 if (base16_decode(bridge_digest
, DIGEST_LEN
,
2641 bridge_req
, strlen(bridge_req
)) == DIGEST_LEN
) {
2642 /* Okay we got a digest-shaped thing; try asking for it */
2643 *dl_to_emit
= get_bridge_dl_status_by_id(bridge_digest
);
2644 if (!(*dl_to_emit
)) {
2645 *errmsg
= "No such bridge identity digest found";
2648 *errmsg
= "That didn't look like a digest";
2651 *errmsg
= "Unknown bridge descriptor download status query";
2655 /** Implementation helper for GETINFO: knows the answers for questions about
2656 * download status information. */
2658 getinfo_helper_downloads(control_connection_t
*control_conn
,
2659 const char *question
, char **answer
,
2660 const char **errmsg
)
2662 download_status_t
*dl_to_emit
= NULL
;
2663 smartlist_t
*digest_list
= NULL
;
2665 /* Assert args are sane */
2666 tor_assert(control_conn
!= NULL
);
2667 tor_assert(question
!= NULL
);
2668 tor_assert(answer
!= NULL
);
2669 tor_assert(errmsg
!= NULL
);
2671 /* We check for this later to see if we should supply a default */
2674 /* Are we after networkstatus downloads? */
2675 if (!strcmpstart(question
, "downloads/networkstatus/")) {
2676 getinfo_helper_downloads_networkstatus(
2677 question
+ strlen("downloads/networkstatus/"),
2678 &dl_to_emit
, errmsg
);
2680 } else if (!strcmpstart(question
, "downloads/cert/")) {
2681 getinfo_helper_downloads_cert(
2682 question
+ strlen("downloads/cert/"),
2683 &dl_to_emit
, &digest_list
, errmsg
);
2684 /* Router descriptors? */
2685 } else if (!strcmpstart(question
, "downloads/desc/")) {
2686 getinfo_helper_downloads_desc(
2687 question
+ strlen("downloads/desc/"),
2688 &dl_to_emit
, &digest_list
, errmsg
);
2689 /* Bridge descriptors? */
2690 } else if (!strcmpstart(question
, "downloads/bridge/")) {
2691 getinfo_helper_downloads_bridge(
2692 question
+ strlen("downloads/bridge/"),
2693 &dl_to_emit
, &digest_list
, errmsg
);
2695 *errmsg
= "Unknown download status query";
2699 *answer
= download_status_to_string(dl_to_emit
);
2702 } else if (digest_list
) {
2703 *answer
= digest_list_to_string(digest_list
);
2704 SMARTLIST_FOREACH(digest_list
, void *, s
, tor_free(s
));
2705 smartlist_free(digest_list
);
2710 *errmsg
= "Unknown error";
2717 /** Allocate and return a description of <b>circ</b>'s current status,
2718 * including its path (if any). */
2720 circuit_describe_status_for_controller(origin_circuit_t
*circ
)
2723 smartlist_t
*descparts
= smartlist_new();
2726 char *vpath
= circuit_list_path_for_controller(circ
);
2728 smartlist_add(descparts
, vpath
);
2730 tor_free(vpath
); /* empty path; don't put an extra space in the result */
2735 cpath_build_state_t
*build_state
= circ
->build_state
;
2736 smartlist_t
*flaglist
= smartlist_new();
2737 char *flaglist_joined
;
2739 if (build_state
->onehop_tunnel
)
2740 smartlist_add(flaglist
, (void *)"ONEHOP_TUNNEL");
2741 if (build_state
->is_internal
)
2742 smartlist_add(flaglist
, (void *)"IS_INTERNAL");
2743 if (build_state
->need_capacity
)
2744 smartlist_add(flaglist
, (void *)"NEED_CAPACITY");
2745 if (build_state
->need_uptime
)
2746 smartlist_add(flaglist
, (void *)"NEED_UPTIME");
2748 /* Only emit a BUILD_FLAGS argument if it will have a non-empty value. */
2749 if (smartlist_len(flaglist
)) {
2750 flaglist_joined
= smartlist_join_strings(flaglist
, ",", 0, NULL
);
2752 smartlist_add_asprintf(descparts
, "BUILD_FLAGS=%s", flaglist_joined
);
2754 tor_free(flaglist_joined
);
2757 smartlist_free(flaglist
);
2760 smartlist_add_asprintf(descparts
, "PURPOSE=%s",
2761 circuit_purpose_to_controller_string(circ
->base_
.purpose
));
2764 const char *hs_state
=
2765 circuit_purpose_to_controller_hs_state_string(circ
->base_
.purpose
);
2767 if (hs_state
!= NULL
) {
2768 smartlist_add_asprintf(descparts
, "HS_STATE=%s", hs_state
);
2772 if (circ
->rend_data
!= NULL
|| circ
->hs_ident
!= NULL
) {
2773 char addr
[HS_SERVICE_ADDR_LEN_BASE32
+ 1];
2774 const char *onion_address
;
2775 if (circ
->rend_data
) {
2776 onion_address
= rend_data_get_address(circ
->rend_data
);
2778 hs_build_address(&circ
->hs_ident
->identity_pk
, HS_VERSION_THREE
, addr
);
2779 onion_address
= addr
;
2781 smartlist_add_asprintf(descparts
, "REND_QUERY=%s", onion_address
);
2785 char tbuf
[ISO_TIME_USEC_LEN
+1];
2786 format_iso_time_nospace_usec(tbuf
, &circ
->base_
.timestamp_created
);
2788 smartlist_add_asprintf(descparts
, "TIME_CREATED=%s", tbuf
);
2791 // Show username and/or password if available.
2792 if (circ
->socks_username_len
> 0) {
2793 char* socks_username_escaped
= esc_for_log_len(circ
->socks_username
,
2794 (size_t) circ
->socks_username_len
);
2795 smartlist_add_asprintf(descparts
, "SOCKS_USERNAME=%s",
2796 socks_username_escaped
);
2797 tor_free(socks_username_escaped
);
2799 if (circ
->socks_password_len
> 0) {
2800 char* socks_password_escaped
= esc_for_log_len(circ
->socks_password
,
2801 (size_t) circ
->socks_password_len
);
2802 smartlist_add_asprintf(descparts
, "SOCKS_PASSWORD=%s",
2803 socks_password_escaped
);
2804 tor_free(socks_password_escaped
);
2807 rv
= smartlist_join_strings(descparts
, " ", 0, NULL
);
2809 SMARTLIST_FOREACH(descparts
, char *, cp
, tor_free(cp
));
2810 smartlist_free(descparts
);
2815 /** Implementation helper for GETINFO: knows how to generate summaries of the
2816 * current states of things we send events about. */
2818 getinfo_helper_events(control_connection_t
*control_conn
,
2819 const char *question
, char **answer
,
2820 const char **errmsg
)
2822 const or_options_t
*options
= get_options();
2823 (void) control_conn
;
2824 if (!strcmp(question
, "circuit-status")) {
2825 smartlist_t
*status
= smartlist_new();
2826 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t
*, circ_
) {
2827 origin_circuit_t
*circ
;
2830 if (! CIRCUIT_IS_ORIGIN(circ_
) || circ_
->marked_for_close
)
2832 circ
= TO_ORIGIN_CIRCUIT(circ_
);
2834 if (circ
->base_
.state
== CIRCUIT_STATE_OPEN
)
2836 else if (circ
->base_
.state
== CIRCUIT_STATE_GUARD_WAIT
)
2837 state
= "GUARD_WAIT";
2838 else if (circ
->cpath
)
2843 circdesc
= circuit_describe_status_for_controller(circ
);
2845 smartlist_add_asprintf(status
, "%lu %s%s%s",
2846 (unsigned long)circ
->global_identifier
,
2847 state
, *circdesc
? " " : "", circdesc
);
2850 SMARTLIST_FOREACH_END(circ_
);
2851 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
2852 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
2853 smartlist_free(status
);
2854 } else if (!strcmp(question
, "stream-status")) {
2855 smartlist_t
*conns
= get_connection_array();
2856 smartlist_t
*status
= smartlist_new();
2858 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
2860 entry_connection_t
*conn
;
2862 origin_circuit_t
*origin_circ
= NULL
;
2863 if (base_conn
->type
!= CONN_TYPE_AP
||
2864 base_conn
->marked_for_close
||
2865 base_conn
->state
== AP_CONN_STATE_SOCKS_WAIT
||
2866 base_conn
->state
== AP_CONN_STATE_NATD_WAIT
)
2868 conn
= TO_ENTRY_CONN(base_conn
);
2869 switch (base_conn
->state
)
2871 case AP_CONN_STATE_CONTROLLER_WAIT
:
2872 case AP_CONN_STATE_CIRCUIT_WAIT
:
2873 if (conn
->socks_request
&&
2874 SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
))
2875 state
= "NEWRESOLVE";
2879 case AP_CONN_STATE_RENDDESC_WAIT
:
2880 case AP_CONN_STATE_CONNECT_WAIT
:
2881 state
= "SENTCONNECT"; break;
2882 case AP_CONN_STATE_RESOLVE_WAIT
:
2883 state
= "SENTRESOLVE"; break;
2884 case AP_CONN_STATE_OPEN
:
2885 state
= "SUCCEEDED"; break;
2887 log_warn(LD_BUG
, "Asked for stream in unknown state %d",
2891 circ
= circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn
));
2892 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
2893 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
2894 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
2895 smartlist_add_asprintf(status
, "%lu %s %lu %s",
2896 (unsigned long) base_conn
->global_identifier
,state
,
2898 (unsigned long)origin_circ
->global_identifier
: 0ul,
2900 } SMARTLIST_FOREACH_END(base_conn
);
2901 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
2902 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
2903 smartlist_free(status
);
2904 } else if (!strcmp(question
, "orconn-status")) {
2905 smartlist_t
*conns
= get_connection_array();
2906 smartlist_t
*status
= smartlist_new();
2907 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
2910 or_connection_t
*conn
;
2911 if (base_conn
->type
!= CONN_TYPE_OR
|| base_conn
->marked_for_close
)
2913 conn
= TO_OR_CONN(base_conn
);
2914 if (conn
->base_
.state
== OR_CONN_STATE_OPEN
)
2915 state
= "CONNECTED";
2916 else if (conn
->nickname
)
2920 orconn_target_get_name(name
, sizeof(name
), conn
);
2921 smartlist_add_asprintf(status
, "%s %s", name
, state
);
2922 } SMARTLIST_FOREACH_END(base_conn
);
2923 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
2924 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
2925 smartlist_free(status
);
2926 } else if (!strcmpstart(question
, "address-mappings/")) {
2927 time_t min_e
, max_e
;
2928 smartlist_t
*mappings
;
2929 question
+= strlen("address-mappings/");
2930 if (!strcmp(question
, "all")) {
2931 min_e
= 0; max_e
= TIME_MAX
;
2932 } else if (!strcmp(question
, "cache")) {
2933 min_e
= 2; max_e
= TIME_MAX
;
2934 } else if (!strcmp(question
, "config")) {
2935 min_e
= 0; max_e
= 0;
2936 } else if (!strcmp(question
, "control")) {
2937 min_e
= 1; max_e
= 1;
2941 mappings
= smartlist_new();
2942 addressmap_get_mappings(mappings
, min_e
, max_e
, 1);
2943 *answer
= smartlist_join_strings(mappings
, "\r\n", 0, NULL
);
2944 SMARTLIST_FOREACH(mappings
, char *, cp
, tor_free(cp
));
2945 smartlist_free(mappings
);
2946 } else if (!strcmpstart(question
, "status/")) {
2947 /* Note that status/ is not a catch-all for events; there's only supposed
2948 * to be a status GETINFO if there's a corresponding STATUS event. */
2949 if (!strcmp(question
, "status/circuit-established")) {
2950 *answer
= tor_strdup(have_completed_a_circuit() ? "1" : "0");
2951 } else if (!strcmp(question
, "status/enough-dir-info")) {
2952 *answer
= tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
2953 } else if (!strcmp(question
, "status/good-server-descriptor") ||
2954 !strcmp(question
, "status/accepted-server-descriptor")) {
2955 /* They're equivalent for now, until we can figure out how to make
2956 * good-server-descriptor be what we want. See comment in
2957 * control-spec.txt. */
2958 *answer
= tor_strdup(directories_have_accepted_server_descriptor()
2960 } else if (!strcmp(question
, "status/reachability-succeeded/or")) {
2961 *answer
= tor_strdup(check_whether_orport_reachable(options
) ?
2963 } else if (!strcmp(question
, "status/reachability-succeeded/dir")) {
2964 *answer
= tor_strdup(check_whether_dirport_reachable(options
) ?
2966 } else if (!strcmp(question
, "status/reachability-succeeded")) {
2967 tor_asprintf(answer
, "OR=%d DIR=%d",
2968 check_whether_orport_reachable(options
) ? 1 : 0,
2969 check_whether_dirport_reachable(options
) ? 1 : 0);
2970 } else if (!strcmp(question
, "status/bootstrap-phase")) {
2971 *answer
= tor_strdup(last_sent_bootstrap_message
);
2972 } else if (!strcmpstart(question
, "status/version/")) {
2973 int is_server
= server_mode(options
);
2974 networkstatus_t
*c
= networkstatus_get_latest_consensus();
2975 version_status_t status
;
2976 const char *recommended
;
2978 recommended
= is_server
? c
->server_versions
: c
->client_versions
;
2979 status
= tor_version_is_obsolete(VERSION
, recommended
);
2982 status
= VS_UNKNOWN
;
2985 if (!strcmp(question
, "status/version/recommended")) {
2986 *answer
= tor_strdup(recommended
);
2989 if (!strcmp(question
, "status/version/current")) {
2992 case VS_RECOMMENDED
: *answer
= tor_strdup("recommended"); break;
2993 case VS_OLD
: *answer
= tor_strdup("obsolete"); break;
2994 case VS_NEW
: *answer
= tor_strdup("new"); break;
2995 case VS_NEW_IN_SERIES
: *answer
= tor_strdup("new in series"); break;
2996 case VS_UNRECOMMENDED
: *answer
= tor_strdup("unrecommended"); break;
2997 case VS_EMPTY
: *answer
= tor_strdup("none recommended"); break;
2998 case VS_UNKNOWN
: *answer
= tor_strdup("unknown"); break;
2999 default: tor_fragile_assert();
3001 } else if (!strcmp(question
, "status/version/num-versioning") ||
3002 !strcmp(question
, "status/version/num-concurring")) {
3003 tor_asprintf(answer
, "%d", get_n_authorities(V3_DIRINFO
));
3004 log_warn(LD_GENERAL
, "%s is deprecated; it no longer gives useful "
3005 "information", question
);
3007 } else if (!strcmp(question
, "status/clients-seen")) {
3008 char *bridge_stats
= geoip_get_bridge_stats_controller(time(NULL
));
3009 if (!bridge_stats
) {
3010 *errmsg
= "No bridge-client stats available";
3013 *answer
= bridge_stats
;
3014 } else if (!strcmp(question
, "status/fresh-relay-descs")) {
3015 if (!server_mode(options
)) {
3016 *errmsg
= "Only relays have descriptors";
3021 if (router_build_fresh_descriptor(&r
, &e
) < 0) {
3022 *errmsg
= "Error generating descriptor";
3025 size_t size
= r
->cache_info
.signed_descriptor_len
+ 1;
3027 size
+= e
->cache_info
.signed_descriptor_len
+ 1;
3029 tor_assert(r
->cache_info
.signed_descriptor_len
);
3030 char *descs
= tor_malloc(size
);
3032 memcpy(cp
, signed_descriptor_get_body(&r
->cache_info
),
3033 r
->cache_info
.signed_descriptor_len
);
3034 cp
+= r
->cache_info
.signed_descriptor_len
- 1;
3036 if (cp
[0] == '\0') {
3038 } else if (cp
[0] != '\n') {
3042 memcpy(cp
, signed_descriptor_get_body(&e
->cache_info
),
3043 e
->cache_info
.signed_descriptor_len
);
3044 cp
+= e
->cache_info
.signed_descriptor_len
- 1;
3046 if (cp
[0] == '\n') {
3048 } else if (cp
[0] != '\0') {
3061 /** Implementation helper for GETINFO: knows how to enumerate hidden services
3062 * created via the control port. */
3064 getinfo_helper_onions(control_connection_t
*control_conn
,
3065 const char *question
, char **answer
,
3066 const char **errmsg
)
3068 smartlist_t
*onion_list
= NULL
;
3069 (void) errmsg
; /* no errors from this method */
3071 if (control_conn
&& !strcmp(question
, "onions/current")) {
3072 onion_list
= control_conn
->ephemeral_onion_services
;
3073 } else if (!strcmp(question
, "onions/detached")) {
3074 onion_list
= detached_onion_services
;
3078 if (!onion_list
|| smartlist_len(onion_list
) == 0) {
3080 *answer
= tor_strdup("");
3084 *answer
= smartlist_join_strings(onion_list
, "\r\n", 0, NULL
);
3091 /** Implementation helper for GETINFO: answers queries about network
3094 getinfo_helper_liveness(control_connection_t
*control_conn
,
3095 const char *question
, char **answer
,
3096 const char **errmsg
)
3100 if (strcmp(question
, "network-liveness") == 0) {
3101 if (get_cached_network_liveness()) {
3102 *answer
= tor_strdup("up");
3104 *answer
= tor_strdup("down");
3111 /** Implementation helper for GETINFO: answers queries about shared random
3114 getinfo_helper_sr(control_connection_t
*control_conn
,
3115 const char *question
, char **answer
,
3116 const char **errmsg
)
3118 (void) control_conn
;
3121 if (!strcmp(question
, "sr/current")) {
3122 *answer
= sr_get_current_for_control();
3123 } else if (!strcmp(question
, "sr/previous")) {
3124 *answer
= sr_get_previous_for_control();
3126 /* Else statement here is unrecognized key so do nothing. */
3131 /** Callback function for GETINFO: on a given control connection, try to
3132 * answer the question <b>q</b> and store the newly-allocated answer in
3133 * *<b>a</b>. If an internal error occurs, return -1 and optionally set
3134 * *<b>error_out</b> to point to an error message to be delivered to the
3135 * controller. On success, _or if the key is not recognized_, return 0. Do not
3136 * set <b>a</b> if the key is not recognized but you may set <b>error_out</b>
3137 * to improve the error message.
3139 typedef int (*getinfo_helper_t
)(control_connection_t
*,
3140 const char *q
, char **a
,
3141 const char **error_out
);
3143 /** A single item for the GETINFO question-to-answer-function table. */
3144 typedef struct getinfo_item_t
{
3145 const char *varname
; /**< The value (or prefix) of the question. */
3146 getinfo_helper_t fn
; /**< The function that knows the answer: NULL if
3147 * this entry is documentation-only. */
3148 const char *desc
; /**< Description of the variable. */
3149 int is_prefix
; /** Must varname match exactly, or must it be a prefix? */
3152 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
3153 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
3154 #define DOC(name, desc) { name, NULL, desc, 0 }
3156 /** Table mapping questions accepted by GETINFO to the functions that know how
3157 * to answer them. */
3158 static const getinfo_item_t getinfo_items
[] = {
3159 ITEM("version", misc
, "The current version of Tor."),
3160 ITEM("bw-event-cache", misc
, "Cached BW events for a short interval."),
3161 ITEM("config-file", misc
, "Current location of the \"torrc\" file."),
3162 ITEM("config-defaults-file", misc
, "Current location of the defaults file."),
3163 ITEM("config-text", misc
,
3164 "Return the string that would be written by a saveconf command."),
3165 ITEM("config-can-saveconf", misc
,
3166 "Is it possible to save the configuration to the \"torrc\" file?"),
3167 ITEM("accounting/bytes", accounting
,
3168 "Number of bytes read/written so far in the accounting interval."),
3169 ITEM("accounting/bytes-left", accounting
,
3170 "Number of bytes left to write/read so far in the accounting interval."),
3171 ITEM("accounting/enabled", accounting
, "Is accounting currently enabled?"),
3172 ITEM("accounting/hibernating", accounting
, "Are we hibernating or awake?"),
3173 ITEM("accounting/interval-start", accounting
,
3174 "Time when the accounting period starts."),
3175 ITEM("accounting/interval-end", accounting
,
3176 "Time when the accounting period ends."),
3177 ITEM("accounting/interval-wake", accounting
,
3178 "Time to wake up in this accounting period."),
3179 ITEM("helper-nodes", entry_guards
, NULL
), /* deprecated */
3180 ITEM("entry-guards", entry_guards
,
3181 "Which nodes are we using as entry guards?"),
3182 ITEM("fingerprint", misc
, NULL
),
3183 PREFIX("config/", config
, "Current configuration values."),
3185 "List of configuration options, types, and documentation."),
3186 DOC("config/defaults",
3187 "List of default values for configuration options. "
3188 "See also config/names"),
3189 PREFIX("current-time/", current_time
, "Current time."),
3190 DOC("current-time/local", "Current time on the local system."),
3191 DOC("current-time/utc", "Current UTC time."),
3192 PREFIX("downloads/networkstatus/", downloads
,
3193 "Download statuses for networkstatus objects"),
3194 DOC("downloads/networkstatus/ns",
3195 "Download status for current-mode networkstatus download"),
3196 DOC("downloads/networkstatus/ns/bootstrap",
3197 "Download status for bootstrap-time networkstatus download"),
3198 DOC("downloads/networkstatus/ns/running",
3199 "Download status for run-time networkstatus download"),
3200 DOC("downloads/networkstatus/microdesc",
3201 "Download status for current-mode microdesc download"),
3202 DOC("downloads/networkstatus/microdesc/bootstrap",
3203 "Download status for bootstrap-time microdesc download"),
3204 DOC("downloads/networkstatus/microdesc/running",
3205 "Download status for run-time microdesc download"),
3206 PREFIX("downloads/cert/", downloads
,
3207 "Download statuses for certificates, by id fingerprint and "
3209 DOC("downloads/cert/fps",
3210 "List of authority fingerprints for which any download statuses "
3212 DOC("downloads/cert/fp/<fp>",
3213 "Download status for <fp> with the default signing key; corresponds "
3214 "to /fp/ URLs on directory server."),
3215 DOC("downloads/cert/fp/<fp>/sks",
3216 "List of signing keys for which specific download statuses are "
3217 "available for this id fingerprint"),
3218 DOC("downloads/cert/fp/<fp>/<sk>",
3219 "Download status for <fp> with signing key <sk>; corresponds "
3220 "to /fp-sk/ URLs on directory server."),
3221 PREFIX("downloads/desc/", downloads
,
3222 "Download statuses for router descriptors, by descriptor digest"),
3223 DOC("downloads/desc/descs",
3224 "Return a list of known router descriptor digests"),
3225 DOC("downloads/desc/<desc>",
3226 "Return a download status for a given descriptor digest"),
3227 PREFIX("downloads/bridge/", downloads
,
3228 "Download statuses for bridge descriptors, by bridge identity "
3230 DOC("downloads/bridge/bridges",
3231 "Return a list of configured bridge identity digests with download "
3233 DOC("downloads/bridge/<desc>",
3234 "Return a download status for a given bridge identity digest"),
3235 ITEM("info/names", misc
,
3236 "List of GETINFO options, types, and documentation."),
3237 ITEM("events/names", misc
,
3238 "Events that the controller can ask for with SETEVENTS."),
3239 ITEM("signal/names", misc
, "Signal names recognized by the SIGNAL command"),
3240 ITEM("features/names", misc
, "What arguments can USEFEATURE take?"),
3241 PREFIX("desc/id/", dir
, "Router descriptors by ID."),
3242 PREFIX("desc/name/", dir
, "Router descriptors by nickname."),
3243 ITEM("desc/all-recent", dir
,
3244 "All non-expired, non-superseded router descriptors."),
3245 ITEM("desc/download-enabled", dir
,
3246 "Do we try to download router descriptors?"),
3247 ITEM("desc/all-recent-extrainfo-hack", dir
, NULL
), /* Hack. */
3248 PREFIX("md/id/", dir
, "Microdescriptors by ID"),
3249 PREFIX("md/name/", dir
, "Microdescriptors by name"),
3250 ITEM("md/download-enabled", dir
,
3251 "Do we try to download microdescriptors?"),
3252 PREFIX("extra-info/digest/", dir
, "Extra-info documents by digest."),
3253 PREFIX("hs/client/desc/id", dir
,
3254 "Hidden Service descriptor in client's cache by onion."),
3255 PREFIX("hs/service/desc/id/", dir
,
3256 "Hidden Service descriptor in services's cache by onion."),
3257 PREFIX("net/listeners/", listeners
, "Bound addresses by type"),
3258 ITEM("ns/all", networkstatus
,
3259 "Brief summary of router status (v2 directory format)"),
3260 PREFIX("ns/id/", networkstatus
,
3261 "Brief summary of router status by ID (v2 directory format)."),
3262 PREFIX("ns/name/", networkstatus
,
3263 "Brief summary of router status by nickname (v2 directory format)."),
3264 PREFIX("ns/purpose/", networkstatus
,
3265 "Brief summary of router status by purpose (v2 directory format)."),
3266 PREFIX("consensus/", networkstatus
,
3267 "Information about and from the ns consensus."),
3268 ITEM("network-status", dir
,
3269 "Brief summary of router status (v1 directory format)"),
3270 ITEM("network-liveness", liveness
,
3271 "Current opinion on whether the network is live"),
3272 ITEM("circuit-status", events
, "List of current circuits originating here."),
3273 ITEM("stream-status", events
,"List of current streams."),
3274 ITEM("orconn-status", events
, "A list of current OR connections."),
3275 ITEM("dormant", misc
,
3276 "Is Tor dormant (not building circuits because it's idle)?"),
3277 PREFIX("address-mappings/", events
, NULL
),
3278 DOC("address-mappings/all", "Current address mappings."),
3279 DOC("address-mappings/cache", "Current cached DNS replies."),
3280 DOC("address-mappings/config",
3281 "Current address mappings from configuration."),
3282 DOC("address-mappings/control", "Current address mappings from controller."),
3283 PREFIX("status/", events
, NULL
),
3284 DOC("status/circuit-established",
3285 "Whether we think client functionality is working."),
3286 DOC("status/enough-dir-info",
3287 "Whether we have enough up-to-date directory information to build "
3289 DOC("status/bootstrap-phase",
3290 "The last bootstrap phase status event that Tor sent."),
3291 DOC("status/clients-seen",
3292 "Breakdown of client countries seen by a bridge."),
3293 DOC("status/fresh-relay-descs",
3294 "A fresh relay/ei descriptor pair for Tor's current state. Not stored."),
3295 DOC("status/version/recommended", "List of currently recommended versions."),
3296 DOC("status/version/current", "Status of the current version."),
3297 DOC("status/version/num-versioning", "Number of versioning authorities."),
3298 DOC("status/version/num-concurring",
3299 "Number of versioning authorities agreeing on the status of the "
3301 ITEM("address", misc
, "IP address of this Tor host, if we can guess it."),
3302 ITEM("traffic/read", misc
,"Bytes read since the process was started."),
3303 ITEM("traffic/written", misc
,
3304 "Bytes written since the process was started."),
3305 ITEM("process/pid", misc
, "Process id belonging to the main tor process."),
3306 ITEM("process/uid", misc
, "User id running the tor process."),
3307 ITEM("process/user", misc
,
3308 "Username under which the tor process is running."),
3309 ITEM("process/descriptor-limit", misc
, "File descriptor limit."),
3310 ITEM("limits/max-mem-in-queues", misc
, "Actual limit on memory in queues"),
3311 PREFIX("desc-annotations/id/", dir
, "Router annotations by hexdigest."),
3312 PREFIX("dir/server/", dir
,"Router descriptors as retrieved from a DirPort."),
3313 PREFIX("dir/status/", dir
,
3314 "v2 networkstatus docs as retrieved from a DirPort."),
3315 ITEM("dir/status-vote/current/consensus", dir
,
3316 "v3 Networkstatus consensus as retrieved from a DirPort."),
3317 ITEM("exit-policy/default", policies
,
3318 "The default value appended to the configured exit policy."),
3319 ITEM("exit-policy/reject-private/default", policies
,
3320 "The default rules appended to the configured exit policy by"
3321 " ExitPolicyRejectPrivate."),
3322 ITEM("exit-policy/reject-private/relay", policies
,
3323 "The relay-specific rules appended to the configured exit policy by"
3324 " ExitPolicyRejectPrivate and/or ExitPolicyRejectLocalInterfaces."),
3325 ITEM("exit-policy/full", policies
, "The entire exit policy of onion router"),
3326 ITEM("exit-policy/ipv4", policies
, "IPv4 parts of exit policy"),
3327 ITEM("exit-policy/ipv6", policies
, "IPv6 parts of exit policy"),
3328 PREFIX("ip-to-country/", geoip
, "Perform a GEOIP lookup"),
3329 ITEM("onions/current", onions
,
3330 "Onion services owned by the current control connection."),
3331 ITEM("onions/detached", onions
,
3332 "Onion services detached from the control connection."),
3333 ITEM("sr/current", sr
, "Get current shared random value."),
3334 ITEM("sr/previous", sr
, "Get previous shared random value."),
3335 { NULL
, NULL
, NULL
, 0 }
3338 /** Allocate and return a list of recognized GETINFO options. */
3340 list_getinfo_options(void)
3343 smartlist_t
*lines
= smartlist_new();
3345 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
3346 if (!getinfo_items
[i
].desc
)
3349 smartlist_add_asprintf(lines
, "%s%s -- %s\n",
3350 getinfo_items
[i
].varname
,
3351 getinfo_items
[i
].is_prefix
? "*" : "",
3352 getinfo_items
[i
].desc
);
3354 smartlist_sort_strings(lines
);
3356 ans
= smartlist_join_strings(lines
, "", 0, NULL
);
3357 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
3358 smartlist_free(lines
);
3363 /** Lookup the 'getinfo' entry <b>question</b>, and return
3364 * the answer in <b>*answer</b> (or NULL if key not recognized).
3365 * Return 0 if success or unrecognized, or -1 if recognized but
3366 * internal error. */
3368 handle_getinfo_helper(control_connection_t
*control_conn
,
3369 const char *question
, char **answer
,
3370 const char **err_out
)
3373 *answer
= NULL
; /* unrecognized key by default */
3375 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
3377 if (getinfo_items
[i
].is_prefix
)
3378 match
= !strcmpstart(question
, getinfo_items
[i
].varname
);
3380 match
= !strcmp(question
, getinfo_items
[i
].varname
);
3382 tor_assert(getinfo_items
[i
].fn
);
3383 return getinfo_items
[i
].fn(control_conn
, question
, answer
, err_out
);
3387 return 0; /* unrecognized */
3390 /** Called when we receive a GETINFO command. Try to fetch all requested
3391 * information, and reply with information or error message. */
3393 handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
3396 smartlist_t
*questions
= smartlist_new();
3397 smartlist_t
*answers
= smartlist_new();
3398 smartlist_t
*unrecognized
= smartlist_new();
3401 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
3403 smartlist_split_string(questions
, body
, " ",
3404 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3405 SMARTLIST_FOREACH_BEGIN(questions
, const char *, q
) {
3406 const char *errmsg
= NULL
;
3407 if (handle_getinfo_helper(conn
, q
, &ans
, &errmsg
) < 0) {
3409 errmsg
= "Internal error";
3410 connection_printf_to_buf(conn
, "551 %s\r\n", errmsg
);
3414 if (errmsg
) /* use provided error message */
3415 smartlist_add_strdup(unrecognized
, errmsg
);
3416 else /* use default error message */
3417 smartlist_add_asprintf(unrecognized
, "Unrecognized key \"%s\"", q
);
3419 smartlist_add_strdup(answers
, q
);
3420 smartlist_add(answers
, ans
);
3422 } SMARTLIST_FOREACH_END(q
);
3424 if (smartlist_len(unrecognized
)) {
3425 /* control-spec section 2.3, mid-reply '-' or end of reply ' ' */
3426 for (i
=0; i
< smartlist_len(unrecognized
)-1; ++i
)
3427 connection_printf_to_buf(conn
,
3429 (char *)smartlist_get(unrecognized
, i
));
3431 connection_printf_to_buf(conn
,
3433 (char *)smartlist_get(unrecognized
, i
));
3437 for (i
= 0; i
< smartlist_len(answers
); i
+= 2) {
3438 char *k
= smartlist_get(answers
, i
);
3439 char *v
= smartlist_get(answers
, i
+1);
3440 if (!strchr(v
, '\n') && !strchr(v
, '\r')) {
3441 connection_printf_to_buf(conn
, "250-%s=", k
);
3442 connection_write_str_to_buf(v
, conn
);
3443 connection_write_str_to_buf("\r\n", conn
);
3447 esc_len
= write_escaped_data(v
, strlen(v
), &esc
);
3448 connection_printf_to_buf(conn
, "250+%s=\r\n", k
);
3449 connection_buf_add(esc
, esc_len
, TO_CONN(conn
));
3453 connection_write_str_to_buf("250 OK\r\n", conn
);
3456 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
3457 smartlist_free(answers
);
3458 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
3459 smartlist_free(questions
);
3460 SMARTLIST_FOREACH(unrecognized
, char *, cp
, tor_free(cp
));
3461 smartlist_free(unrecognized
);
3466 /** Given a string, convert it to a circuit purpose. */
3468 circuit_purpose_from_string(const char *string
)
3470 if (!strcasecmpstart(string
, "purpose="))
3471 string
+= strlen("purpose=");
3473 if (!strcasecmp(string
, "general"))
3474 return CIRCUIT_PURPOSE_C_GENERAL
;
3475 else if (!strcasecmp(string
, "controller"))
3476 return CIRCUIT_PURPOSE_CONTROLLER
;
3478 return CIRCUIT_PURPOSE_UNKNOWN
;
3481 /** Return a newly allocated smartlist containing the arguments to the command
3482 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
3483 * or if <b>max_args</b> is nonnegative and there are more than
3484 * <b>max_args</b> arguments, send a 512 error to the controller, using
3485 * <b>command</b> as the command name in the error message. */
3486 static smartlist_t
*
3487 getargs_helper(const char *command
, control_connection_t
*conn
,
3488 const char *body
, int min_args
, int max_args
)
3490 smartlist_t
*args
= smartlist_new();
3491 smartlist_split_string(args
, body
, " ",
3492 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3493 if (smartlist_len(args
) < min_args
) {
3494 connection_printf_to_buf(conn
, "512 Missing argument to %s\r\n",command
);
3496 } else if (max_args
>= 0 && smartlist_len(args
) > max_args
) {
3497 connection_printf_to_buf(conn
, "512 Too many arguments to %s\r\n",command
);
3502 SMARTLIST_FOREACH(args
, char *, s
, tor_free(s
));
3503 smartlist_free(args
);
3507 /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
3508 * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
3509 * such element exists. */
3511 find_element_starting_with(smartlist_t
*sl
, int start_at
, const char *prefix
)
3514 for (i
= start_at
; i
< smartlist_len(sl
); ++i
) {
3515 const char *elt
= smartlist_get(sl
, i
);
3516 if (!strcasecmpstart(elt
, prefix
))
3522 /** Helper. Return true iff s is an argument that we should treat as a
3523 * key-value pair. */
3525 is_keyval_pair(const char *s
)
3527 /* An argument is a key-value pair if it has an =, and it isn't of the form
3528 * $fingeprint=name */
3529 return strchr(s
, '=') && s
[0] != '$';
3532 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
3533 * circuit, and report success or failure. */
3535 handle_control_extendcircuit(control_connection_t
*conn
, uint32_t len
,
3538 smartlist_t
*router_nicknames
=NULL
, *nodes
=NULL
;
3539 origin_circuit_t
*circ
= NULL
;
3541 uint8_t intended_purpose
= CIRCUIT_PURPOSE_C_GENERAL
;
3545 router_nicknames
= smartlist_new();
3547 args
= getargs_helper("EXTENDCIRCUIT", conn
, body
, 1, -1);
3551 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,0));
3554 const char *purp
= find_element_starting_with(args
, 1, "PURPOSE=");
3557 intended_purpose
= circuit_purpose_from_string(purp
);
3558 if (intended_purpose
== CIRCUIT_PURPOSE_UNKNOWN
) {
3559 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
3560 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3561 smartlist_free(args
);
3566 if ((smartlist_len(args
) == 1) ||
3567 (smartlist_len(args
) >= 2 && is_keyval_pair(smartlist_get(args
, 1)))) {
3568 // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
3569 circ
= circuit_launch(intended_purpose
, CIRCLAUNCH_NEED_CAPACITY
);
3571 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
3573 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
3574 (unsigned long)circ
->global_identifier
);
3576 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3577 smartlist_free(args
);
3580 // "EXTENDCIRCUIT 0 router1,router2" ||
3581 // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
3584 if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
,0)))) {
3585 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
3586 (char*)smartlist_get(args
, 0));
3587 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3588 smartlist_free(args
);
3592 if (smartlist_len(args
) < 2) {
3593 connection_printf_to_buf(conn
,
3594 "512 syntax error: not enough arguments.\r\n");
3595 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3596 smartlist_free(args
);
3600 smartlist_split_string(router_nicknames
, smartlist_get(args
,1), ",", 0, 0);
3602 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3603 smartlist_free(args
);
3605 nodes
= smartlist_new();
3606 int first_node
= zero_circ
;
3607 SMARTLIST_FOREACH_BEGIN(router_nicknames
, const char *, n
) {
3608 const node_t
*node
= node_get_by_nickname(n
, 0);
3610 connection_printf_to_buf(conn
, "552 No such router \"%s\"\r\n", n
);
3613 if (!node_has_preferred_descriptor(node
, first_node
)) {
3614 connection_printf_to_buf(conn
, "552 No descriptor for \"%s\"\r\n", n
);
3617 smartlist_add(nodes
, (void*)node
);
3619 } SMARTLIST_FOREACH_END(n
);
3620 if (!smartlist_len(nodes
)) {
3621 connection_write_str_to_buf("512 No router names provided\r\n", conn
);
3626 /* start a new circuit */
3627 circ
= origin_circuit_init(intended_purpose
, 0);
3630 /* now circ refers to something that is ready to be extended */
3631 first_node
= zero_circ
;
3632 SMARTLIST_FOREACH(nodes
, const node_t
*, node
,
3634 extend_info_t
*info
= extend_info_from_node(node
, first_node
);
3636 tor_assert_nonfatal(first_node
);
3637 log_warn(LD_CONTROL
,
3638 "controller tried to connect to a node that lacks a suitable "
3639 "descriptor, or which doesn't have any "
3640 "addresses that are allowed by the firewall configuration; "
3641 "circuit marked for closing.");
3642 circuit_mark_for_close(TO_CIRCUIT(circ
), -END_CIRC_REASON_CONNECTFAILED
);
3643 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
3646 circuit_append_new_exit(circ
, info
);
3647 if (circ
->build_state
->desired_path_len
> 1) {
3648 circ
->build_state
->onehop_tunnel
= 0;
3650 extend_info_free(info
);
3654 /* now that we've populated the cpath, start extending */
3657 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
3658 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
3659 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
3663 if (circ
->base_
.state
== CIRCUIT_STATE_OPEN
||
3664 circ
->base_
.state
== CIRCUIT_STATE_GUARD_WAIT
) {
3666 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
3667 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
3668 log_info(LD_CONTROL
,
3669 "send_next_onion_skin failed; circuit marked for closing.");
3670 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
3671 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn
);
3677 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
3678 (unsigned long)circ
->global_identifier
);
3679 if (zero_circ
) /* send a 'launched' event, for completeness */
3680 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
3682 SMARTLIST_FOREACH(router_nicknames
, char *, n
, tor_free(n
));
3683 smartlist_free(router_nicknames
);
3684 smartlist_free(nodes
);
3688 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
3689 * circuit and it's a valid purpose, change it. */
3691 handle_control_setcircuitpurpose(control_connection_t
*conn
,
3692 uint32_t len
, const char *body
)
3694 origin_circuit_t
*circ
= NULL
;
3695 uint8_t new_purpose
;
3697 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
3699 args
= getargs_helper("SETCIRCUITPURPOSE", conn
, body
, 2, -1);
3703 if (!(circ
= get_circ(smartlist_get(args
,0)))) {
3704 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
3705 (char*)smartlist_get(args
, 0));
3710 const char *purp
= find_element_starting_with(args
,1,"PURPOSE=");
3712 connection_write_str_to_buf("552 No purpose given\r\n", conn
);
3715 new_purpose
= circuit_purpose_from_string(purp
);
3716 if (new_purpose
== CIRCUIT_PURPOSE_UNKNOWN
) {
3717 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
3722 circuit_change_purpose(TO_CIRCUIT(circ
), new_purpose
);
3723 connection_write_str_to_buf("250 OK\r\n", conn
);
3727 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3728 smartlist_free(args
);
3733 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
3734 * stream, and report success or failure. */
3736 handle_control_attachstream(control_connection_t
*conn
, uint32_t len
,
3739 entry_connection_t
*ap_conn
= NULL
;
3740 origin_circuit_t
*circ
= NULL
;
3743 crypt_path_t
*cpath
=NULL
;
3744 int hop
=0, hop_line_ok
=1;
3747 args
= getargs_helper("ATTACHSTREAM", conn
, body
, 2, -1);
3751 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,1));
3753 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))) {
3754 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
3755 (char*)smartlist_get(args
, 0));
3756 } else if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
, 1)))) {
3757 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
3758 (char*)smartlist_get(args
, 1));
3760 const char *hopstring
= find_element_starting_with(args
,2,"HOP=");
3762 hopstring
+= strlen("HOP=");
3763 hop
= (int) tor_parse_ulong(hopstring
, 10, 0, INT_MAX
,
3764 &hop_line_ok
, NULL
);
3765 if (!hop_line_ok
) { /* broken hop line */
3766 connection_printf_to_buf(conn
, "552 Bad value hop=%s\r\n", hopstring
);
3770 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3771 smartlist_free(args
);
3772 if (!ap_conn
|| (!zero_circ
&& !circ
) || !hop_line_ok
)
3775 if (ENTRY_TO_CONN(ap_conn
)->state
!= AP_CONN_STATE_CONTROLLER_WAIT
&&
3776 ENTRY_TO_CONN(ap_conn
)->state
!= AP_CONN_STATE_CONNECT_WAIT
&&
3777 ENTRY_TO_CONN(ap_conn
)->state
!= AP_CONN_STATE_RESOLVE_WAIT
) {
3778 connection_write_str_to_buf(
3779 "555 Connection is not managed by controller.\r\n",
3784 /* Do we need to detach it first? */
3785 if (ENTRY_TO_CONN(ap_conn
)->state
!= AP_CONN_STATE_CONTROLLER_WAIT
) {
3786 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(ap_conn
);
3787 circuit_t
*tmpcirc
= circuit_get_by_edge_conn(edge_conn
);
3788 connection_edge_end(edge_conn
, END_STREAM_REASON_TIMEOUT
);
3789 /* Un-mark it as ending, since we're going to reuse it. */
3790 edge_conn
->edge_has_sent_end
= 0;
3791 edge_conn
->end_reason
= 0;
3793 circuit_detach_stream(tmpcirc
, edge_conn
);
3794 CONNECTION_AP_EXPECT_NONPENDING(ap_conn
);
3795 TO_CONN(edge_conn
)->state
= AP_CONN_STATE_CONTROLLER_WAIT
;
3798 if (circ
&& (circ
->base_
.state
!= CIRCUIT_STATE_OPEN
)) {
3799 connection_write_str_to_buf(
3800 "551 Can't attach stream to non-open origin circuit\r\n",
3804 /* Is this a single hop circuit? */
3805 if (circ
&& (circuit_get_cpath_len(circ
)<2 || hop
==1)) {
3806 connection_write_str_to_buf(
3807 "551 Can't attach stream to this one-hop circuit.\r\n", conn
);
3811 if (circ
&& hop
>0) {
3812 /* find this hop in the circuit, and set cpath */
3813 cpath
= circuit_get_cpath_hop(circ
, hop
);
3815 connection_printf_to_buf(conn
,
3816 "551 Circuit doesn't have %d hops.\r\n", hop
);
3820 if (connection_ap_handshake_rewrite_and_attach(ap_conn
, circ
, cpath
) < 0) {
3821 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn
);
3824 send_control_done(conn
);
3828 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
3829 * descriptor, and report success or failure. */
3831 handle_control_postdescriptor(control_connection_t
*conn
, uint32_t len
,
3835 const char *msg
=NULL
;
3836 uint8_t purpose
= ROUTER_PURPOSE_GENERAL
;
3837 int cache
= 0; /* eventually, we may switch this to 1 */
3839 const char *cp
= memchr(body
, '\n', len
);
3842 connection_printf_to_buf(conn
, "251 Empty body\r\n");
3847 char *cmdline
= tor_memdup_nulterm(body
, cp
-body
);
3848 smartlist_t
*args
= smartlist_new();
3849 smartlist_split_string(args
, cmdline
, " ",
3850 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3851 SMARTLIST_FOREACH_BEGIN(args
, char *, option
) {
3852 if (!strcasecmpstart(option
, "purpose=")) {
3853 option
+= strlen("purpose=");
3854 purpose
= router_purpose_from_string(option
);
3855 if (purpose
== ROUTER_PURPOSE_UNKNOWN
) {
3856 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n",
3860 } else if (!strcasecmpstart(option
, "cache=")) {
3861 option
+= strlen("cache=");
3862 if (!strcasecmp(option
, "no"))
3864 else if (!strcasecmp(option
, "yes"))
3867 connection_printf_to_buf(conn
, "552 Unknown cache request \"%s\"\r\n",
3871 } else { /* unrecognized argument? */
3872 connection_printf_to_buf(conn
,
3873 "512 Unexpected argument \"%s\" to postdescriptor\r\n", option
);
3876 } SMARTLIST_FOREACH_END(option
);
3878 read_escaped_data(cp
, len
-(cp
-body
), &desc
);
3880 switch (router_load_single_router(desc
, purpose
, cache
, &msg
)) {
3882 if (!msg
) msg
= "Could not parse descriptor";
3883 connection_printf_to_buf(conn
, "554 %s\r\n", msg
);
3886 if (!msg
) msg
= "Descriptor not added";
3887 connection_printf_to_buf(conn
, "251 %s\r\n",msg
);
3890 send_control_done(conn
);
3896 SMARTLIST_FOREACH(args
, char *, arg
, tor_free(arg
));
3897 smartlist_free(args
);
3902 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
3903 * address of the named AP stream, and report success or failure. */
3905 handle_control_redirectstream(control_connection_t
*conn
, uint32_t len
,
3908 entry_connection_t
*ap_conn
= NULL
;
3909 char *new_addr
= NULL
;
3910 uint16_t new_port
= 0;
3914 args
= getargs_helper("REDIRECTSTREAM", conn
, body
, 2, -1);
3918 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))
3919 || !ap_conn
->socks_request
) {
3920 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
3921 (char*)smartlist_get(args
, 0));
3924 if (smartlist_len(args
) > 2) { /* they included a port too */
3925 new_port
= (uint16_t) tor_parse_ulong(smartlist_get(args
, 2),
3926 10, 1, 65535, &ok
, NULL
);
3929 connection_printf_to_buf(conn
, "512 Cannot parse port \"%s\"\r\n",
3930 (char*)smartlist_get(args
, 2));
3932 new_addr
= tor_strdup(smartlist_get(args
, 1));
3936 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3937 smartlist_free(args
);
3941 strlcpy(ap_conn
->socks_request
->address
, new_addr
,
3942 sizeof(ap_conn
->socks_request
->address
));
3944 ap_conn
->socks_request
->port
= new_port
;
3946 send_control_done(conn
);
3950 /** Called when we get a CLOSESTREAM command; try to close the named stream
3951 * and report success or failure. */
3953 handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
3956 entry_connection_t
*ap_conn
=NULL
;
3962 args
= getargs_helper("CLOSESTREAM", conn
, body
, 2, -1);
3966 else if (!(ap_conn
= get_stream(smartlist_get(args
, 0))))
3967 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
3968 (char*)smartlist_get(args
, 0));
3970 reason
= (uint8_t) tor_parse_ulong(smartlist_get(args
,1), 10, 0, 255,
3973 connection_printf_to_buf(conn
, "552 Unrecognized reason \"%s\"\r\n",
3974 (char*)smartlist_get(args
, 1));
3978 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3979 smartlist_free(args
);
3983 connection_mark_unattached_ap(ap_conn
, reason
);
3984 send_control_done(conn
);
3988 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
3989 * and report success or failure. */
3991 handle_control_closecircuit(control_connection_t
*conn
, uint32_t len
,
3994 origin_circuit_t
*circ
= NULL
;
3999 args
= getargs_helper("CLOSECIRCUIT", conn
, body
, 1, -1);
4003 if (!(circ
=get_circ(smartlist_get(args
, 0))))
4004 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
4005 (char*)smartlist_get(args
, 0));
4008 for (i
=1; i
< smartlist_len(args
); ++i
) {
4009 if (!strcasecmp(smartlist_get(args
, i
), "IfUnused"))
4012 log_info(LD_CONTROL
, "Skipping unknown option %s",
4013 (char*)smartlist_get(args
,i
));
4016 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4017 smartlist_free(args
);
4021 if (!safe
|| !circ
->p_streams
) {
4022 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_REQUESTED
);
4025 send_control_done(conn
);
4029 /** Called when we get a RESOLVE command: start trying to resolve
4030 * the listed addresses. */
4032 handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
4035 smartlist_t
*args
, *failed
;
4037 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
4039 if (!(conn
->event_mask
& (((event_mask_t
)1)<<EVENT_ADDRMAP
))) {
4040 log_warn(LD_CONTROL
, "Controller asked us to resolve an address, but "
4041 "isn't listening for ADDRMAP events. It probably won't see "
4044 args
= smartlist_new();
4045 smartlist_split_string(args
, body
, " ",
4046 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
4048 const char *modearg
= find_element_starting_with(args
, 0, "mode=");
4049 if (modearg
&& !strcasecmp(modearg
, "mode=reverse"))
4052 failed
= smartlist_new();
4053 SMARTLIST_FOREACH(args
, const char *, arg
, {
4054 if (!is_keyval_pair(arg
)) {
4055 if (dnsserv_launch_request(arg
, is_reverse
, conn
)<0)
4056 smartlist_add(failed
, (char*)arg
);
4060 send_control_done(conn
);
4061 SMARTLIST_FOREACH(failed
, const char *, arg
, {
4062 control_event_address_mapped(arg
, arg
, time(NULL
),
4066 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4067 smartlist_free(args
);
4068 smartlist_free(failed
);
4072 /** Called when we get a PROTOCOLINFO command: send back a reply. */
4074 handle_control_protocolinfo(control_connection_t
*conn
, uint32_t len
,
4077 const char *bad_arg
= NULL
;
4081 conn
->have_sent_protocolinfo
= 1;
4082 args
= smartlist_new();
4083 smartlist_split_string(args
, body
, " ",
4084 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
4085 SMARTLIST_FOREACH(args
, const char *, arg
, {
4087 tor_parse_long(arg
, 10, 0, LONG_MAX
, &ok
, NULL
);
4094 connection_printf_to_buf(conn
, "513 No such version %s\r\n",
4096 /* Don't tolerate bad arguments when not authenticated. */
4097 if (!STATE_IS_OPEN(TO_CONN(conn
)->state
))
4098 connection_mark_for_close(TO_CONN(conn
));
4101 const or_options_t
*options
= get_options();
4102 int cookies
= options
->CookieAuthentication
;
4103 char *cfile
= get_controller_cookie_file_name();
4107 abs_cfile
= make_path_absolute(cfile
);
4108 esc_cfile
= esc_for_log(abs_cfile
);
4110 int passwd
= (options
->HashedControlPassword
!= NULL
||
4111 options
->HashedControlSessionPassword
!= NULL
);
4112 smartlist_t
*mlist
= smartlist_new();
4114 smartlist_add(mlist
, (char*)"COOKIE");
4115 smartlist_add(mlist
, (char*)"SAFECOOKIE");
4118 smartlist_add(mlist
, (char*)"HASHEDPASSWORD");
4119 if (!cookies
&& !passwd
)
4120 smartlist_add(mlist
, (char*)"NULL");
4121 methods
= smartlist_join_strings(mlist
, ",", 0, NULL
);
4122 smartlist_free(mlist
);
4125 connection_printf_to_buf(conn
,
4126 "250-PROTOCOLINFO 1\r\n"
4127 "250-AUTH METHODS=%s%s%s\r\n"
4128 "250-VERSION Tor=%s\r\n"
4131 cookies
?" COOKIEFILE=":"",
4132 cookies
?esc_cfile
:"",
4136 tor_free(abs_cfile
);
4137 tor_free(esc_cfile
);
4140 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4141 smartlist_free(args
);
4145 /** Called when we get an AUTHCHALLENGE command. */
4147 handle_control_authchallenge(control_connection_t
*conn
, uint32_t len
,
4150 const char *cp
= body
;
4152 size_t client_nonce_len
;
4153 char server_hash
[DIGEST256_LEN
];
4154 char server_hash_encoded
[HEX_DIGEST256_LEN
+1];
4155 char server_nonce
[SAFECOOKIE_SERVER_NONCE_LEN
];
4156 char server_nonce_encoded
[(2*SAFECOOKIE_SERVER_NONCE_LEN
) + 1];
4158 cp
+= strspn(cp
, " \t\n\r");
4159 if (!strcasecmpstart(cp
, "SAFECOOKIE")) {
4160 cp
+= strlen("SAFECOOKIE");
4162 connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
4163 "authentication\r\n", conn
);
4164 connection_mark_for_close(TO_CONN(conn
));
4168 if (!authentication_cookie_is_set
) {
4169 connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
4171 connection_mark_for_close(TO_CONN(conn
));
4175 cp
+= strspn(cp
, " \t\n\r");
4178 decode_escaped_string(cp
, len
- (cp
- body
),
4179 &client_nonce
, &client_nonce_len
);
4180 if (newcp
== NULL
) {
4181 connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
4183 connection_mark_for_close(TO_CONN(conn
));
4188 size_t client_nonce_encoded_len
= strspn(cp
, "0123456789ABCDEFabcdef");
4190 client_nonce_len
= client_nonce_encoded_len
/ 2;
4191 client_nonce
= tor_malloc_zero(client_nonce_len
);
4193 if (base16_decode(client_nonce
, client_nonce_len
,
4194 cp
, client_nonce_encoded_len
)
4195 != (int) client_nonce_len
) {
4196 connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
4198 connection_mark_for_close(TO_CONN(conn
));
4199 tor_free(client_nonce
);
4203 cp
+= client_nonce_encoded_len
;
4206 cp
+= strspn(cp
, " \t\n\r");
4209 connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
4211 connection_mark_for_close(TO_CONN(conn
));
4212 tor_free(client_nonce
);
4215 crypto_rand(server_nonce
, SAFECOOKIE_SERVER_NONCE_LEN
);
4217 /* Now compute and send the server-to-controller response, and the
4218 * server's nonce. */
4219 tor_assert(authentication_cookie
!= NULL
);
4222 size_t tmp_len
= (AUTHENTICATION_COOKIE_LEN
+
4224 SAFECOOKIE_SERVER_NONCE_LEN
);
4225 char *tmp
= tor_malloc_zero(tmp_len
);
4226 char *client_hash
= tor_malloc_zero(DIGEST256_LEN
);
4227 memcpy(tmp
, authentication_cookie
, AUTHENTICATION_COOKIE_LEN
);
4228 memcpy(tmp
+ AUTHENTICATION_COOKIE_LEN
, client_nonce
, client_nonce_len
);
4229 memcpy(tmp
+ AUTHENTICATION_COOKIE_LEN
+ client_nonce_len
,
4230 server_nonce
, SAFECOOKIE_SERVER_NONCE_LEN
);
4232 crypto_hmac_sha256(server_hash
,
4233 SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT
,
4234 strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT
),
4238 crypto_hmac_sha256(client_hash
,
4239 SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT
,
4240 strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT
),
4244 conn
->safecookie_client_hash
= client_hash
;
4249 base16_encode(server_hash_encoded
, sizeof(server_hash_encoded
),
4250 server_hash
, sizeof(server_hash
));
4251 base16_encode(server_nonce_encoded
, sizeof(server_nonce_encoded
),
4252 server_nonce
, sizeof(server_nonce
));
4254 connection_printf_to_buf(conn
,
4255 "250 AUTHCHALLENGE SERVERHASH=%s "
4256 "SERVERNONCE=%s\r\n",
4257 server_hash_encoded
,
4258 server_nonce_encoded
);
4260 tor_free(client_nonce
);
4264 /** Called when we get a USEFEATURE command: parse the feature list, and
4265 * set up the control_connection's options properly. */
4267 handle_control_usefeature(control_connection_t
*conn
,
4273 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
4274 args
= smartlist_new();
4275 smartlist_split_string(args
, body
, " ",
4276 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
4277 SMARTLIST_FOREACH_BEGIN(args
, const char *, arg
) {
4278 if (!strcasecmp(arg
, "VERBOSE_NAMES"))
4280 else if (!strcasecmp(arg
, "EXTENDED_EVENTS"))
4283 connection_printf_to_buf(conn
, "552 Unrecognized feature \"%s\"\r\n",
4288 } SMARTLIST_FOREACH_END(arg
);
4291 send_control_done(conn
);
4294 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4295 smartlist_free(args
);
4299 /** Implementation for the DROPGUARDS command. */
4301 handle_control_dropguards(control_connection_t
*conn
,
4306 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
4307 args
= smartlist_new();
4308 smartlist_split_string(args
, body
, " ",
4309 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
4311 static int have_warned
= 0;
4312 if (! have_warned
) {
4313 log_warn(LD_CONTROL
, "DROPGUARDS is dangerous; make sure you understand "
4314 "the risks before using it. It may be removed in a future "
4319 if (smartlist_len(args
)) {
4320 connection_printf_to_buf(conn
, "512 Too many arguments to DROPGUARDS\r\n");
4322 remove_all_entry_guards();
4323 send_control_done(conn
);
4326 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4327 smartlist_free(args
);
4331 /** Implementation for the HSFETCH command. */
4333 handle_control_hsfetch(control_connection_t
*conn
, uint32_t len
,
4337 char digest
[DIGEST_LEN
], *hsaddress
= NULL
, *arg1
= NULL
, *desc_id
= NULL
;
4338 smartlist_t
*args
= NULL
, *hsdirs
= NULL
;
4339 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
4340 static const char *hsfetch_command
= "HSFETCH";
4341 static const char *v2_str
= "v2-";
4342 const size_t v2_str_len
= strlen(v2_str
);
4343 rend_data_t
*rend_query
= NULL
;
4345 /* Make sure we have at least one argument, the HSAddress. */
4346 args
= getargs_helper(hsfetch_command
, conn
, body
, 1, -1);
4351 /* Extract the first argument (either HSAddress or DescID). */
4352 arg1
= smartlist_get(args
, 0);
4353 /* Test if it's an HS address without the .onion part. */
4354 if (rend_valid_v2_service_id(arg1
)) {
4356 } else if (strcmpstart(arg1
, v2_str
) == 0 &&
4357 rend_valid_descriptor_id(arg1
+ v2_str_len
) &&
4358 base32_decode(digest
, sizeof(digest
), arg1
+ v2_str_len
,
4359 REND_DESC_ID_V2_LEN_BASE32
) == 0) {
4360 /* We have a well formed version 2 descriptor ID. Keep the decoded value
4364 connection_printf_to_buf(conn
, "513 Invalid argument \"%s\"\r\n",
4369 static const char *opt_server
= "SERVER=";
4371 /* Skip first argument because it's the HSAddress or DescID. */
4372 for (i
= 1; i
< smartlist_len(args
); ++i
) {
4373 const char *arg
= smartlist_get(args
, i
);
4376 if (!strcasecmpstart(arg
, opt_server
)) {
4379 server
= arg
+ strlen(opt_server
);
4380 node
= node_get_by_hex_id(server
, 0);
4382 connection_printf_to_buf(conn
, "552 Server \"%s\" not found\r\n",
4387 /* Stores routerstatus_t object for each specified server. */
4388 hsdirs
= smartlist_new();
4390 /* Valid server, add it to our local list. */
4391 smartlist_add(hsdirs
, node
->rs
);
4393 connection_printf_to_buf(conn
, "513 Unexpected argument \"%s\"\r\n",
4399 rend_query
= rend_data_client_create(hsaddress
, desc_id
, NULL
,
4401 if (rend_query
== NULL
) {
4402 connection_printf_to_buf(conn
, "551 Error creating the HS query\r\n");
4406 /* Using a descriptor ID, we force the user to provide at least one
4407 * hsdir server using the SERVER= option. */
4408 if (desc_id
&& (!hsdirs
|| !smartlist_len(hsdirs
))) {
4409 connection_printf_to_buf(conn
, "512 %s option is required\r\n",
4414 /* We are about to trigger HSDir fetch so send the OK now because after
4415 * that 650 event(s) are possible so better to have the 250 OK before them
4416 * to avoid out of order replies. */
4417 send_control_done(conn
);
4419 /* Trigger the fetch using the built rend query and possibly a list of HS
4420 * directory to use. This function ignores the client cache thus this will
4421 * always send a fetch command. */
4422 rend_client_fetch_v2_desc(rend_query
, hsdirs
);
4425 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4426 smartlist_free(args
);
4427 /* Contains data pointer that we don't own thus no cleanup. */
4428 smartlist_free(hsdirs
);
4429 rend_data_free(rend_query
);
4434 /** Implementation for the HSPOST command. */
4436 handle_control_hspost(control_connection_t
*conn
,
4440 static const char *opt_server
= "SERVER=";
4441 static const char *opt_hsaddress
= "HSADDRESS=";
4442 smartlist_t
*hs_dirs
= NULL
;
4443 const char *encoded_desc
= body
;
4444 size_t encoded_desc_len
= len
;
4445 const char *onion_address
= NULL
;
4447 char *cp
= memchr(body
, '\n', len
);
4449 connection_printf_to_buf(conn
, "251 Empty body\r\n");
4452 char *argline
= tor_strndup(body
, cp
-body
);
4454 smartlist_t
*args
= smartlist_new();
4456 /* If any SERVER= or HSADDRESS= options were specified, try to parse
4457 * the options line. */
4458 if (!strcasecmpstart(argline
, opt_server
) ||
4459 !strcasecmpstart(argline
, opt_hsaddress
)) {
4460 /* encoded_desc begins after a newline character */
4463 encoded_desc_len
= len
-(cp
-body
);
4465 smartlist_split_string(args
, argline
, " ",
4466 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
4467 SMARTLIST_FOREACH_BEGIN(args
, const char *, arg
) {
4468 if (!strcasecmpstart(arg
, opt_server
)) {
4469 const char *server
= arg
+ strlen(opt_server
);
4470 const node_t
*node
= node_get_by_hex_id(server
, 0);
4472 if (!node
|| !node
->rs
) {
4473 connection_printf_to_buf(conn
, "552 Server \"%s\" not found\r\n",
4477 /* Valid server, add it to our local list. */
4479 hs_dirs
= smartlist_new();
4480 smartlist_add(hs_dirs
, node
->rs
);
4481 } else if (!strcasecmpstart(arg
, opt_hsaddress
)) {
4482 const char *address
= arg
+ strlen(opt_hsaddress
);
4483 if (!hs_address_is_valid(address
)) {
4484 connection_printf_to_buf(conn
, "512 Malformed onion address\r\n");
4487 onion_address
= address
;
4489 connection_printf_to_buf(conn
, "512 Unexpected argument \"%s\"\r\n",
4493 } SMARTLIST_FOREACH_END(arg
);
4496 /* Handle the v3 case. */
4497 if (onion_address
) {
4498 char *desc_str
= NULL
;
4499 read_escaped_data(encoded_desc
, encoded_desc_len
, &desc_str
);
4500 if (hs_control_hspost_command(desc_str
, onion_address
, hs_dirs
) < 0) {
4501 connection_printf_to_buf(conn
, "554 Invalid descriptor\r\n");
4503 send_control_done(conn
);
4509 /* From this point on, it is only v2. */
4511 /* Read the dot encoded descriptor, and parse it. */
4512 rend_encoded_v2_service_descriptor_t
*desc
=
4513 tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t
));
4514 read_escaped_data(encoded_desc
, encoded_desc_len
, &desc
->desc_str
);
4516 rend_service_descriptor_t
*parsed
= NULL
;
4517 char *intro_content
= NULL
;
4519 size_t encoded_size
;
4520 const char *next_desc
;
4521 if (!rend_parse_v2_service_descriptor(&parsed
, desc
->desc_id
, &intro_content
,
4522 &intro_size
, &encoded_size
,
4523 &next_desc
, desc
->desc_str
, 1)) {
4524 /* Post the descriptor. */
4525 char serviceid
[REND_SERVICE_ID_LEN_BASE32
+1];
4526 if (!rend_get_service_id(parsed
->pk
, serviceid
)) {
4527 smartlist_t
*descs
= smartlist_new();
4528 smartlist_add(descs
, desc
);
4530 /* We are about to trigger HS descriptor upload so send the OK now
4531 * because after that 650 event(s) are possible so better to have the
4532 * 250 OK before them to avoid out of order replies. */
4533 send_control_done(conn
);
4535 /* Trigger the descriptor upload */
4536 directory_post_to_hs_dir(parsed
, descs
, hs_dirs
, serviceid
, 0);
4537 smartlist_free(descs
);
4540 rend_service_descriptor_free(parsed
);
4542 connection_printf_to_buf(conn
, "554 Invalid descriptor\r\n");
4545 tor_free(intro_content
);
4546 rend_encoded_v2_service_descriptor_free(desc
);
4549 smartlist_free(hs_dirs
); /* Contents belong to the rend service code. */
4550 SMARTLIST_FOREACH(args
, char *, arg
, tor_free(arg
));
4551 smartlist_free(args
);
4555 /* Helper function for ADD_ONION that adds an ephemeral service depending on
4556 * the given hs_version.
4558 * The secret key in pk depends on the hs_version. The ownership of the key
4559 * used in pk is given to the HS subsystem so the caller must stop accessing
4562 * The port_cfgs is a list of service port. Ownership transferred to service.
4563 * The max_streams refers to the MaxStreams= key.
4564 * The max_streams_close_circuit refers to the MaxStreamsCloseCircuit key.
4565 * The auth_type is the authentication type of the clients in auth_clients.
4566 * The ownership of that list is transferred to the service.
4568 * On success (RSAE_OKAY), the address_out points to a newly allocated string
4569 * containing the onion address without the .onion part. On error, address_out
4571 static hs_service_add_ephemeral_status_t
4572 add_onion_helper_add_service(int hs_version
,
4573 add_onion_secret_key_t
*pk
,
4574 smartlist_t
*port_cfgs
, int max_streams
,
4575 int max_streams_close_circuit
, int auth_type
,
4576 smartlist_t
*auth_clients
, char **address_out
)
4578 hs_service_add_ephemeral_status_t ret
;
4581 tor_assert(port_cfgs
);
4582 tor_assert(address_out
);
4584 switch (hs_version
) {
4585 case HS_VERSION_TWO
:
4586 ret
= rend_service_add_ephemeral(pk
->v2
, port_cfgs
, max_streams
,
4587 max_streams_close_circuit
, auth_type
,
4588 auth_clients
, address_out
);
4590 case HS_VERSION_THREE
:
4591 ret
= hs_service_add_ephemeral(pk
->v3
, port_cfgs
, max_streams
,
4592 max_streams_close_circuit
, address_out
);
4595 tor_assert_unreached();
4601 /** Called when we get a ADD_ONION command; parse the body, and set up
4602 * the new ephemeral Onion Service. */
4604 handle_control_add_onion(control_connection_t
*conn
,
4610 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
4611 args
= getargs_helper("ADD_ONION", conn
, body
, 2, -1);
4614 arg_len
= smartlist_len(args
);
4616 /* Parse all of the arguments that do not involve handling cryptographic
4617 * material first, since there's no reason to touch that at all if any of
4618 * the other arguments are malformed.
4620 smartlist_t
*port_cfgs
= smartlist_new();
4621 smartlist_t
*auth_clients
= NULL
;
4622 smartlist_t
*auth_created_clients
= NULL
;
4625 int max_streams
= 0;
4626 int max_streams_close_circuit
= 0;
4627 rend_auth_type_t auth_type
= REND_NO_AUTH
;
4628 /* Default to adding an anonymous hidden service if no flag is given */
4629 int non_anonymous
= 0;
4630 for (int i
= 1; i
< arg_len
; i
++) {
4631 static const char *port_prefix
= "Port=";
4632 static const char *flags_prefix
= "Flags=";
4633 static const char *max_s_prefix
= "MaxStreams=";
4634 static const char *auth_prefix
= "ClientAuth=";
4636 const char *arg
= smartlist_get(args
, i
);
4637 if (!strcasecmpstart(arg
, port_prefix
)) {
4638 /* "Port=VIRTPORT[,TARGET]". */
4639 const char *port_str
= arg
+ strlen(port_prefix
);
4641 rend_service_port_config_t
*cfg
=
4642 rend_service_parse_port_config(port_str
, ",", NULL
);
4644 connection_printf_to_buf(conn
, "512 Invalid VIRTPORT/TARGET\r\n");
4647 smartlist_add(port_cfgs
, cfg
);
4648 } else if (!strcasecmpstart(arg
, max_s_prefix
)) {
4649 /* "MaxStreams=[0..65535]". */
4650 const char *max_s_str
= arg
+ strlen(max_s_prefix
);
4652 max_streams
= (int)tor_parse_long(max_s_str
, 10, 0, 65535, &ok
, NULL
);
4654 connection_printf_to_buf(conn
, "512 Invalid MaxStreams\r\n");
4657 } else if (!strcasecmpstart(arg
, flags_prefix
)) {
4658 /* "Flags=Flag[,Flag]", where Flag can be:
4659 * * 'DiscardPK' - If tor generates the keypair, do not include it in
4661 * * 'Detach' - Do not tie this onion service to any particular control
4663 * * 'MaxStreamsCloseCircuit' - Close the circuit if MaxStreams is
4665 * * 'BasicAuth' - Client authorization using the 'basic' method.
4666 * * 'NonAnonymous' - Add a non-anonymous Single Onion Service. If this
4667 * flag is present, tor must be in non-anonymous
4668 * hidden service mode. If this flag is absent,
4669 * tor must be in anonymous hidden service mode.
4671 static const char *discard_flag
= "DiscardPK";
4672 static const char *detach_flag
= "Detach";
4673 static const char *max_s_close_flag
= "MaxStreamsCloseCircuit";
4674 static const char *basicauth_flag
= "BasicAuth";
4675 static const char *non_anonymous_flag
= "NonAnonymous";
4677 smartlist_t
*flags
= smartlist_new();
4680 smartlist_split_string(flags
, arg
+ strlen(flags_prefix
), ",",
4681 SPLIT_IGNORE_BLANK
, 0);
4682 if (smartlist_len(flags
) < 1) {
4683 connection_printf_to_buf(conn
, "512 Invalid 'Flags' argument\r\n");
4686 SMARTLIST_FOREACH_BEGIN(flags
, const char *, flag
)
4688 if (!strcasecmp(flag
, discard_flag
)) {
4690 } else if (!strcasecmp(flag
, detach_flag
)) {
4692 } else if (!strcasecmp(flag
, max_s_close_flag
)) {
4693 max_streams_close_circuit
= 1;
4694 } else if (!strcasecmp(flag
, basicauth_flag
)) {
4695 auth_type
= REND_BASIC_AUTH
;
4696 } else if (!strcasecmp(flag
, non_anonymous_flag
)) {
4699 connection_printf_to_buf(conn
,
4700 "512 Invalid 'Flags' argument: %s\r\n",
4705 } SMARTLIST_FOREACH_END(flag
);
4706 SMARTLIST_FOREACH(flags
, char *, cp
, tor_free(cp
));
4707 smartlist_free(flags
);
4710 } else if (!strcasecmpstart(arg
, auth_prefix
)) {
4711 char *err_msg
= NULL
;
4713 rend_authorized_client_t
*client
=
4714 add_onion_helper_clientauth(arg
+ strlen(auth_prefix
),
4715 &created
, &err_msg
);
4718 connection_write_str_to_buf(err_msg
, conn
);
4724 if (auth_clients
!= NULL
) {
4726 SMARTLIST_FOREACH_BEGIN(auth_clients
, rend_authorized_client_t
*, ac
) {
4727 if (strcmp(ac
->client_name
, client
->client_name
) == 0) {
4731 } SMARTLIST_FOREACH_END(ac
);
4733 connection_printf_to_buf(conn
,
4734 "512 Duplicate name in ClientAuth\r\n");
4735 rend_authorized_client_free(client
);
4739 auth_clients
= smartlist_new();
4740 auth_created_clients
= smartlist_new();
4742 smartlist_add(auth_clients
, client
);
4744 smartlist_add(auth_created_clients
, client
);
4747 connection_printf_to_buf(conn
, "513 Invalid argument\r\n");
4751 if (smartlist_len(port_cfgs
) == 0) {
4752 connection_printf_to_buf(conn
, "512 Missing 'Port' argument\r\n");
4754 } else if (auth_type
== REND_NO_AUTH
&& auth_clients
!= NULL
) {
4755 connection_printf_to_buf(conn
, "512 No auth type specified\r\n");
4757 } else if (auth_type
!= REND_NO_AUTH
&& auth_clients
== NULL
) {
4758 connection_printf_to_buf(conn
, "512 No auth clients specified\r\n");
4760 } else if ((auth_type
== REND_BASIC_AUTH
&&
4761 smartlist_len(auth_clients
) > 512) ||
4762 (auth_type
== REND_STEALTH_AUTH
&&
4763 smartlist_len(auth_clients
) > 16)) {
4764 connection_printf_to_buf(conn
, "512 Too many auth clients\r\n");
4766 } else if (non_anonymous
!= rend_service_non_anonymous_mode_enabled(
4768 /* If we failed, and the non-anonymous flag is set, Tor must be in
4769 * anonymous hidden service mode.
4770 * The error message changes based on the current Tor config:
4771 * 512 Tor is in anonymous hidden service mode
4772 * 512 Tor is in non-anonymous hidden service mode
4773 * (I've deliberately written them out in full here to aid searchability.)
4775 connection_printf_to_buf(conn
, "512 Tor is in %sanonymous hidden service "
4777 non_anonymous
? "" : "non-");
4781 /* Parse the "keytype:keyblob" argument. */
4783 add_onion_secret_key_t pk
= { NULL
};
4784 const char *key_new_alg
= NULL
;
4785 char *key_new_blob
= NULL
;
4786 char *err_msg
= NULL
;
4788 if (add_onion_helper_keyarg(smartlist_get(args
, 0), discard_pk
,
4789 &key_new_alg
, &key_new_blob
, &pk
, &hs_version
,
4792 connection_write_str_to_buf(err_msg
, conn
);
4797 tor_assert(!err_msg
);
4799 /* Hidden service version 3 don't have client authentication support so if
4800 * ClientAuth was given, send back an error. */
4801 if (hs_version
== HS_VERSION_THREE
&& auth_clients
) {
4802 connection_printf_to_buf(conn
, "513 ClientAuth not supported\r\n");
4806 /* Create the HS, using private key pk, client authentication auth_type,
4807 * the list of auth_clients, and port config port_cfg.
4808 * rend_service_add_ephemeral() will take ownership of pk and port_cfg,
4809 * regardless of success/failure.
4811 char *service_id
= NULL
;
4812 int ret
= add_onion_helper_add_service(hs_version
, &pk
, port_cfgs
,
4814 max_streams_close_circuit
, auth_type
,
4815 auth_clients
, &service_id
);
4816 port_cfgs
= NULL
; /* port_cfgs is now owned by the rendservice code. */
4817 auth_clients
= NULL
; /* so is auth_clients */
4822 if (!detached_onion_services
)
4823 detached_onion_services
= smartlist_new();
4824 smartlist_add(detached_onion_services
, service_id
);
4826 if (!conn
->ephemeral_onion_services
)
4827 conn
->ephemeral_onion_services
= smartlist_new();
4828 smartlist_add(conn
->ephemeral_onion_services
, service_id
);
4831 tor_assert(service_id
);
4832 connection_printf_to_buf(conn
, "250-ServiceID=%s\r\n", service_id
);
4834 tor_assert(key_new_blob
);
4835 connection_printf_to_buf(conn
, "250-PrivateKey=%s:%s\r\n",
4836 key_new_alg
, key_new_blob
);
4838 if (auth_created_clients
) {
4839 SMARTLIST_FOREACH(auth_created_clients
, rend_authorized_client_t
*, ac
, {
4840 char *encoded
= rend_auth_encode_cookie(ac
->descriptor_cookie
,
4842 tor_assert(encoded
);
4843 connection_printf_to_buf(conn
, "250-ClientAuth=%s:%s\r\n",
4844 ac
->client_name
, encoded
);
4845 memwipe(encoded
, 0, strlen(encoded
));
4850 connection_printf_to_buf(conn
, "250 OK\r\n");
4853 case RSAE_BADPRIVKEY
:
4854 connection_printf_to_buf(conn
, "551 Failed to generate onion address\r\n");
4856 case RSAE_ADDREXISTS
:
4857 connection_printf_to_buf(conn
, "550 Onion address collision\r\n");
4859 case RSAE_BADVIRTPORT
:
4860 connection_printf_to_buf(conn
, "512 Invalid VIRTPORT/TARGET\r\n");
4863 connection_printf_to_buf(conn
, "512 Invalid client authorization\r\n");
4865 case RSAE_INTERNAL
: /* FALLSTHROUGH */
4867 connection_printf_to_buf(conn
, "551 Failed to add Onion Service\r\n");
4870 memwipe(key_new_blob
, 0, strlen(key_new_blob
));
4871 tor_free(key_new_blob
);
4876 SMARTLIST_FOREACH(port_cfgs
, rend_service_port_config_t
*, p
,
4877 rend_service_port_config_free(p
));
4878 smartlist_free(port_cfgs
);
4882 SMARTLIST_FOREACH(auth_clients
, rend_authorized_client_t
*, ac
,
4883 rend_authorized_client_free(ac
));
4884 smartlist_free(auth_clients
);
4886 if (auth_created_clients
) {
4887 // Do not free entries; they are the same as auth_clients
4888 smartlist_free(auth_created_clients
);
4891 SMARTLIST_FOREACH(args
, char *, cp
, {
4892 memwipe(cp
, 0, strlen(cp
));
4895 smartlist_free(args
);
4899 /** Helper function to handle parsing the KeyType:KeyBlob argument to the
4900 * ADD_ONION command. Return a new crypto_pk_t and if a new key was generated
4901 * and the private key not discarded, the algorithm and serialized private key,
4902 * or NULL and an optional control protocol error message on failure. The
4903 * caller is responsible for freeing the returned key_new_blob and err_msg.
4905 * Note: The error messages returned are deliberately vague to avoid echoing
4909 add_onion_helper_keyarg(const char *arg
, int discard_pk
,
4910 const char **key_new_alg_out
, char **key_new_blob_out
,
4911 add_onion_secret_key_t
*decoded_key
, int *hs_version
,
4914 smartlist_t
*key_args
= smartlist_new();
4915 crypto_pk_t
*pk
= NULL
;
4916 const char *key_new_alg
= NULL
;
4917 char *key_new_blob
= NULL
;
4918 char *err_msg
= NULL
;
4921 smartlist_split_string(key_args
, arg
, ":", SPLIT_IGNORE_BLANK
, 0);
4922 if (smartlist_len(key_args
) != 2) {
4923 err_msg
= tor_strdup("512 Invalid key type/blob\r\n");
4927 /* The format is "KeyType:KeyBlob". */
4928 static const char *key_type_new
= "NEW";
4929 static const char *key_type_best
= "BEST";
4930 static const char *key_type_rsa1024
= "RSA1024";
4931 static const char *key_type_ed25519_v3
= "ED25519-V3";
4933 const char *key_type
= smartlist_get(key_args
, 0);
4934 const char *key_blob
= smartlist_get(key_args
, 1);
4936 if (!strcasecmp(key_type_rsa1024
, key_type
)) {
4937 /* "RSA:<Base64 Blob>" - Loading a pre-existing RSA1024 key. */
4938 pk
= crypto_pk_base64_decode(key_blob
, strlen(key_blob
));
4940 err_msg
= tor_strdup("512 Failed to decode RSA key\r\n");
4943 if (crypto_pk_num_bits(pk
) != PK_BYTES
*8) {
4945 err_msg
= tor_strdup("512 Invalid RSA key size\r\n");
4948 decoded_key
->v2
= pk
;
4949 *hs_version
= HS_VERSION_TWO
;
4950 } else if (!strcasecmp(key_type_ed25519_v3
, key_type
)) {
4951 /* "ED25519-V3:<Base64 Blob>" - Loading a pre-existing ed25519 key. */
4952 ed25519_secret_key_t
*sk
= tor_malloc_zero(sizeof(*sk
));
4953 if (base64_decode((char *) sk
->seckey
, sizeof(sk
->seckey
), key_blob
,
4954 strlen(key_blob
)) != sizeof(sk
->seckey
)) {
4956 err_msg
= tor_strdup("512 Failed to decode ED25519-V3 key\r\n");
4959 decoded_key
->v3
= sk
;
4960 *hs_version
= HS_VERSION_THREE
;
4961 } else if (!strcasecmp(key_type_new
, key_type
)) {
4962 /* "NEW:<Algorithm>" - Generating a new key, blob as algorithm. */
4963 if (!strcasecmp(key_type_rsa1024
, key_blob
) ||
4964 !strcasecmp(key_type_best
, key_blob
)) {
4965 /* "RSA1024", RSA 1024 bit, also currently "BEST" by default. */
4966 pk
= crypto_pk_new();
4967 if (crypto_pk_generate_key(pk
)) {
4968 tor_asprintf(&err_msg
, "551 Failed to generate %s key\r\n",
4973 if (crypto_pk_base64_encode(pk
, &key_new_blob
)) {
4975 tor_asprintf(&err_msg
, "551 Failed to encode %s key\r\n",
4979 key_new_alg
= key_type_rsa1024
;
4981 decoded_key
->v2
= pk
;
4982 *hs_version
= HS_VERSION_TWO
;
4983 } else if (!strcasecmp(key_type_ed25519_v3
, key_blob
)) {
4984 ed25519_secret_key_t
*sk
= tor_malloc_zero(sizeof(*sk
));
4985 if (ed25519_secret_key_generate(sk
, 1) < 0) {
4987 tor_asprintf(&err_msg
, "551 Failed to generate %s key\r\n",
4988 key_type_ed25519_v3
);
4992 ssize_t len
= base64_encode_size(sizeof(sk
->seckey
), 0) + 1;
4993 key_new_blob
= tor_malloc_zero(len
);
4994 if (base64_encode(key_new_blob
, len
, (const char *) sk
->seckey
,
4995 sizeof(sk
->seckey
), 0) != (len
- 1)) {
4997 tor_free(key_new_blob
);
4998 tor_asprintf(&err_msg
, "551 Failed to encode %s key\r\n",
4999 key_type_ed25519_v3
);
5002 key_new_alg
= key_type_ed25519_v3
;
5004 decoded_key
->v3
= sk
;
5005 *hs_version
= HS_VERSION_THREE
;
5007 err_msg
= tor_strdup("513 Invalid key type\r\n");
5011 err_msg
= tor_strdup("513 Invalid key type\r\n");
5015 /* Succeeded in loading or generating a private key. */
5019 SMARTLIST_FOREACH(key_args
, char *, cp
, {
5020 memwipe(cp
, 0, strlen(cp
));
5023 smartlist_free(key_args
);
5026 *err_msg_out
= err_msg
;
5030 *key_new_alg_out
= key_new_alg
;
5031 *key_new_blob_out
= key_new_blob
;
5036 /** Helper function to handle parsing a ClientAuth argument to the
5037 * ADD_ONION command. Return a new rend_authorized_client_t, or NULL
5038 * and an optional control protocol error message on failure. The
5039 * caller is responsible for freeing the returned auth_client and err_msg.
5041 * If 'created' is specified, it will be set to 1 when a new cookie has
5044 STATIC rend_authorized_client_t
*
5045 add_onion_helper_clientauth(const char *arg
, int *created
, char **err_msg
)
5050 tor_assert(created
);
5051 tor_assert(err_msg
);
5054 smartlist_t
*auth_args
= smartlist_new();
5055 rend_authorized_client_t
*client
=
5056 tor_malloc_zero(sizeof(rend_authorized_client_t
));
5057 smartlist_split_string(auth_args
, arg
, ":", 0, 0);
5058 if (smartlist_len(auth_args
) < 1 || smartlist_len(auth_args
) > 2) {
5059 *err_msg
= tor_strdup("512 Invalid ClientAuth syntax\r\n");
5062 client
->client_name
= tor_strdup(smartlist_get(auth_args
, 0));
5063 if (smartlist_len(auth_args
) == 2) {
5064 char *decode_err_msg
= NULL
;
5065 if (rend_auth_decode_cookie(smartlist_get(auth_args
, 1),
5066 client
->descriptor_cookie
,
5067 NULL
, &decode_err_msg
) < 0) {
5068 tor_assert(decode_err_msg
);
5069 tor_asprintf(err_msg
, "512 %s\r\n", decode_err_msg
);
5070 tor_free(decode_err_msg
);
5075 crypto_rand((char *) client
->descriptor_cookie
, REND_DESC_COOKIE_LEN
);
5079 if (!rend_valid_client_name(client
->client_name
)) {
5080 *err_msg
= tor_strdup("512 Invalid name in ClientAuth\r\n");
5086 SMARTLIST_FOREACH(auth_args
, char *, item
, tor_free(item
));
5087 smartlist_free(auth_args
);
5089 rend_authorized_client_free(client
);
5095 /** Called when we get a DEL_ONION command; parse the body, and remove
5096 * the existing ephemeral Onion Service. */
5098 handle_control_del_onion(control_connection_t
*conn
,
5104 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
5105 args
= getargs_helper("DEL_ONION", conn
, body
, 1, 1);
5109 const char *service_id
= smartlist_get(args
, 0);
5110 if (rend_valid_v2_service_id(service_id
)) {
5111 hs_version
= HS_VERSION_TWO
;
5112 } else if (hs_address_is_valid(service_id
)) {
5113 hs_version
= HS_VERSION_THREE
;
5115 connection_printf_to_buf(conn
, "512 Malformed Onion Service id\r\n");
5119 /* Determine if the onion service belongs to this particular control
5120 * connection, or if it is in the global list of detached services. If it
5121 * is in neither, either the service ID is invalid in some way, or it
5122 * explicitly belongs to a different control connection, and an error
5123 * should be returned.
5125 smartlist_t
*services
[2] = {
5126 conn
->ephemeral_onion_services
,
5127 detached_onion_services
5129 smartlist_t
*onion_services
= NULL
;
5131 for (size_t i
= 0; i
< ARRAY_LENGTH(services
); i
++) {
5132 idx
= smartlist_string_pos(services
[i
], service_id
);
5134 onion_services
= services
[i
];
5138 if (onion_services
== NULL
) {
5139 connection_printf_to_buf(conn
, "552 Unknown Onion Service id\r\n");
5142 switch (hs_version
) {
5143 case HS_VERSION_TWO
:
5144 ret
= rend_service_del_ephemeral(service_id
);
5146 case HS_VERSION_THREE
:
5147 ret
= hs_service_del_ephemeral(service_id
);
5150 /* The ret value will be -1 thus hitting the warning below. This should
5151 * never happen because of the check at the start of the function. */
5155 /* This should *NEVER* fail, since the service is on either the
5156 * per-control connection list, or the global one.
5158 log_warn(LD_BUG
, "Failed to remove Onion Service %s.",
5159 escaped(service_id
));
5160 tor_fragile_assert();
5163 /* Remove/scrub the service_id from the appropriate list. */
5164 char *cp
= smartlist_get(onion_services
, idx
);
5165 smartlist_del(onion_services
, idx
);
5166 memwipe(cp
, 0, strlen(cp
));
5169 send_control_done(conn
);
5173 SMARTLIST_FOREACH(args
, char *, cp
, {
5174 memwipe(cp
, 0, strlen(cp
));
5177 smartlist_free(args
);
5181 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
5183 connection_control_finished_flushing(control_connection_t
*conn
)
5189 /** Called when <b>conn</b> has gotten its socket closed. */
5191 connection_control_reached_eof(control_connection_t
*conn
)
5195 log_info(LD_CONTROL
,"Control connection reached EOF. Closing.");
5196 connection_mark_for_close(TO_CONN(conn
));
5200 /** Shut down this Tor instance in the same way that SIGINT would, but
5201 * with a log message appropriate for the loss of an owning controller. */
5203 lost_owning_controller(const char *owner_type
, const char *loss_manner
)
5205 log_notice(LD_CONTROL
, "Owning controller %s has %s -- exiting now.",
5206 owner_type
, loss_manner
);
5208 activate_signal(SIGTERM
);
5211 /** Called when <b>conn</b> is being freed. */
5213 connection_control_closed(control_connection_t
*conn
)
5217 conn
->event_mask
= 0;
5218 control_update_global_event_mask();
5220 /* Close all ephemeral Onion Services if any.
5221 * The list and it's contents are scrubbed/freed in connection_free_.
5223 if (conn
->ephemeral_onion_services
) {
5224 SMARTLIST_FOREACH_BEGIN(conn
->ephemeral_onion_services
, char *, cp
) {
5225 if (rend_valid_v2_service_id(cp
)) {
5226 rend_service_del_ephemeral(cp
);
5227 } else if (hs_address_is_valid(cp
)) {
5228 hs_service_del_ephemeral(cp
);
5230 /* An invalid .onion in our list should NEVER happen */
5231 tor_fragile_assert();
5233 } SMARTLIST_FOREACH_END(cp
);
5236 if (conn
->is_owning_control_connection
) {
5237 lost_owning_controller("connection", "closed");
5241 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
5242 * stage of the protocol. */
5244 is_valid_initial_command(control_connection_t
*conn
, const char *cmd
)
5246 if (conn
->base_
.state
== CONTROL_CONN_STATE_OPEN
)
5248 if (!strcasecmp(cmd
, "PROTOCOLINFO"))
5249 return (!conn
->have_sent_protocolinfo
&&
5250 conn
->safecookie_client_hash
== NULL
);
5251 if (!strcasecmp(cmd
, "AUTHCHALLENGE"))
5252 return (conn
->safecookie_client_hash
== NULL
);
5253 if (!strcasecmp(cmd
, "AUTHENTICATE") ||
5254 !strcasecmp(cmd
, "QUIT"))
5259 /** Do not accept any control command of more than 1MB in length. Anything
5260 * that needs to be anywhere near this long probably means that one of our
5261 * interfaces is broken. */
5262 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
5264 /** Wrapper around peek_buf_has_control0 command: presents the same
5265 * interface as that underlying functions, but takes a connection_t intead of
5269 peek_connection_has_control0_command(connection_t
*conn
)
5271 return peek_buf_has_control0_command(conn
->inbuf
);
5275 peek_connection_has_http_command(connection_t
*conn
)
5277 return peek_buf_has_http_command(conn
->inbuf
);
5280 static const char CONTROLPORT_IS_NOT_AN_HTTP_PROXY_MSG
[] =
5281 "HTTP/1.0 501 Tor ControlPort is not an HTTP proxy"
5282 "\r\nContent-Type: text/html; charset=iso-8859-1\r\n\r\n"
5285 "<title>Tor's ControlPort is not an HTTP proxy</title>\n"
5288 "<h1>Tor's ControlPort is not an HTTP proxy</h1>\n"
5290 "It appears you have configured your web browser to use Tor's control port"
5291 " as an HTTP proxy.\n"
5292 "This is not correct: Tor's default SOCKS proxy port is 9050.\n"
5293 "Please configure your client accordingly.\n"
5296 "See <a href=\"https://www.torproject.org/documentation.html\">"
5297 "https://www.torproject.org/documentation.html</a> for more "
5299 "<!-- Plus this comment, to make the body response more than 512 bytes, so "
5300 " IE will be willing to display it. Comment comment comment comment "
5301 " comment comment comment comment comment comment comment comment.-->\n"
5306 /** Called when data has arrived on a v1 control connection: Try to fetch
5307 * commands from conn->inbuf, and execute them.
5310 connection_control_process_inbuf(control_connection_t
*conn
)
5313 uint32_t cmd_data_len
;
5318 tor_assert(conn
->base_
.state
== CONTROL_CONN_STATE_OPEN
||
5319 conn
->base_
.state
== CONTROL_CONN_STATE_NEEDAUTH
);
5321 if (!conn
->incoming_cmd
) {
5322 conn
->incoming_cmd
= tor_malloc(1024);
5323 conn
->incoming_cmd_len
= 1024;
5324 conn
->incoming_cmd_cur_len
= 0;
5327 if (conn
->base_
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
5328 peek_connection_has_control0_command(TO_CONN(conn
))) {
5329 /* Detect v0 commands and send a "no more v0" message. */
5332 set_uint16(buf
+2, htons(0x0000)); /* type == error */
5333 set_uint16(buf
+4, htons(0x0001)); /* code == internal error */
5334 strlcpy(buf
+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
5335 "and later; upgrade your controller.",
5337 body_len
= 2+strlen(buf
+6)+2; /* code, msg, nul. */
5338 set_uint16(buf
+0, htons(body_len
));
5339 connection_buf_add(buf
, 4+body_len
, TO_CONN(conn
));
5341 connection_mark_and_flush(TO_CONN(conn
));
5345 /* If the user has the HTTP proxy port and the control port confused. */
5346 if (conn
->base_
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
5347 peek_connection_has_http_command(TO_CONN(conn
))) {
5348 connection_write_str_to_buf(CONTROLPORT_IS_NOT_AN_HTTP_PROXY_MSG
, conn
);
5349 log_notice(LD_CONTROL
, "Received HTTP request on ControlPort");
5350 connection_mark_and_flush(TO_CONN(conn
));
5358 /* First, fetch a line. */
5360 data_len
= conn
->incoming_cmd_len
- conn
->incoming_cmd_cur_len
;
5361 r
= connection_buf_get_line(TO_CONN(conn
),
5362 conn
->incoming_cmd
+conn
->incoming_cmd_cur_len
,
5365 /* Line not all here yet. Wait. */
5368 if (data_len
+ conn
->incoming_cmd_cur_len
> MAX_COMMAND_LINE_LENGTH
) {
5369 connection_write_str_to_buf("500 Line too long.\r\n", conn
);
5370 connection_stop_reading(TO_CONN(conn
));
5371 connection_mark_and_flush(TO_CONN(conn
));
5373 while (conn
->incoming_cmd_len
< data_len
+conn
->incoming_cmd_cur_len
)
5374 conn
->incoming_cmd_len
*= 2;
5375 conn
->incoming_cmd
= tor_realloc(conn
->incoming_cmd
,
5376 conn
->incoming_cmd_len
);
5380 tor_assert(data_len
);
5382 last_idx
= conn
->incoming_cmd_cur_len
;
5383 conn
->incoming_cmd_cur_len
+= (int)data_len
;
5385 /* We have appended a line to incoming_cmd. Is the command done? */
5386 if (last_idx
== 0 && *conn
->incoming_cmd
!= '+')
5387 /* One line command, didn't start with '+'. */
5389 /* XXXX this code duplication is kind of dumb. */
5390 if (last_idx
+3 == conn
->incoming_cmd_cur_len
&&
5391 tor_memeq(conn
->incoming_cmd
+ last_idx
, ".\r\n", 3)) {
5392 /* Just appended ".\r\n"; we're done. Remove it. */
5393 conn
->incoming_cmd
[last_idx
] = '\0';
5394 conn
->incoming_cmd_cur_len
-= 3;
5396 } else if (last_idx
+2 == conn
->incoming_cmd_cur_len
&&
5397 tor_memeq(conn
->incoming_cmd
+ last_idx
, ".\n", 2)) {
5398 /* Just appended ".\n"; we're done. Remove it. */
5399 conn
->incoming_cmd
[last_idx
] = '\0';
5400 conn
->incoming_cmd_cur_len
-= 2;
5403 /* Otherwise, read another line. */
5405 data_len
= conn
->incoming_cmd_cur_len
;
5406 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
5410 while ((size_t)cmd_len
< data_len
5411 && !TOR_ISSPACE(conn
->incoming_cmd
[cmd_len
]))
5414 conn
->incoming_cmd
[cmd_len
]='\0';
5415 args
= conn
->incoming_cmd
+cmd_len
+1;
5416 tor_assert(data_len
>(size_t)cmd_len
);
5417 data_len
-= (cmd_len
+1); /* skip the command and NUL we added after it */
5418 while (TOR_ISSPACE(*args
)) {
5423 /* If the connection is already closing, ignore further commands */
5424 if (TO_CONN(conn
)->marked_for_close
) {
5428 /* Otherwise, Quit is always valid. */
5429 if (!strcasecmp(conn
->incoming_cmd
, "QUIT")) {
5430 connection_write_str_to_buf("250 closing connection\r\n", conn
);
5431 connection_mark_and_flush(TO_CONN(conn
));
5435 if (conn
->base_
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
5436 !is_valid_initial_command(conn
, conn
->incoming_cmd
)) {
5437 connection_write_str_to_buf("514 Authentication required.\r\n", conn
);
5438 connection_mark_for_close(TO_CONN(conn
));
5442 if (data_len
>= UINT32_MAX
) {
5443 connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn
);
5444 connection_mark_for_close(TO_CONN(conn
));
5448 /* XXXX Why is this not implemented as a table like the GETINFO
5449 * items are? Even handling the plus signs at the beginnings of
5450 * commands wouldn't be very hard with proper macros. */
5451 cmd_data_len
= (uint32_t)data_len
;
5452 if (!strcasecmp(conn
->incoming_cmd
, "SETCONF")) {
5453 if (handle_control_setconf(conn
, cmd_data_len
, args
))
5455 } else if (!strcasecmp(conn
->incoming_cmd
, "RESETCONF")) {
5456 if (handle_control_resetconf(conn
, cmd_data_len
, args
))
5458 } else if (!strcasecmp(conn
->incoming_cmd
, "GETCONF")) {
5459 if (handle_control_getconf(conn
, cmd_data_len
, args
))
5461 } else if (!strcasecmp(conn
->incoming_cmd
, "+LOADCONF")) {
5462 if (handle_control_loadconf(conn
, cmd_data_len
, args
))
5464 } else if (!strcasecmp(conn
->incoming_cmd
, "SETEVENTS")) {
5465 if (handle_control_setevents(conn
, cmd_data_len
, args
))
5467 } else if (!strcasecmp(conn
->incoming_cmd
, "AUTHENTICATE")) {
5468 if (handle_control_authenticate(conn
, cmd_data_len
, args
))
5470 } else if (!strcasecmp(conn
->incoming_cmd
, "SAVECONF")) {
5471 if (handle_control_saveconf(conn
, cmd_data_len
, args
))
5473 } else if (!strcasecmp(conn
->incoming_cmd
, "SIGNAL")) {
5474 if (handle_control_signal(conn
, cmd_data_len
, args
))
5476 } else if (!strcasecmp(conn
->incoming_cmd
, "TAKEOWNERSHIP")) {
5477 if (handle_control_takeownership(conn
, cmd_data_len
, args
))
5479 } else if (!strcasecmp(conn
->incoming_cmd
, "MAPADDRESS")) {
5480 if (handle_control_mapaddress(conn
, cmd_data_len
, args
))
5482 } else if (!strcasecmp(conn
->incoming_cmd
, "GETINFO")) {
5483 if (handle_control_getinfo(conn
, cmd_data_len
, args
))
5485 } else if (!strcasecmp(conn
->incoming_cmd
, "EXTENDCIRCUIT")) {
5486 if (handle_control_extendcircuit(conn
, cmd_data_len
, args
))
5488 } else if (!strcasecmp(conn
->incoming_cmd
, "SETCIRCUITPURPOSE")) {
5489 if (handle_control_setcircuitpurpose(conn
, cmd_data_len
, args
))
5491 } else if (!strcasecmp(conn
->incoming_cmd
, "SETROUTERPURPOSE")) {
5492 connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn
);
5493 } else if (!strcasecmp(conn
->incoming_cmd
, "ATTACHSTREAM")) {
5494 if (handle_control_attachstream(conn
, cmd_data_len
, args
))
5496 } else if (!strcasecmp(conn
->incoming_cmd
, "+POSTDESCRIPTOR")) {
5497 if (handle_control_postdescriptor(conn
, cmd_data_len
, args
))
5499 } else if (!strcasecmp(conn
->incoming_cmd
, "REDIRECTSTREAM")) {
5500 if (handle_control_redirectstream(conn
, cmd_data_len
, args
))
5502 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSESTREAM")) {
5503 if (handle_control_closestream(conn
, cmd_data_len
, args
))
5505 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSECIRCUIT")) {
5506 if (handle_control_closecircuit(conn
, cmd_data_len
, args
))
5508 } else if (!strcasecmp(conn
->incoming_cmd
, "USEFEATURE")) {
5509 if (handle_control_usefeature(conn
, cmd_data_len
, args
))
5511 } else if (!strcasecmp(conn
->incoming_cmd
, "RESOLVE")) {
5512 if (handle_control_resolve(conn
, cmd_data_len
, args
))
5514 } else if (!strcasecmp(conn
->incoming_cmd
, "PROTOCOLINFO")) {
5515 if (handle_control_protocolinfo(conn
, cmd_data_len
, args
))
5517 } else if (!strcasecmp(conn
->incoming_cmd
, "AUTHCHALLENGE")) {
5518 if (handle_control_authchallenge(conn
, cmd_data_len
, args
))
5520 } else if (!strcasecmp(conn
->incoming_cmd
, "DROPGUARDS")) {
5521 if (handle_control_dropguards(conn
, cmd_data_len
, args
))
5523 } else if (!strcasecmp(conn
->incoming_cmd
, "HSFETCH")) {
5524 if (handle_control_hsfetch(conn
, cmd_data_len
, args
))
5526 } else if (!strcasecmp(conn
->incoming_cmd
, "+HSPOST")) {
5527 if (handle_control_hspost(conn
, cmd_data_len
, args
))
5529 } else if (!strcasecmp(conn
->incoming_cmd
, "ADD_ONION")) {
5530 int ret
= handle_control_add_onion(conn
, cmd_data_len
, args
);
5531 memwipe(args
, 0, cmd_data_len
); /* Scrub the private key. */
5534 } else if (!strcasecmp(conn
->incoming_cmd
, "DEL_ONION")) {
5535 int ret
= handle_control_del_onion(conn
, cmd_data_len
, args
);
5536 memwipe(args
, 0, cmd_data_len
); /* Scrub the service id/pk. */
5540 connection_printf_to_buf(conn
, "510 Unrecognized command \"%s\"\r\n",
5541 conn
->incoming_cmd
);
5544 conn
->incoming_cmd_cur_len
= 0;
5548 /** Something major has happened to circuit <b>circ</b>: tell any
5549 * interested control connections. */
5551 control_event_circuit_status(origin_circuit_t
*circ
, circuit_status_event_t tp
,
5555 char reasons
[64] = "";
5556 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS
))
5562 case CIRC_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
5563 case CIRC_EVENT_BUILT
: status
= "BUILT"; break;
5564 case CIRC_EVENT_EXTENDED
: status
= "EXTENDED"; break;
5565 case CIRC_EVENT_FAILED
: status
= "FAILED"; break;
5566 case CIRC_EVENT_CLOSED
: status
= "CLOSED"; break;
5568 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
5569 tor_fragile_assert();
5573 if (tp
== CIRC_EVENT_FAILED
|| tp
== CIRC_EVENT_CLOSED
) {
5574 const char *reason_str
= circuit_end_reason_to_control_string(reason_code
);
5575 char unk_reason_buf
[16];
5577 tor_snprintf(unk_reason_buf
, 16, "UNKNOWN_%d", reason_code
);
5578 reason_str
= unk_reason_buf
;
5580 if (reason_code
> 0 && reason_code
& END_CIRC_REASON_FLAG_REMOTE
) {
5581 tor_snprintf(reasons
, sizeof(reasons
),
5582 " REASON=DESTROYED REMOTE_REASON=%s", reason_str
);
5584 tor_snprintf(reasons
, sizeof(reasons
),
5585 " REASON=%s", reason_str
);
5590 char *circdesc
= circuit_describe_status_for_controller(circ
);
5591 const char *sp
= strlen(circdesc
) ? " " : "";
5592 send_control_event(EVENT_CIRCUIT_STATUS
,
5593 "650 CIRC %lu %s%s%s%s\r\n",
5594 (unsigned long)circ
->global_identifier
,
5604 /** Something minor has happened to circuit <b>circ</b>: tell any
5605 * interested control connections. */
5607 control_event_circuit_status_minor(origin_circuit_t
*circ
,
5608 circuit_status_minor_event_t e
,
5609 int purpose
, const struct timeval
*tv
)
5611 const char *event_desc
;
5612 char event_tail
[160] = "";
5613 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR
))
5619 case CIRC_MINOR_EVENT_PURPOSE_CHANGED
:
5620 event_desc
= "PURPOSE_CHANGED";
5623 /* event_tail can currently be up to 68 chars long */
5624 const char *hs_state_str
=
5625 circuit_purpose_to_controller_hs_state_string(purpose
);
5626 tor_snprintf(event_tail
, sizeof(event_tail
),
5627 " OLD_PURPOSE=%s%s%s",
5628 circuit_purpose_to_controller_string(purpose
),
5629 (hs_state_str
!= NULL
) ? " OLD_HS_STATE=" : "",
5630 (hs_state_str
!= NULL
) ? hs_state_str
: "");
5634 case CIRC_MINOR_EVENT_CANNIBALIZED
:
5635 event_desc
= "CANNIBALIZED";
5638 /* event_tail can currently be up to 130 chars long */
5639 const char *hs_state_str
=
5640 circuit_purpose_to_controller_hs_state_string(purpose
);
5641 const struct timeval
*old_timestamp_began
= tv
;
5642 char tbuf
[ISO_TIME_USEC_LEN
+1];
5643 format_iso_time_nospace_usec(tbuf
, old_timestamp_began
);
5645 tor_snprintf(event_tail
, sizeof(event_tail
),
5646 " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
5647 circuit_purpose_to_controller_string(purpose
),
5648 (hs_state_str
!= NULL
) ? " OLD_HS_STATE=" : "",
5649 (hs_state_str
!= NULL
) ? hs_state_str
: "",
5655 log_warn(LD_BUG
, "Unrecognized status code %d", (int)e
);
5656 tor_fragile_assert();
5661 char *circdesc
= circuit_describe_status_for_controller(circ
);
5662 const char *sp
= strlen(circdesc
) ? " " : "";
5663 send_control_event(EVENT_CIRCUIT_STATUS_MINOR
,
5664 "650 CIRC_MINOR %lu %s%s%s%s\r\n",
5665 (unsigned long)circ
->global_identifier
,
5676 * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
5677 * interested controllers.
5680 control_event_circuit_purpose_changed(origin_circuit_t
*circ
,
5683 return control_event_circuit_status_minor(circ
,
5684 CIRC_MINOR_EVENT_PURPOSE_CHANGED
,
5690 * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
5691 * created-time from <b>old_tv_created</b>: tell any interested controllers.
5694 control_event_circuit_cannibalized(origin_circuit_t
*circ
,
5696 const struct timeval
*old_tv_created
)
5698 return control_event_circuit_status_minor(circ
,
5699 CIRC_MINOR_EVENT_CANNIBALIZED
,
5704 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
5705 * <b>buf</b>, determine the address:port combination requested on
5706 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
5709 write_stream_target_to_buf(entry_connection_t
*conn
, char *buf
, size_t len
)
5712 if (conn
->chosen_exit_name
)
5713 if (tor_snprintf(buf2
, sizeof(buf2
), ".%s.exit", conn
->chosen_exit_name
)<0)
5715 if (!conn
->socks_request
)
5717 if (tor_snprintf(buf
, len
, "%s%s%s:%d",
5718 conn
->socks_request
->address
,
5719 conn
->chosen_exit_name
? buf2
: "",
5720 !conn
->chosen_exit_name
&& connection_edge_is_rendezvous_stream(
5721 ENTRY_TO_EDGE_CONN(conn
)) ? ".onion" : "",
5722 conn
->socks_request
->port
)<0)
5727 /** Something has happened to the stream associated with AP connection
5728 * <b>conn</b>: tell any interested control connections. */
5730 control_event_stream_status(entry_connection_t
*conn
, stream_status_event_t tp
,
5733 char reason_buf
[64];
5734 char addrport_buf
[64];
5737 origin_circuit_t
*origin_circ
= NULL
;
5739 const char *purpose
= "";
5740 tor_assert(conn
->socks_request
);
5742 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS
))
5745 if (tp
== STREAM_EVENT_CLOSED
&&
5746 (reason_code
& END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
))
5749 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
5751 reason_buf
[0] = '\0';
5754 case STREAM_EVENT_SENT_CONNECT
: status
= "SENTCONNECT"; break;
5755 case STREAM_EVENT_SENT_RESOLVE
: status
= "SENTRESOLVE"; break;
5756 case STREAM_EVENT_SUCCEEDED
: status
= "SUCCEEDED"; break;
5757 case STREAM_EVENT_FAILED
: status
= "FAILED"; break;
5758 case STREAM_EVENT_CLOSED
: status
= "CLOSED"; break;
5759 case STREAM_EVENT_NEW
: status
= "NEW"; break;
5760 case STREAM_EVENT_NEW_RESOLVE
: status
= "NEWRESOLVE"; break;
5761 case STREAM_EVENT_FAILED_RETRIABLE
: status
= "DETACHED"; break;
5762 case STREAM_EVENT_REMAP
: status
= "REMAP"; break;
5764 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
5767 if (reason_code
&& (tp
== STREAM_EVENT_FAILED
||
5768 tp
== STREAM_EVENT_CLOSED
||
5769 tp
== STREAM_EVENT_FAILED_RETRIABLE
)) {
5770 const char *reason_str
= stream_end_reason_to_control_string(reason_code
);
5773 tor_asprintf(&r
, " UNKNOWN_%d", reason_code
);
5776 if (reason_code
& END_STREAM_REASON_FLAG_REMOTE
)
5777 tor_snprintf(reason_buf
, sizeof(reason_buf
),
5778 " REASON=END REMOTE_REASON=%s", reason_str
);
5780 tor_snprintf(reason_buf
, sizeof(reason_buf
),
5781 " REASON=%s", reason_str
);
5783 } else if (reason_code
&& tp
== STREAM_EVENT_REMAP
) {
5784 switch (reason_code
) {
5785 case REMAP_STREAM_SOURCE_CACHE
:
5786 strlcpy(reason_buf
, " SOURCE=CACHE", sizeof(reason_buf
));
5788 case REMAP_STREAM_SOURCE_EXIT
:
5789 strlcpy(reason_buf
, " SOURCE=EXIT", sizeof(reason_buf
));
5792 tor_snprintf(reason_buf
, sizeof(reason_buf
), " REASON=UNKNOWN_%d",
5794 /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
5799 if (tp
== STREAM_EVENT_NEW
|| tp
== STREAM_EVENT_NEW_RESOLVE
) {
5801 * When the control conn is an AF_UNIX socket and we have no address,
5802 * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
5805 if (strcmp(ENTRY_TO_CONN(conn
)->address
, "(Tor_internal)") != 0) {
5806 tor_snprintf(addrport_buf
,sizeof(addrport_buf
), " SOURCE_ADDR=%s:%d",
5807 ENTRY_TO_CONN(conn
)->address
, ENTRY_TO_CONN(conn
)->port
);
5810 * else leave it blank so control on AF_UNIX doesn't need to make
5813 addrport_buf
[0] = '\0';
5816 addrport_buf
[0] = '\0';
5819 if (tp
== STREAM_EVENT_NEW_RESOLVE
) {
5820 purpose
= " PURPOSE=DNS_REQUEST";
5821 } else if (tp
== STREAM_EVENT_NEW
) {
5822 if (conn
->use_begindir
) {
5823 connection_t
*linked
= ENTRY_TO_CONN(conn
)->linked_conn
;
5824 int linked_dir_purpose
= -1;
5825 if (linked
&& linked
->type
== CONN_TYPE_DIR
)
5826 linked_dir_purpose
= linked
->purpose
;
5827 if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose
))
5828 purpose
= " PURPOSE=DIR_UPLOAD";
5830 purpose
= " PURPOSE=DIR_FETCH";
5832 purpose
= " PURPOSE=USER";
5835 circ
= circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn
));
5836 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
5837 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
5838 send_control_event(EVENT_STREAM_STATUS
,
5839 "650 STREAM "U64_FORMAT
" %s %lu %s%s%s%s\r\n",
5840 U64_PRINTF_ARG(ENTRY_TO_CONN(conn
)->global_identifier
),
5843 (unsigned long)origin_circ
->global_identifier
: 0ul,
5844 buf
, reason_buf
, addrport_buf
, purpose
);
5846 /* XXX need to specify its intended exit, etc? */
5851 /** Figure out the best name for the target router of an OR connection
5852 * <b>conn</b>, and write it into the <b>len</b>-character buffer
5855 orconn_target_get_name(char *name
, size_t len
, or_connection_t
*conn
)
5857 const node_t
*node
= node_get_by_id(conn
->identity_digest
);
5859 tor_assert(len
> MAX_VERBOSE_NICKNAME_LEN
);
5860 node_get_verbose_nickname(node
, name
);
5861 } else if (! tor_digest_is_zero(conn
->identity_digest
)) {
5863 base16_encode(name
+1, len
-1, conn
->identity_digest
,
5866 tor_snprintf(name
, len
, "%s:%d",
5867 conn
->base_
.address
, conn
->base_
.port
);
5871 /** Called when the status of an OR connection <b>conn</b> changes: tell any
5872 * interested control connections. <b>tp</b> is the new status for the
5873 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
5874 * may be the reason why.
5877 control_event_or_conn_status(or_connection_t
*conn
, or_conn_status_event_t tp
,
5883 char ncircs_buf
[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
5885 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS
))
5890 case OR_CONN_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
5891 case OR_CONN_EVENT_CONNECTED
: status
= "CONNECTED"; break;
5892 case OR_CONN_EVENT_FAILED
: status
= "FAILED"; break;
5893 case OR_CONN_EVENT_CLOSED
: status
= "CLOSED"; break;
5894 case OR_CONN_EVENT_NEW
: status
= "NEW"; break;
5896 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
5900 ncircs
= circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn
->chan
));
5904 ncircs
+= connection_or_get_num_circuits(conn
);
5905 if (ncircs
&& (tp
== OR_CONN_EVENT_FAILED
|| tp
== OR_CONN_EVENT_CLOSED
)) {
5906 tor_snprintf(ncircs_buf
, sizeof(ncircs_buf
), " NCIRCS=%d", ncircs
);
5909 orconn_target_get_name(name
, sizeof(name
), conn
);
5910 send_control_event(EVENT_OR_CONN_STATUS
,
5911 "650 ORCONN %s %s%s%s%s ID="U64_FORMAT
"\r\n",
5913 reason
? " REASON=" : "",
5914 orconn_end_reason_to_control_string(reason
),
5916 U64_PRINTF_ARG(conn
->base_
.global_identifier
));
5922 * Print out STREAM_BW event for a single conn
5925 control_event_stream_bandwidth(edge_connection_t
*edge_conn
)
5928 char tbuf
[ISO_TIME_USEC_LEN
+1];
5929 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED
)) {
5930 if (!edge_conn
->n_read
&& !edge_conn
->n_written
)
5933 tor_gettimeofday(&now
);
5934 format_iso_time_nospace_usec(tbuf
, &now
);
5935 send_control_event(EVENT_STREAM_BANDWIDTH_USED
,
5936 "650 STREAM_BW "U64_FORMAT
" %lu %lu %s\r\n",
5937 U64_PRINTF_ARG(edge_conn
->base_
.global_identifier
),
5938 (unsigned long)edge_conn
->n_read
,
5939 (unsigned long)edge_conn
->n_written
,
5942 edge_conn
->n_written
= edge_conn
->n_read
= 0;
5948 /** A second or more has elapsed: tell any interested control
5949 * connections how much bandwidth streams have used. */
5951 control_event_stream_bandwidth_used(void)
5953 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED
)) {
5954 smartlist_t
*conns
= get_connection_array();
5955 edge_connection_t
*edge_conn
;
5957 char tbuf
[ISO_TIME_USEC_LEN
+1];
5959 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
)
5961 if (conn
->type
!= CONN_TYPE_AP
)
5963 edge_conn
= TO_EDGE_CONN(conn
);
5964 if (!edge_conn
->n_read
&& !edge_conn
->n_written
)
5967 tor_gettimeofday(&now
);
5968 format_iso_time_nospace_usec(tbuf
, &now
);
5969 send_control_event(EVENT_STREAM_BANDWIDTH_USED
,
5970 "650 STREAM_BW "U64_FORMAT
" %lu %lu %s\r\n",
5971 U64_PRINTF_ARG(edge_conn
->base_
.global_identifier
),
5972 (unsigned long)edge_conn
->n_read
,
5973 (unsigned long)edge_conn
->n_written
,
5976 edge_conn
->n_written
= edge_conn
->n_read
= 0;
5978 SMARTLIST_FOREACH_END(conn
);
5984 /** A second or more has elapsed: tell any interested control connections
5985 * how much bandwidth origin circuits have used. */
5987 control_event_circ_bandwidth_used(void)
5989 origin_circuit_t
*ocirc
;
5991 char tbuf
[ISO_TIME_USEC_LEN
+1];
5992 if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED
))
5995 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t
*, circ
) {
5996 if (!CIRCUIT_IS_ORIGIN(circ
))
5998 ocirc
= TO_ORIGIN_CIRCUIT(circ
);
5999 if (!ocirc
->n_read_circ_bw
&& !ocirc
->n_written_circ_bw
)
6001 tor_gettimeofday(&now
);
6002 format_iso_time_nospace_usec(tbuf
, &now
);
6003 send_control_event(EVENT_CIRC_BANDWIDTH_USED
,
6004 "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu TIME=%s "
6005 "DELIVERED_READ=%lu OVERHEAD_READ=%lu "
6006 "DELIVERED_WRITTEN=%lu OVERHEAD_WRITTEN=%lu\r\n",
6007 ocirc
->global_identifier
,
6008 (unsigned long)ocirc
->n_read_circ_bw
,
6009 (unsigned long)ocirc
->n_written_circ_bw
,
6011 (unsigned long)ocirc
->n_delivered_read_circ_bw
,
6012 (unsigned long)ocirc
->n_overhead_read_circ_bw
,
6013 (unsigned long)ocirc
->n_delivered_written_circ_bw
,
6014 (unsigned long)ocirc
->n_overhead_written_circ_bw
);
6015 ocirc
->n_written_circ_bw
= ocirc
->n_read_circ_bw
= 0;
6016 ocirc
->n_overhead_written_circ_bw
= ocirc
->n_overhead_read_circ_bw
= 0;
6017 ocirc
->n_delivered_written_circ_bw
= ocirc
->n_delivered_read_circ_bw
= 0;
6019 SMARTLIST_FOREACH_END(circ
);
6024 /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
6025 * bandwidth counters. */
6027 control_event_conn_bandwidth(connection_t
*conn
)
6029 const char *conn_type_str
;
6030 if (!get_options()->TestingEnableConnBwEvent
||
6031 !EVENT_IS_INTERESTING(EVENT_CONN_BW
))
6033 if (!conn
->n_read_conn_bw
&& !conn
->n_written_conn_bw
)
6035 switch (conn
->type
) {
6037 conn_type_str
= "OR";
6040 conn_type_str
= "DIR";
6042 case CONN_TYPE_EXIT
:
6043 conn_type_str
= "EXIT";
6048 send_control_event(EVENT_CONN_BW
,
6049 "650 CONN_BW ID="U64_FORMAT
" TYPE=%s "
6050 "READ=%lu WRITTEN=%lu\r\n",
6051 U64_PRINTF_ARG(conn
->global_identifier
),
6053 (unsigned long)conn
->n_read_conn_bw
,
6054 (unsigned long)conn
->n_written_conn_bw
);
6055 conn
->n_written_conn_bw
= conn
->n_read_conn_bw
= 0;
6059 /** A second or more has elapsed: tell any interested control
6060 * connections how much bandwidth connections have used. */
6062 control_event_conn_bandwidth_used(void)
6064 if (get_options()->TestingEnableConnBwEvent
&&
6065 EVENT_IS_INTERESTING(EVENT_CONN_BW
)) {
6066 SMARTLIST_FOREACH(get_connection_array(), connection_t
*, conn
,
6067 control_event_conn_bandwidth(conn
));
6072 /** Helper: iterate over cell statistics of <b>circ</b> and sum up added
6073 * cells, removed cells, and waiting times by cell command and direction.
6074 * Store results in <b>cell_stats</b>. Free cell statistics of the
6075 * circuit afterwards. */
6077 sum_up_cell_stats_by_command(circuit_t
*circ
, cell_stats_t
*cell_stats
)
6079 memset(cell_stats
, 0, sizeof(cell_stats_t
));
6080 SMARTLIST_FOREACH_BEGIN(circ
->testing_cell_stats
,
6081 const testing_cell_stats_entry_t
*, ent
) {
6082 tor_assert(ent
->command
<= CELL_COMMAND_MAX_
);
6083 if (!ent
->removed
&& !ent
->exitward
) {
6084 cell_stats
->added_cells_appward
[ent
->command
] += 1;
6085 } else if (!ent
->removed
&& ent
->exitward
) {
6086 cell_stats
->added_cells_exitward
[ent
->command
] += 1;
6087 } else if (!ent
->exitward
) {
6088 cell_stats
->removed_cells_appward
[ent
->command
] += 1;
6089 cell_stats
->total_time_appward
[ent
->command
] += ent
->waiting_time
* 10;
6091 cell_stats
->removed_cells_exitward
[ent
->command
] += 1;
6092 cell_stats
->total_time_exitward
[ent
->command
] += ent
->waiting_time
* 10;
6094 } SMARTLIST_FOREACH_END(ent
);
6095 circuit_clear_testing_cell_stats(circ
);
6098 /** Helper: append a cell statistics string to <code>event_parts</code>,
6099 * prefixed with <code>key</code>=. Statistics consist of comma-separated
6100 * key:value pairs with lower-case command strings as keys and cell
6101 * numbers or total waiting times as values. A key:value pair is included
6102 * if the entry in <code>include_if_non_zero</code> is not zero, but with
6103 * the (possibly zero) entry from <code>number_to_include</code>. Both
6104 * arrays are expected to have a length of CELL_COMMAND_MAX_ + 1. If no
6105 * entry in <code>include_if_non_zero</code> is positive, no string will
6106 * be added to <code>event_parts</code>. */
6108 append_cell_stats_by_command(smartlist_t
*event_parts
, const char *key
,
6109 const uint64_t *include_if_non_zero
,
6110 const uint64_t *number_to_include
)
6112 smartlist_t
*key_value_strings
= smartlist_new();
6114 for (i
= 0; i
<= CELL_COMMAND_MAX_
; i
++) {
6115 if (include_if_non_zero
[i
] > 0) {
6116 smartlist_add_asprintf(key_value_strings
, "%s:"U64_FORMAT
,
6117 cell_command_to_string(i
),
6118 U64_PRINTF_ARG(number_to_include
[i
]));
6121 if (smartlist_len(key_value_strings
) > 0) {
6122 char *joined
= smartlist_join_strings(key_value_strings
, ",", 0, NULL
);
6123 smartlist_add_asprintf(event_parts
, "%s=%s", key
, joined
);
6124 SMARTLIST_FOREACH(key_value_strings
, char *, cp
, tor_free(cp
));
6127 smartlist_free(key_value_strings
);
6130 /** Helper: format <b>cell_stats</b> for <b>circ</b> for inclusion in a
6131 * CELL_STATS event and write result string to <b>event_string</b>. */
6133 format_cell_stats(char **event_string
, circuit_t
*circ
,
6134 cell_stats_t
*cell_stats
)
6136 smartlist_t
*event_parts
= smartlist_new();
6137 if (CIRCUIT_IS_ORIGIN(circ
)) {
6138 origin_circuit_t
*ocirc
= TO_ORIGIN_CIRCUIT(circ
);
6139 smartlist_add_asprintf(event_parts
, "ID=%lu",
6140 (unsigned long)ocirc
->global_identifier
);
6141 } else if (TO_OR_CIRCUIT(circ
)->p_chan
) {
6142 or_circuit_t
*or_circ
= TO_OR_CIRCUIT(circ
);
6143 smartlist_add_asprintf(event_parts
, "InboundQueue=%lu",
6144 (unsigned long)or_circ
->p_circ_id
);
6145 smartlist_add_asprintf(event_parts
, "InboundConn="U64_FORMAT
,
6146 U64_PRINTF_ARG(or_circ
->p_chan
->global_identifier
));
6147 append_cell_stats_by_command(event_parts
, "InboundAdded",
6148 cell_stats
->added_cells_appward
,
6149 cell_stats
->added_cells_appward
);
6150 append_cell_stats_by_command(event_parts
, "InboundRemoved",
6151 cell_stats
->removed_cells_appward
,
6152 cell_stats
->removed_cells_appward
);
6153 append_cell_stats_by_command(event_parts
, "InboundTime",
6154 cell_stats
->removed_cells_appward
,
6155 cell_stats
->total_time_appward
);
6158 smartlist_add_asprintf(event_parts
, "OutboundQueue=%lu",
6159 (unsigned long)circ
->n_circ_id
);
6160 smartlist_add_asprintf(event_parts
, "OutboundConn="U64_FORMAT
,
6161 U64_PRINTF_ARG(circ
->n_chan
->global_identifier
));
6162 append_cell_stats_by_command(event_parts
, "OutboundAdded",
6163 cell_stats
->added_cells_exitward
,
6164 cell_stats
->added_cells_exitward
);
6165 append_cell_stats_by_command(event_parts
, "OutboundRemoved",
6166 cell_stats
->removed_cells_exitward
,
6167 cell_stats
->removed_cells_exitward
);
6168 append_cell_stats_by_command(event_parts
, "OutboundTime",
6169 cell_stats
->removed_cells_exitward
,
6170 cell_stats
->total_time_exitward
);
6172 *event_string
= smartlist_join_strings(event_parts
, " ", 0, NULL
);
6173 SMARTLIST_FOREACH(event_parts
, char *, cp
, tor_free(cp
));
6174 smartlist_free(event_parts
);
6177 /** A second or more has elapsed: tell any interested control connection
6178 * how many cells have been processed for a given circuit. */
6180 control_event_circuit_cell_stats(void)
6182 cell_stats_t
*cell_stats
;
6184 if (!get_options()->TestingEnableCellStatsEvent
||
6185 !EVENT_IS_INTERESTING(EVENT_CELL_STATS
))
6187 cell_stats
= tor_malloc(sizeof(cell_stats_t
));
6188 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t
*, circ
) {
6189 if (!circ
->testing_cell_stats
)
6191 sum_up_cell_stats_by_command(circ
, cell_stats
);
6192 format_cell_stats(&event_string
, circ
, cell_stats
);
6193 send_control_event(EVENT_CELL_STATS
,
6194 "650 CELL_STATS %s\r\n", event_string
);
6195 tor_free(event_string
);
6197 SMARTLIST_FOREACH_END(circ
);
6198 tor_free(cell_stats
);
6202 /* about 5 minutes worth. */
6203 #define N_BW_EVENTS_TO_CACHE 300
6204 /* Index into cached_bw_events to next write. */
6205 static int next_measurement_idx
= 0;
6206 /* number of entries set in n_measurements */
6207 static int n_measurements
= 0;
6208 static struct cached_bw_event_s
{
6211 } cached_bw_events
[N_BW_EVENTS_TO_CACHE
];
6213 /** A second or more has elapsed: tell any interested control
6214 * connections how much bandwidth we used. */
6216 control_event_bandwidth_used(uint32_t n_read
, uint32_t n_written
)
6218 cached_bw_events
[next_measurement_idx
].n_read
= n_read
;
6219 cached_bw_events
[next_measurement_idx
].n_written
= n_written
;
6220 if (++next_measurement_idx
== N_BW_EVENTS_TO_CACHE
)
6221 next_measurement_idx
= 0;
6222 if (n_measurements
< N_BW_EVENTS_TO_CACHE
)
6225 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED
)) {
6226 send_control_event(EVENT_BANDWIDTH_USED
,
6227 "650 BW %lu %lu\r\n",
6228 (unsigned long)n_read
,
6229 (unsigned long)n_written
);
6236 get_bw_samples(void)
6239 int idx
= (next_measurement_idx
+ N_BW_EVENTS_TO_CACHE
- n_measurements
)
6240 % N_BW_EVENTS_TO_CACHE
;
6241 tor_assert(0 <= idx
&& idx
< N_BW_EVENTS_TO_CACHE
);
6243 smartlist_t
*elements
= smartlist_new();
6245 for (i
= 0; i
< n_measurements
; ++i
) {
6246 tor_assert(0 <= idx
&& idx
< N_BW_EVENTS_TO_CACHE
);
6247 const struct cached_bw_event_s
*bwe
= &cached_bw_events
[idx
];
6249 smartlist_add_asprintf(elements
, "%u,%u",
6250 (unsigned)bwe
->n_read
,
6251 (unsigned)bwe
->n_written
);
6253 idx
= (idx
+ 1) % N_BW_EVENTS_TO_CACHE
;
6256 char *result
= smartlist_join_strings(elements
, " ", 0, NULL
);
6258 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
6259 smartlist_free(elements
);
6264 /** Called when we are sending a log message to the controllers: suspend
6265 * sending further log messages to the controllers until we're done. Used by
6266 * CONN_LOG_PROTECT. */
6268 disable_control_logging(void)
6270 ++disable_log_messages
;
6273 /** We're done sending a log message to the controllers: re-enable controller
6274 * logging. Used by CONN_LOG_PROTECT. */
6276 enable_control_logging(void)
6278 if (--disable_log_messages
< 0)
6282 /** We got a log message: tell any interested control connections. */
6284 control_event_logmsg(int severity
, uint32_t domain
, const char *msg
)
6288 /* Don't even think of trying to add stuff to a buffer from a cpuworker
6289 * thread. (See #25987 for plan to fix.) */
6290 if (! in_main_thread())
6293 if (disable_log_messages
)
6296 if (domain
== LD_BUG
&& EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
) &&
6297 severity
<= LOG_NOTICE
) {
6298 char *esc
= esc_for_log(msg
);
6299 ++disable_log_messages
;
6300 control_event_general_status(severity
, "BUG REASON=%s", esc
);
6301 --disable_log_messages
;
6305 event
= log_severity_to_event(severity
);
6306 if (event
>= 0 && EVENT_IS_INTERESTING(event
)) {
6309 if (strchr(msg
, '\n')) {
6311 b
= tor_strdup(msg
);
6312 for (cp
= b
; *cp
; ++cp
)
6313 if (*cp
== '\r' || *cp
== '\n')
6317 case LOG_DEBUG
: s
= "DEBUG"; break;
6318 case LOG_INFO
: s
= "INFO"; break;
6319 case LOG_NOTICE
: s
= "NOTICE"; break;
6320 case LOG_WARN
: s
= "WARN"; break;
6321 case LOG_ERR
: s
= "ERR"; break;
6322 default: s
= "UnknownLogSeverity"; break;
6324 ++disable_log_messages
;
6325 send_control_event(event
, "650 %s %s\r\n", s
, b
?b
:msg
);
6326 if (severity
== LOG_ERR
) {
6327 /* Force a flush, since we may be about to die horribly */
6328 queued_events_flush_all(1);
6330 --disable_log_messages
;
6336 * Logging callback: called when there is a queued pending log callback.
6339 control_event_logmsg_pending(void)
6341 if (! in_main_thread()) {
6342 /* We can't handle this case yet, since we're using a
6343 * mainloop_event_t to invoke queued_events_flush_all. We ought to
6344 * use a different mechanism instead: see #25987.
6348 tor_assert(flush_queued_events_event
);
6349 mainloop_event_activate(flush_queued_events_event
);
6352 /** Called whenever we receive new router descriptors: tell any
6353 * interested control connections. <b>routers</b> is a list of
6357 control_event_descriptors_changed(smartlist_t
*routers
)
6361 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC
))
6365 smartlist_t
*names
= smartlist_new();
6367 SMARTLIST_FOREACH(routers
, routerinfo_t
*, ri
, {
6368 char *b
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
6369 router_get_verbose_nickname(b
, ri
);
6370 smartlist_add(names
, b
);
6372 ids
= smartlist_join_strings(names
, " ", 0, NULL
);
6373 tor_asprintf(&msg
, "650 NEWDESC %s\r\n", ids
);
6374 send_control_event_string(EVENT_NEW_DESC
, msg
);
6377 SMARTLIST_FOREACH(names
, char *, cp
, tor_free(cp
));
6378 smartlist_free(names
);
6383 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
6384 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
6385 * <b>error</b> is non-NULL, it is an error code describing the failure
6386 * mode of the mapping.
6389 control_event_address_mapped(const char *from
, const char *to
, time_t expires
,
6390 const char *error
, const int cached
)
6392 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP
))
6395 if (expires
< 3 || expires
== TIME_MAX
)
6396 send_control_event(EVENT_ADDRMAP
,
6397 "650 ADDRMAP %s %s NEVER %s%s"
6398 "CACHED=\"%s\"\r\n",
6399 from
, to
, error
?error
:"", error
?" ":"",
6402 char buf
[ISO_TIME_LEN
+1];
6403 char buf2
[ISO_TIME_LEN
+1];
6404 format_local_iso_time(buf
,expires
);
6405 format_iso_time(buf2
,expires
);
6406 send_control_event(EVENT_ADDRMAP
,
6407 "650 ADDRMAP %s %s \"%s\""
6408 " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
6410 error
?error
:"", error
?" ":"",
6411 buf2
, cached
?"YES":"NO");
6417 /** Cached liveness for network liveness events and GETINFO
6420 static int network_is_live
= 0;
6423 get_cached_network_liveness(void)
6425 return network_is_live
;
6429 set_cached_network_liveness(int liveness
)
6431 network_is_live
= liveness
;
6434 /** The network liveness has changed; this is called from circuitstats.c
6435 * whenever we receive a cell, or when timeout expires and we assume the
6436 * network is down. */
6438 control_event_network_liveness_update(int liveness
)
6441 if (get_cached_network_liveness() <= 0) {
6442 /* Update cached liveness */
6443 set_cached_network_liveness(1);
6444 log_debug(LD_CONTROL
, "Sending NETWORK_LIVENESS UP");
6445 send_control_event_string(EVENT_NETWORK_LIVENESS
,
6446 "650 NETWORK_LIVENESS UP\r\n");
6448 /* else was already live, no-op */
6450 if (get_cached_network_liveness() > 0) {
6451 /* Update cached liveness */
6452 set_cached_network_liveness(0);
6453 log_debug(LD_CONTROL
, "Sending NETWORK_LIVENESS DOWN");
6454 send_control_event_string(EVENT_NETWORK_LIVENESS
,
6455 "650 NETWORK_LIVENESS DOWN\r\n");
6457 /* else was already dead, no-op */
6463 /** Helper function for NS-style events. Constructs and sends an event
6464 * of type <b>event</b> with string <b>event_string</b> out of the set of
6465 * networkstatuses <b>statuses</b>. Currently it is used for NS events
6466 * and NEWCONSENSUS events. */
6468 control_event_networkstatus_changed_helper(smartlist_t
*statuses
,
6470 const char *event_string
)
6473 char *s
, *esc
= NULL
;
6474 if (!EVENT_IS_INTERESTING(event
) || !smartlist_len(statuses
))
6477 strs
= smartlist_new();
6478 smartlist_add_strdup(strs
, "650+");
6479 smartlist_add_strdup(strs
, event_string
);
6480 smartlist_add_strdup(strs
, "\r\n");
6481 SMARTLIST_FOREACH(statuses
, const routerstatus_t
*, rs
,
6483 s
= networkstatus_getinfo_helper_single(rs
);
6485 smartlist_add(strs
, s
);
6488 s
= smartlist_join_strings(strs
, "", 0, NULL
);
6489 write_escaped_data(s
, strlen(s
), &esc
);
6490 SMARTLIST_FOREACH(strs
, char *, cp
, tor_free(cp
));
6491 smartlist_free(strs
);
6493 send_control_event_string(event
, esc
);
6494 send_control_event_string(event
,
6501 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
6502 * an NS event to any controller that cares. */
6504 control_event_networkstatus_changed(smartlist_t
*statuses
)
6506 return control_event_networkstatus_changed_helper(statuses
, EVENT_NS
, "NS");
6509 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
6510 * event consisting of an NS-style line for each relay in the consensus. */
6512 control_event_newconsensus(const networkstatus_t
*consensus
)
6514 if (!control_event_is_interesting(EVENT_NEWCONSENSUS
))
6516 return control_event_networkstatus_changed_helper(
6517 consensus
->routerstatus_list
, EVENT_NEWCONSENSUS
, "NEWCONSENSUS");
6520 /** Called when we compute a new circuitbuildtimeout */
6522 control_event_buildtimeout_set(buildtimeout_set_event_t type
,
6525 const char *type_string
= NULL
;
6527 if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET
))
6531 case BUILDTIMEOUT_SET_EVENT_COMPUTED
:
6532 type_string
= "COMPUTED";
6534 case BUILDTIMEOUT_SET_EVENT_RESET
:
6535 type_string
= "RESET";
6537 case BUILDTIMEOUT_SET_EVENT_SUSPENDED
:
6538 type_string
= "SUSPENDED";
6540 case BUILDTIMEOUT_SET_EVENT_DISCARD
:
6541 type_string
= "DISCARD";
6543 case BUILDTIMEOUT_SET_EVENT_RESUME
:
6544 type_string
= "RESUME";
6547 type_string
= "UNKNOWN";
6551 send_control_event(EVENT_BUILDTIMEOUT_SET
,
6552 "650 BUILDTIMEOUT_SET %s %s\r\n",
6558 /** Called when a signal has been processed from signal_callback */
6560 control_event_signal(uintptr_t signal_num
)
6562 const char *signal_string
= NULL
;
6564 if (!control_event_is_interesting(EVENT_GOT_SIGNAL
))
6567 switch (signal_num
) {
6569 signal_string
= "RELOAD";
6572 signal_string
= "DUMP";
6575 signal_string
= "DEBUG";
6578 signal_string
= "NEWNYM";
6580 case SIGCLEARDNSCACHE
:
6581 signal_string
= "CLEARDNSCACHE";
6584 signal_string
= "HEARTBEAT";
6587 log_warn(LD_BUG
, "Unrecognized signal %lu in control_event_signal",
6588 (unsigned long)signal_num
);
6592 send_control_event(EVENT_GOT_SIGNAL
, "650 SIGNAL %s\r\n",
6597 /** Called when a single local_routerstatus_t has changed: Sends an NS event
6598 * to any controller that cares. */
6600 control_event_networkstatus_changed_single(const routerstatus_t
*rs
)
6602 smartlist_t
*statuses
;
6605 if (!EVENT_IS_INTERESTING(EVENT_NS
))
6608 statuses
= smartlist_new();
6609 smartlist_add(statuses
, (void*)rs
);
6610 r
= control_event_networkstatus_changed(statuses
);
6611 smartlist_free(statuses
);
6615 /** Our own router descriptor has changed; tell any controllers that care.
6618 control_event_my_descriptor_changed(void)
6620 send_control_event(EVENT_DESCCHANGED
, "650 DESCCHANGED\r\n");
6624 /** Helper: sends a status event where <b>type</b> is one of
6625 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
6626 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
6627 * string corresponding to <b>args</b>. */
6629 control_event_status(int type
, int severity
, const char *format
, va_list args
)
6631 char *user_buf
= NULL
;
6632 char format_buf
[160];
6633 const char *status
, *sev
;
6636 case EVENT_STATUS_GENERAL
:
6637 status
= "STATUS_GENERAL";
6639 case EVENT_STATUS_CLIENT
:
6640 status
= "STATUS_CLIENT";
6642 case EVENT_STATUS_SERVER
:
6643 status
= "STATUS_SERVER";
6646 log_warn(LD_BUG
, "Unrecognized status type %d", type
);
6660 log_warn(LD_BUG
, "Unrecognized status severity %d", severity
);
6663 if (tor_snprintf(format_buf
, sizeof(format_buf
), "650 %s %s",
6665 log_warn(LD_BUG
, "Format string too long.");
6668 tor_vasprintf(&user_buf
, format
, args
);
6670 send_control_event(type
, "%s %s\r\n", format_buf
, user_buf
);
6675 #define CONTROL_EVENT_STATUS_BODY(event, sev) \
6679 if (!EVENT_IS_INTERESTING(event)) \
6682 va_start(ap, format); \
6683 r = control_event_status((event), (sev), format, ap); \
6687 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
6688 * by formatting the arguments using the printf-style <b>format</b>. */
6690 control_event_general_status(int severity
, const char *format
, ...)
6692 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL
, severity
);
6696 /** Format and send an EVENT_STATUS_GENERAL LOG_ERR event, and flush it to the
6697 * controller(s) immediately. */
6699 control_event_general_error(const char *format
, ...)
6701 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL
, LOG_ERR
);
6702 /* Force a flush, since we may be about to die horribly */
6703 queued_events_flush_all(1);
6707 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
6708 * by formatting the arguments using the printf-style <b>format</b>. */
6710 control_event_client_status(int severity
, const char *format
, ...)
6712 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT
, severity
);
6716 /** Format and send an EVENT_STATUS_CLIENT LOG_ERR event, and flush it to the
6717 * controller(s) immediately. */
6719 control_event_client_error(const char *format
, ...)
6721 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT
, LOG_ERR
);
6722 /* Force a flush, since we may be about to die horribly */
6723 queued_events_flush_all(1);
6727 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
6728 * by formatting the arguments using the printf-style <b>format</b>. */
6730 control_event_server_status(int severity
, const char *format
, ...)
6732 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER
, severity
);
6736 /** Format and send an EVENT_STATUS_SERVER LOG_ERR event, and flush it to the
6737 * controller(s) immediately. */
6739 control_event_server_error(const char *format
, ...)
6741 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER
, LOG_ERR
);
6742 /* Force a flush, since we may be about to die horribly */
6743 queued_events_flush_all(1);
6747 /** Called when the status of an entry guard with the given <b>nickname</b>
6748 * and identity <b>digest</b> has changed to <b>status</b>: tells any
6749 * controllers that care. */
6751 control_event_guard(const char *nickname
, const char *digest
,
6754 char hbuf
[HEX_DIGEST_LEN
+1];
6755 base16_encode(hbuf
, sizeof(hbuf
), digest
, DIGEST_LEN
);
6756 if (!EVENT_IS_INTERESTING(EVENT_GUARD
))
6760 char buf
[MAX_VERBOSE_NICKNAME_LEN
+1];
6761 const node_t
*node
= node_get_by_id(digest
);
6763 node_get_verbose_nickname(node
, buf
);
6765 tor_snprintf(buf
, sizeof(buf
), "$%s~%s", hbuf
, nickname
);
6767 send_control_event(EVENT_GUARD
,
6768 "650 GUARD ENTRY %s %s\r\n", buf
, status
);
6773 /** Called when a configuration option changes. This is generally triggered
6774 * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
6775 * a smartlist_t containing (key, value, ...) pairs in sequence.
6776 * <b>value</b> can be NULL. */
6778 control_event_conf_changed(const smartlist_t
*elements
)
6783 if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED
) ||
6784 smartlist_len(elements
) == 0) {
6787 lines
= smartlist_new();
6788 for (i
= 0; i
< smartlist_len(elements
); i
+= 2) {
6789 char *k
= smartlist_get(elements
, i
);
6790 char *v
= smartlist_get(elements
, i
+1);
6792 smartlist_add_asprintf(lines
, "650-%s", k
);
6794 smartlist_add_asprintf(lines
, "650-%s=%s", k
, v
);
6797 result
= smartlist_join_strings(lines
, "\r\n", 0, NULL
);
6798 send_control_event(EVENT_CONF_CHANGED
,
6799 "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result
);
6801 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
6802 smartlist_free(lines
);
6806 /** Helper: Return a newly allocated string containing a path to the
6807 * file where we store our authentication cookie. */
6809 get_controller_cookie_file_name(void)
6811 const or_options_t
*options
= get_options();
6812 if (options
->CookieAuthFile
&& strlen(options
->CookieAuthFile
)) {
6813 return tor_strdup(options
->CookieAuthFile
);
6815 return get_datadir_fname("control_auth_cookie");
6819 /* Initialize the cookie-based authentication system of the
6820 * ControlPort. If <b>enabled</b> is 0, then disable the cookie
6821 * authentication system. */
6823 init_control_cookie_authentication(int enabled
)
6829 authentication_cookie_is_set
= 0;
6833 fname
= get_controller_cookie_file_name();
6834 retval
= init_cookie_authentication(fname
, "", /* no header */
6835 AUTHENTICATION_COOKIE_LEN
,
6836 get_options()->CookieAuthFileGroupReadable
,
6837 &authentication_cookie
,
6838 &authentication_cookie_is_set
);
6843 /** A copy of the process specifier of Tor's owning controller, or
6844 * NULL if this Tor instance is not currently owned by a process. */
6845 static char *owning_controller_process_spec
= NULL
;
6847 /** A process-termination monitor for Tor's owning controller, or NULL
6848 * if this Tor instance is not currently owned by a process. */
6849 static tor_process_monitor_t
*owning_controller_process_monitor
= NULL
;
6851 /** Process-termination monitor callback for Tor's owning controller
6854 owning_controller_procmon_cb(void *unused
)
6858 lost_owning_controller("process", "vanished");
6861 /** Set <b>process_spec</b> as Tor's owning controller process.
6862 * Exit on failure. */
6864 monitor_owning_controller_process(const char *process_spec
)
6868 tor_assert((owning_controller_process_spec
== NULL
) ==
6869 (owning_controller_process_monitor
== NULL
));
6871 if (owning_controller_process_spec
!= NULL
) {
6872 if ((process_spec
!= NULL
) && !strcmp(process_spec
,
6873 owning_controller_process_spec
)) {
6874 /* Same process -- return now, instead of disposing of and
6875 * recreating the process-termination monitor. */
6879 /* We are currently owned by a process, and we should no longer be
6880 * owned by it. Free the process-termination monitor. */
6881 tor_process_monitor_free(owning_controller_process_monitor
);
6882 owning_controller_process_monitor
= NULL
;
6884 tor_free(owning_controller_process_spec
);
6885 owning_controller_process_spec
= NULL
;
6888 tor_assert((owning_controller_process_spec
== NULL
) &&
6889 (owning_controller_process_monitor
== NULL
));
6891 if (process_spec
== NULL
)
6894 owning_controller_process_spec
= tor_strdup(process_spec
);
6895 owning_controller_process_monitor
=
6896 tor_process_monitor_new(tor_libevent_get_base(),
6897 owning_controller_process_spec
,
6899 owning_controller_procmon_cb
, NULL
,
6902 if (owning_controller_process_monitor
== NULL
) {
6903 log_err(LD_BUG
, "Couldn't create process-termination monitor for "
6904 "owning controller: %s. Exiting.",
6906 owning_controller_process_spec
= NULL
;
6907 tor_shutdown_event_loop_and_exit(1);
6911 /** Convert the name of a bootstrapping phase <b>s</b> into strings
6912 * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
6914 bootstrap_status_to_string(bootstrap_status_t s
, const char **tag
,
6915 const char **summary
)
6918 case BOOTSTRAP_STATUS_UNDEF
:
6920 *summary
= "Undefined";
6922 case BOOTSTRAP_STATUS_STARTING
:
6924 *summary
= "Starting";
6926 case BOOTSTRAP_STATUS_CONN_DIR
:
6928 *summary
= "Connecting to directory server";
6930 case BOOTSTRAP_STATUS_HANDSHAKE
:
6931 *tag
= "status_handshake";
6932 *summary
= "Finishing handshake";
6934 case BOOTSTRAP_STATUS_HANDSHAKE_DIR
:
6935 *tag
= "handshake_dir";
6936 *summary
= "Finishing handshake with directory server";
6938 case BOOTSTRAP_STATUS_ONEHOP_CREATE
:
6939 *tag
= "onehop_create";
6940 *summary
= "Establishing an encrypted directory connection";
6942 case BOOTSTRAP_STATUS_REQUESTING_STATUS
:
6943 *tag
= "requesting_status";
6944 *summary
= "Asking for networkstatus consensus";
6946 case BOOTSTRAP_STATUS_LOADING_STATUS
:
6947 *tag
= "loading_status";
6948 *summary
= "Loading networkstatus consensus";
6950 case BOOTSTRAP_STATUS_LOADING_KEYS
:
6951 *tag
= "loading_keys";
6952 *summary
= "Loading authority key certs";
6954 case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS
:
6955 *tag
= "requesting_descriptors";
6956 /* XXXX this appears to incorrectly report internal on most loads */
6957 *summary
= router_have_consensus_path() == CONSENSUS_PATH_INTERNAL
?
6958 "Asking for relay descriptors for internal paths" :
6959 "Asking for relay descriptors";
6961 /* If we're sure there are no exits in the consensus,
6962 * inform the controller by adding "internal"
6963 * to the status summaries.
6964 * (We only check this while loading descriptors,
6965 * so we may not know in the earlier stages.)
6966 * But if there are exits, we can't be sure whether
6967 * we're creating internal or exit paths/circuits.
6968 * XXXX Or should be use different tags or statuses
6969 * for internal and exit/all? */
6970 case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS
:
6971 *tag
= "loading_descriptors";
6972 *summary
= router_have_consensus_path() == CONSENSUS_PATH_INTERNAL
?
6973 "Loading relay descriptors for internal paths" :
6974 "Loading relay descriptors";
6976 case BOOTSTRAP_STATUS_CONN_OR
:
6978 *summary
= router_have_consensus_path() == CONSENSUS_PATH_INTERNAL
?
6979 "Connecting to the Tor network internally" :
6980 "Connecting to the Tor network";
6982 case BOOTSTRAP_STATUS_HANDSHAKE_OR
:
6983 *tag
= "handshake_or";
6984 *summary
= router_have_consensus_path() == CONSENSUS_PATH_INTERNAL
?
6985 "Finishing handshake with first hop of internal circuit" :
6986 "Finishing handshake with first hop";
6988 case BOOTSTRAP_STATUS_CIRCUIT_CREATE
:
6989 *tag
= "circuit_create";
6990 *summary
= router_have_consensus_path() == CONSENSUS_PATH_INTERNAL
?
6991 "Establishing an internal Tor circuit" :
6992 "Establishing a Tor circuit";
6994 case BOOTSTRAP_STATUS_DONE
:
6999 // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
7000 *tag
= *summary
= "unknown";
7006 /** What percentage through the bootstrap process are we? We remember
7007 * this so we can avoid sending redundant bootstrap status events, and
7008 * so we can guess context for the bootstrap messages which are
7009 * ambiguous. It starts at 'undef', but gets set to 'starting' while
7010 * Tor initializes. */
7011 static int bootstrap_percent
= BOOTSTRAP_STATUS_UNDEF
;
7013 /** As bootstrap_percent, but holds the bootstrapping level at which we last
7014 * logged a NOTICE-level message. We use this, plus BOOTSTRAP_PCT_INCREMENT,
7015 * to avoid flooding the log with a new message every time we get a few more
7016 * microdescriptors */
7017 static int notice_bootstrap_percent
= 0;
7019 /** How many problems have we had getting to the next bootstrapping phase?
7020 * These include failure to establish a connection to a Tor relay,
7021 * failures to finish the TLS handshake, failures to validate the
7022 * consensus document, etc. */
7023 static int bootstrap_problems
= 0;
7025 /** We only tell the controller once we've hit a threshold of problems
7026 * for the current phase. */
7027 #define BOOTSTRAP_PROBLEM_THRESHOLD 10
7029 /** When our bootstrapping progress level changes, but our bootstrapping
7030 * status has not advanced, we only log at NOTICE when we have made at least
7031 * this much progress.
7033 #define BOOTSTRAP_PCT_INCREMENT 5
7035 /** Called when Tor has made progress at bootstrapping its directory
7036 * information and initial circuits.
7038 * <b>status</b> is the new status, that is, what task we will be doing
7039 * next. <b>progress</b> is zero if we just started this task, else it
7040 * represents progress on the task.
7042 * Return true if we logged a message at level NOTICE, and false otherwise.
7045 control_event_bootstrap(bootstrap_status_t status
, int progress
)
7047 const char *tag
, *summary
;
7048 char buf
[BOOTSTRAP_MSG_LEN
];
7050 if (bootstrap_percent
== BOOTSTRAP_STATUS_DONE
)
7051 return 0; /* already bootstrapped; nothing to be done here. */
7053 /* special case for handshaking status, since our TLS handshaking code
7054 * can't distinguish what the connection is going to be for. */
7055 if (status
== BOOTSTRAP_STATUS_HANDSHAKE
) {
7056 if (bootstrap_percent
< BOOTSTRAP_STATUS_CONN_OR
) {
7057 status
= BOOTSTRAP_STATUS_HANDSHAKE_DIR
;
7059 status
= BOOTSTRAP_STATUS_HANDSHAKE_OR
;
7063 if (status
> bootstrap_percent
||
7064 (progress
&& progress
> bootstrap_percent
)) {
7065 int loglevel
= LOG_NOTICE
;
7066 bootstrap_status_to_string(status
, &tag
, &summary
);
7068 if (status
<= bootstrap_percent
&&
7069 (progress
< notice_bootstrap_percent
+ BOOTSTRAP_PCT_INCREMENT
)) {
7070 /* We log the message at info if the status hasn't advanced, and if less
7071 * than BOOTSTRAP_PCT_INCREMENT progress has been made.
7073 loglevel
= LOG_INFO
;
7076 tor_log(loglevel
, LD_CONTROL
,
7077 "Bootstrapped %d%%: %s", progress
? progress
: status
, summary
);
7078 tor_snprintf(buf
, sizeof(buf
),
7079 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
7080 progress
? progress
: status
, tag
, summary
);
7081 tor_snprintf(last_sent_bootstrap_message
,
7082 sizeof(last_sent_bootstrap_message
),
7084 control_event_client_status(LOG_NOTICE
, "%s", buf
);
7085 if (status
> bootstrap_percent
) {
7086 bootstrap_percent
= status
; /* new milestone reached */
7088 if (progress
> bootstrap_percent
) {
7089 /* incremental progress within a milestone */
7090 bootstrap_percent
= progress
;
7091 bootstrap_problems
= 0; /* Progress! Reset our problem counter. */
7093 if (loglevel
== LOG_NOTICE
&&
7094 bootstrap_percent
> notice_bootstrap_percent
) {
7095 /* Remember that we gave a notice at this level. */
7096 notice_bootstrap_percent
= bootstrap_percent
;
7098 return loglevel
== LOG_NOTICE
;
7104 /** Called when Tor has failed to make bootstrapping progress in a way
7105 * that indicates a problem. <b>warn</b> gives a human-readable hint
7106 * as to why, and <b>reason</b> provides a controller-facing short
7107 * tag. <b>conn</b> is the connection that caused this problem and
7108 * can be NULL if a connection cannot be easily identified.
7111 control_event_bootstrap_problem(const char *warn
, const char *reason
,
7112 const connection_t
*conn
, int dowarn
)
7114 int status
= bootstrap_percent
;
7115 const char *tag
= "", *summary
= "";
7116 char buf
[BOOTSTRAP_MSG_LEN
];
7117 const char *recommendation
= "ignore";
7119 char *or_id
= NULL
, *hostaddr
= NULL
;
7120 or_connection_t
*or_conn
= NULL
;
7122 /* bootstrap_percent must not be in "undefined" state here. */
7123 tor_assert(status
>= 0);
7125 if (bootstrap_percent
== 100)
7126 return; /* already bootstrapped; nothing to be done here. */
7128 bootstrap_problems
++;
7130 if (bootstrap_problems
>= BOOTSTRAP_PROBLEM_THRESHOLD
)
7133 /* Don't warn about our bootstrapping status if we are hibernating or
7135 if (we_are_hibernating())
7138 while (status
>=0 && bootstrap_status_to_string(status
, &tag
, &summary
) < 0)
7139 status
--; /* find a recognized status string based on current progress */
7140 status
= bootstrap_percent
; /* set status back to the actual number */
7142 severity
= dowarn
? LOG_WARN
: LOG_INFO
;
7145 recommendation
= "warn";
7147 if (conn
&& conn
->type
== CONN_TYPE_OR
) {
7148 /* XXX TO_OR_CONN can't deal with const */
7149 or_conn
= TO_OR_CONN((connection_t
*)conn
);
7150 or_id
= tor_strdup(hex_str(or_conn
->identity_digest
, DIGEST_LEN
));
7152 or_id
= tor_strdup("?");
7156 tor_asprintf(&hostaddr
, "%s:%d", conn
->address
, (int)conn
->port
);
7158 hostaddr
= tor_strdup("?");
7161 LD_CONTROL
, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
7162 "count %d; recommendation %s; host %s at %s)",
7163 status
, summary
, warn
, reason
,
7164 bootstrap_problems
, recommendation
,
7167 connection_or_report_broken_states(severity
, LD_HANDSHAKE
);
7169 tor_snprintf(buf
, sizeof(buf
),
7170 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
7171 "COUNT=%d RECOMMENDATION=%s HOSTID=\"%s\" HOSTADDR=\"%s\"",
7172 bootstrap_percent
, tag
, summary
, warn
, reason
, bootstrap_problems
,
7176 tor_snprintf(last_sent_bootstrap_message
,
7177 sizeof(last_sent_bootstrap_message
),
7179 control_event_client_status(LOG_WARN
, "%s", buf
);
7185 /** Called when Tor has failed to make bootstrapping progress in a way
7186 * that indicates a problem. <b>warn</b> gives a hint as to why, and
7187 * <b>reason</b> provides an "or_conn_end_reason" tag. <b>or_conn</b>
7188 * is the connection that caused this problem.
7191 control_event_bootstrap_prob_or
, (const char *warn
, int reason
,
7192 or_connection_t
*or_conn
))
7196 if (or_conn
->have_noted_bootstrap_problem
)
7199 or_conn
->have_noted_bootstrap_problem
= 1;
7201 if (reason
== END_OR_CONN_REASON_NO_ROUTE
)
7204 /* If we are using bridges and all our OR connections are now
7205 closed, it means that we totally failed to connect to our
7206 bridges. Throw a warning. */
7207 if (get_options()->UseBridges
&& !any_other_active_or_conns(or_conn
))
7210 control_event_bootstrap_problem(warn
,
7211 orconn_end_reason_to_control_string(reason
),
7212 TO_CONN(or_conn
), dowarn
);
7215 /** We just generated a new summary of which countries we've seen clients
7216 * from recently. Send a copy to the controller in case it wants to
7217 * display it for the user. */
7219 control_event_clients_seen(const char *controller_str
)
7221 send_control_event(EVENT_CLIENTS_SEEN
,
7222 "650 CLIENTS_SEEN %s\r\n", controller_str
);
7225 /** A new pluggable transport called <b>transport_name</b> was
7226 * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
7227 * "server" or "client" depending on the mode of the pluggable
7229 * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
7232 control_event_transport_launched(const char *mode
, const char *transport_name
,
7233 tor_addr_t
*addr
, uint16_t port
)
7235 send_control_event(EVENT_TRANSPORT_LAUNCHED
,
7236 "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
7237 mode
, transport_name
, fmt_addr(addr
), port
);
7240 /** Convert rendezvous auth type to string for HS_DESC control events
7243 rend_auth_type_to_string(rend_auth_type_t auth_type
)
7247 switch (auth_type
) {
7251 case REND_BASIC_AUTH
:
7254 case REND_STEALTH_AUTH
:
7255 str
= "STEALTH_AUTH";
7264 /** Return a longname the node whose identity is <b>id_digest</b>. If
7265 * node_get_by_id() returns NULL, base 16 encoding of <b>id_digest</b> is
7268 * This function is not thread-safe. Each call to this function invalidates
7269 * previous values returned by this function.
7271 MOCK_IMPL(const char *,
7272 node_describe_longname_by_id
,(const char *id_digest
))
7274 static char longname
[MAX_VERBOSE_NICKNAME_LEN
+1];
7275 node_get_verbose_nickname_by_id(id_digest
, longname
);
7279 /** Return either the onion address if the given pointer is a non empty
7280 * string else the unknown string. */
7282 rend_hsaddress_str_or_unknown(const char *onion_address
)
7284 static const char *str_unknown
= "UNKNOWN";
7285 const char *str_ret
= str_unknown
;
7287 /* No valid pointer, unknown it is. */
7288 if (!onion_address
) {
7291 /* Empty onion address thus we don't know, unknown it is. */
7292 if (onion_address
[0] == '\0') {
7295 /* All checks are good so return the given onion address. */
7296 str_ret
= onion_address
;
7302 /** send HS_DESC requested event.
7304 * <b>rend_query</b> is used to fetch requested onion address and auth type.
7305 * <b>hs_dir</b> is the description of contacting hs directory.
7306 * <b>desc_id_base32</b> is the ID of requested hs descriptor.
7307 * <b>hsdir_index</b> is the HSDir fetch index value for v3, an hex string.
7310 control_event_hs_descriptor_requested(const char *onion_address
,
7311 rend_auth_type_t auth_type
,
7312 const char *id_digest
,
7313 const char *desc_id
,
7314 const char *hsdir_index
)
7316 char *hsdir_index_field
= NULL
;
7318 if (BUG(!id_digest
|| !desc_id
)) {
7323 tor_asprintf(&hsdir_index_field
, " HSDIR_INDEX=%s", hsdir_index
);
7326 send_control_event(EVENT_HS_DESC
,
7327 "650 HS_DESC REQUESTED %s %s %s %s%s\r\n",
7328 rend_hsaddress_str_or_unknown(onion_address
),
7329 rend_auth_type_to_string(auth_type
),
7330 node_describe_longname_by_id(id_digest
),
7332 hsdir_index_field
? hsdir_index_field
: "");
7333 tor_free(hsdir_index_field
);
7336 /** For an HS descriptor query <b>rend_data</b>, using the
7337 * <b>onion_address</b> and HSDir fingerprint <b>hsdir_fp</b>, find out
7338 * which descriptor ID in the query is the right one.
7340 * Return a pointer of the binary descriptor ID found in the query's object
7341 * or NULL if not found. */
7343 get_desc_id_from_query(const rend_data_t
*rend_data
, const char *hsdir_fp
)
7346 const char *desc_id
= NULL
;
7347 const rend_data_v2_t
*rend_data_v2
= TO_REND_DATA_V2(rend_data
);
7349 /* Possible if the fetch was done using a descriptor ID. This means that
7350 * the HSFETCH command was used. */
7351 if (!tor_digest_is_zero(rend_data_v2
->desc_id_fetch
)) {
7352 desc_id
= rend_data_v2
->desc_id_fetch
;
7356 /* Without a directory fingerprint at this stage, we can't do much. */
7357 if (hsdir_fp
== NULL
) {
7361 /* OK, we have an onion address so now let's find which descriptor ID
7362 * is the one associated with the HSDir fingerprint. */
7363 for (replica
= 0; replica
< REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS
;
7365 const char *digest
= rend_data_get_desc_id(rend_data
, replica
, NULL
);
7367 SMARTLIST_FOREACH_BEGIN(rend_data
->hsdirs_fp
, char *, fingerprint
) {
7368 if (tor_memcmp(fingerprint
, hsdir_fp
, DIGEST_LEN
) == 0) {
7369 /* Found it! This descriptor ID is the right one. */
7373 } SMARTLIST_FOREACH_END(fingerprint
);
7380 /** send HS_DESC CREATED event when a local service generates a descriptor.
7382 * <b>onion_address</b> is service address.
7383 * <b>desc_id</b> is the descriptor ID.
7384 * <b>replica</b> is the the descriptor replica number. If it is negative, it
7388 control_event_hs_descriptor_created(const char *onion_address
,
7389 const char *desc_id
,
7392 char *replica_field
= NULL
;
7394 if (BUG(!onion_address
|| !desc_id
)) {
7399 tor_asprintf(&replica_field
, " REPLICA=%d", replica
);
7402 send_control_event(EVENT_HS_DESC
,
7403 "650 HS_DESC CREATED %s UNKNOWN UNKNOWN %s%s\r\n",
7404 onion_address
, desc_id
,
7405 replica_field
? replica_field
: "");
7406 tor_free(replica_field
);
7409 /** send HS_DESC upload event.
7411 * <b>onion_address</b> is service address.
7412 * <b>hs_dir</b> is the description of contacting hs directory.
7413 * <b>desc_id</b> is the ID of requested hs descriptor.
7416 control_event_hs_descriptor_upload(const char *onion_address
,
7417 const char *id_digest
,
7418 const char *desc_id
,
7419 const char *hsdir_index
)
7421 char *hsdir_index_field
= NULL
;
7423 if (BUG(!onion_address
|| !id_digest
|| !desc_id
)) {
7428 tor_asprintf(&hsdir_index_field
, " HSDIR_INDEX=%s", hsdir_index
);
7431 send_control_event(EVENT_HS_DESC
,
7432 "650 HS_DESC UPLOAD %s UNKNOWN %s %s%s\r\n",
7434 node_describe_longname_by_id(id_digest
),
7436 hsdir_index_field
? hsdir_index_field
: "");
7437 tor_free(hsdir_index_field
);
7440 /** send HS_DESC event after got response from hs directory.
7442 * NOTE: this is an internal function used by following functions:
7443 * control_event_hsv2_descriptor_received
7444 * control_event_hsv2_descriptor_failed
7445 * control_event_hsv3_descriptor_failed
7447 * So do not call this function directly.
7450 event_hs_descriptor_receive_end(const char *action
,
7451 const char *onion_address
,
7452 const char *desc_id
,
7453 rend_auth_type_t auth_type
,
7454 const char *hsdir_id_digest
,
7457 char *reason_field
= NULL
;
7459 if (BUG(!action
|| !onion_address
)) {
7464 tor_asprintf(&reason_field
, " REASON=%s", reason
);
7467 send_control_event(EVENT_HS_DESC
,
7468 "650 HS_DESC %s %s %s %s%s%s\r\n",
7470 rend_hsaddress_str_or_unknown(onion_address
),
7471 rend_auth_type_to_string(auth_type
),
7473 node_describe_longname_by_id(hsdir_id_digest
) :
7475 desc_id
? desc_id
: "",
7476 reason_field
? reason_field
: "");
7478 tor_free(reason_field
);
7481 /** send HS_DESC event after got response from hs directory.
7483 * NOTE: this is an internal function used by following functions:
7484 * control_event_hs_descriptor_uploaded
7485 * control_event_hs_descriptor_upload_failed
7487 * So do not call this function directly.
7490 control_event_hs_descriptor_upload_end(const char *action
,
7491 const char *onion_address
,
7492 const char *id_digest
,
7495 char *reason_field
= NULL
;
7497 if (BUG(!action
|| !id_digest
)) {
7502 tor_asprintf(&reason_field
, " REASON=%s", reason
);
7505 send_control_event(EVENT_HS_DESC
,
7506 "650 HS_DESC %s %s UNKNOWN %s%s\r\n",
7508 rend_hsaddress_str_or_unknown(onion_address
),
7509 node_describe_longname_by_id(id_digest
),
7510 reason_field
? reason_field
: "");
7512 tor_free(reason_field
);
7515 /** send HS_DESC RECEIVED event
7517 * called when we successfully received a hidden service descriptor.
7520 control_event_hsv2_descriptor_received(const char *onion_address
,
7521 const rend_data_t
*rend_data
,
7522 const char *hsdir_id_digest
)
7524 char *desc_id_field
= NULL
;
7525 const char *desc_id
;
7527 if (BUG(!rend_data
|| !hsdir_id_digest
|| !onion_address
)) {
7531 desc_id
= get_desc_id_from_query(rend_data
, hsdir_id_digest
);
7532 if (desc_id
!= NULL
) {
7533 char desc_id_base32
[REND_DESC_ID_V2_LEN_BASE32
+ 1];
7534 /* Set the descriptor ID digest to base32 so we can send it. */
7535 base32_encode(desc_id_base32
, sizeof(desc_id_base32
), desc_id
,
7537 /* Extra whitespace is needed before the value. */
7538 tor_asprintf(&desc_id_field
, " %s", desc_id_base32
);
7541 event_hs_descriptor_receive_end("RECEIVED", onion_address
, desc_id_field
,
7542 TO_REND_DATA_V2(rend_data
)->auth_type
,
7543 hsdir_id_digest
, NULL
);
7544 tor_free(desc_id_field
);
7547 /* Send HS_DESC RECEIVED event
7549 * Called when we successfully received a hidden service descriptor. */
7551 control_event_hsv3_descriptor_received(const char *onion_address
,
7552 const char *desc_id
,
7553 const char *hsdir_id_digest
)
7555 char *desc_id_field
= NULL
;
7557 if (BUG(!onion_address
|| !desc_id
|| !hsdir_id_digest
)) {
7561 /* Because DescriptorID is an optional positional value, we need to add a
7562 * whitespace before in order to not be next to the HsDir value. */
7563 tor_asprintf(&desc_id_field
, " %s", desc_id
);
7565 event_hs_descriptor_receive_end("RECEIVED", onion_address
, desc_id_field
,
7566 REND_NO_AUTH
, hsdir_id_digest
, NULL
);
7567 tor_free(desc_id_field
);
7570 /** send HS_DESC UPLOADED event
7572 * called when we successfully uploaded a hidden service descriptor.
7575 control_event_hs_descriptor_uploaded(const char *id_digest
,
7576 const char *onion_address
)
7578 if (BUG(!id_digest
)) {
7582 control_event_hs_descriptor_upload_end("UPLOADED", onion_address
,
7586 /** Send HS_DESC event to inform controller that query <b>rend_data</b>
7587 * failed to retrieve hidden service descriptor from directory identified by
7588 * <b>id_digest</b>. If NULL, "UNKNOWN" is used. If <b>reason</b> is not NULL,
7589 * add it to REASON= field.
7592 control_event_hsv2_descriptor_failed(const rend_data_t
*rend_data
,
7593 const char *hsdir_id_digest
,
7596 char *desc_id_field
= NULL
;
7597 const char *desc_id
;
7599 if (BUG(!rend_data
)) {
7603 desc_id
= get_desc_id_from_query(rend_data
, hsdir_id_digest
);
7604 if (desc_id
!= NULL
) {
7605 char desc_id_base32
[REND_DESC_ID_V2_LEN_BASE32
+ 1];
7606 /* Set the descriptor ID digest to base32 so we can send it. */
7607 base32_encode(desc_id_base32
, sizeof(desc_id_base32
), desc_id
,
7609 /* Extra whitespace is needed before the value. */
7610 tor_asprintf(&desc_id_field
, " %s", desc_id_base32
);
7613 event_hs_descriptor_receive_end("FAILED", rend_data_get_address(rend_data
),
7615 TO_REND_DATA_V2(rend_data
)->auth_type
,
7616 hsdir_id_digest
, reason
);
7617 tor_free(desc_id_field
);
7620 /** Send HS_DESC event to inform controller that the query to
7621 * <b>onion_address</b> failed to retrieve hidden service descriptor
7622 * <b>desc_id</b> from directory identified by <b>hsdir_id_digest</b>. If
7623 * NULL, "UNKNOWN" is used. If <b>reason</b> is not NULL, add it to REASON=
7626 control_event_hsv3_descriptor_failed(const char *onion_address
,
7627 const char *desc_id
,
7628 const char *hsdir_id_digest
,
7631 char *desc_id_field
= NULL
;
7633 if (BUG(!onion_address
|| !desc_id
|| !reason
)) {
7637 /* Because DescriptorID is an optional positional value, we need to add a
7638 * whitespace before in order to not be next to the HsDir value. */
7639 tor_asprintf(&desc_id_field
, " %s", desc_id
);
7641 event_hs_descriptor_receive_end("FAILED", onion_address
, desc_id_field
,
7642 REND_NO_AUTH
, hsdir_id_digest
, reason
);
7643 tor_free(desc_id_field
);
7646 /** Send HS_DESC_CONTENT event after completion of a successful fetch from hs
7647 * directory. If <b>hsdir_id_digest</b> is NULL, it is replaced by "UNKNOWN".
7648 * If <b>content</b> is NULL, it is replaced by an empty string. The
7649 * <b>onion_address</b> or <b>desc_id</b> set to NULL will no trigger the
7652 control_event_hs_descriptor_content(const char *onion_address
,
7653 const char *desc_id
,
7654 const char *hsdir_id_digest
,
7655 const char *content
)
7657 static const char *event_name
= "HS_DESC_CONTENT";
7658 char *esc_content
= NULL
;
7660 if (!onion_address
|| !desc_id
) {
7661 log_warn(LD_BUG
, "Called with onion_address==%p, desc_id==%p, ",
7662 onion_address
, desc_id
);
7666 if (content
== NULL
) {
7667 /* Point it to empty content so it can still be escaped. */
7670 write_escaped_data(content
, strlen(content
), &esc_content
);
7672 send_control_event(EVENT_HS_DESC_CONTENT
,
7673 "650+%s %s %s %s\r\n%s650 OK\r\n",
7675 rend_hsaddress_str_or_unknown(onion_address
),
7678 node_describe_longname_by_id(hsdir_id_digest
) :
7681 tor_free(esc_content
);
7684 /** Send HS_DESC event to inform controller upload of hidden service
7685 * descriptor identified by <b>id_digest</b> failed. If <b>reason</b>
7686 * is not NULL, add it to REASON= field.
7689 control_event_hs_descriptor_upload_failed(const char *id_digest
,
7690 const char *onion_address
,
7693 if (BUG(!id_digest
)) {
7696 control_event_hs_descriptor_upload_end("FAILED", onion_address
,
7700 /** Free any leftover allocated memory of the control.c subsystem. */
7702 control_free_all(void)
7704 smartlist_t
*queued_events
= NULL
;
7706 stats_prev_n_read
= stats_prev_n_written
= 0;
7708 if (authentication_cookie
) /* Free the auth cookie */
7709 tor_free(authentication_cookie
);
7710 if (detached_onion_services
) { /* Free the detached onion services */
7711 SMARTLIST_FOREACH(detached_onion_services
, char *, cp
, tor_free(cp
));
7712 smartlist_free(detached_onion_services
);
7715 if (queued_control_events_lock
) {
7716 tor_mutex_acquire(queued_control_events_lock
);
7717 flush_queued_event_pending
= 0;
7718 queued_events
= queued_control_events
;
7719 queued_control_events
= NULL
;
7720 tor_mutex_release(queued_control_events_lock
);
7722 if (queued_events
) {
7723 SMARTLIST_FOREACH(queued_events
, queued_event_t
*, ev
,
7724 queued_event_free(ev
));
7725 smartlist_free(queued_events
);
7727 if (flush_queued_events_event
) {
7728 mainloop_event_free(flush_queued_events_event
);
7729 flush_queued_events_event
= NULL
;
7731 bootstrap_percent
= BOOTSTRAP_STATUS_UNDEF
;
7732 notice_bootstrap_percent
= 0;
7733 bootstrap_problems
= 0;
7734 authentication_cookie_is_set
= 0;
7735 global_event_mask
= 0;
7736 disable_log_messages
= 0;
7737 memset(last_sent_bootstrap_message
, 0, sizeof(last_sent_bootstrap_message
));
7740 #ifdef TOR_UNIT_TESTS
7741 /* For testing: change the value of global_event_mask */
7743 control_testing_set_global_event_mask(uint64_t mask
)
7745 global_event_mask
= mask
;
7747 #endif /* defined(TOR_UNIT_TESTS) */