2 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2018, 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
38 #include "core/or/or.h"
39 #include "app/config/config.h"
40 #include "app/config/confparse.h"
41 #include "app/main/main.h"
42 #include "core/mainloop/connection.h"
43 #include "core/mainloop/mainloop.h"
44 #include "core/or/channel.h"
45 #include "core/or/channeltls.h"
46 #include "core/or/circuitbuild.h"
47 #include "core/or/circuitlist.h"
48 #include "core/or/circuitstats.h"
49 #include "core/or/circuituse.h"
50 #include "core/or/command.h"
51 #include "core/or/connection_edge.h"
52 #include "core/or/connection_or.h"
53 #include "core/or/policies.h"
54 #include "core/or/reasons.h"
55 #include "core/proto/proto_control0.h"
56 #include "core/proto/proto_http.h"
57 #include "feature/client/addressmap.h"
58 #include "feature/client/bridges.h"
59 #include "feature/client/dnsserv.h"
60 #include "feature/client/entrynodes.h"
61 #include "feature/control/control.h"
62 #include "feature/control/fmt_serverstatus.h"
63 #include "feature/dircache/dirserv.h"
64 #include "feature/dirclient/dirclient.h"
65 #include "feature/dirclient/dlstatus.h"
66 #include "feature/dircommon/directory.h"
67 #include "feature/hibernate/hibernate.h"
68 #include "feature/hs/hs_cache.h"
69 #include "feature/hs/hs_common.h"
70 #include "feature/hs/hs_control.h"
71 #include "feature/hs_common/shared_random_client.h"
72 #include "feature/nodelist/authcert.h"
73 #include "feature/nodelist/dirlist.h"
74 #include "feature/nodelist/microdesc.h"
75 #include "feature/nodelist/networkstatus.h"
76 #include "feature/nodelist/nodelist.h"
77 #include "feature/nodelist/routerinfo.h"
78 #include "feature/nodelist/routerlist.h"
79 #include "feature/nodelist/routerparse.h"
80 #include "feature/relay/router.h"
81 #include "feature/relay/routermode.h"
82 #include "feature/relay/selftest.h"
83 #include "feature/rend/rendclient.h"
84 #include "feature/rend/rendcommon.h"
85 #include "feature/rend/rendservice.h"
86 #include "feature/stats/geoip.h"
87 #include "feature/stats/predict_ports.h"
88 #include "lib/container/buffers.h"
89 #include "lib/crypt_ops/crypto_rand.h"
90 #include "lib/crypt_ops/crypto_util.h"
91 #include "lib/encoding/confline.h"
92 #include "lib/evloop/compat_libevent.h"
94 #include "feature/dircache/cached_dir_st.h"
95 #include "feature/control/control_connection_st.h"
96 #include "core/or/cpath_build_state_st.h"
97 #include "core/or/entry_connection_st.h"
98 #include "feature/nodelist/extrainfo_st.h"
99 #include "feature/nodelist/networkstatus_st.h"
100 #include "feature/nodelist/node_st.h"
101 #include "core/or/or_connection_st.h"
102 #include "core/or/or_circuit_st.h"
103 #include "core/or/origin_circuit_st.h"
104 #include "feature/nodelist/microdesc_st.h"
105 #include "feature/rend/rend_authorized_client_st.h"
106 #include "feature/rend/rend_encoded_v2_service_descriptor_st.h"
107 #include "feature/rend/rend_service_descriptor_st.h"
108 #include "feature/nodelist/routerinfo_st.h"
109 #include "feature/nodelist/routerlist_st.h"
110 #include "core/or/socks_request_st.h"
115 #ifdef HAVE_SYS_STAT_H
116 #include <sys/stat.h>
121 #include <sys/resource.h>
124 #include "lib/crypt_ops/crypto_s2k.h"
125 #include "lib/evloop/procmon.h"
126 #include "lib/evloop/compat_libevent.h"
128 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
129 * finished authentication and is accepting commands. */
130 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
132 /** Bitfield: The bit 1<<e is set if <b>any</b> open control
133 * connection is interested in events of type <b>e</b>. We use this
134 * so that we can decide to skip generating event messages that nobody
135 * has interest in without having to walk over the global connection
138 typedef uint64_t event_mask_t
;
140 /** An event mask of all the events that any controller is interested in
142 static event_mask_t global_event_mask
= 0;
144 /** True iff we have disabled log messages from being sent to the controller */
145 static int disable_log_messages
= 0;
147 /** Macro: true if any control connection is interested in events of type
149 #define EVENT_IS_INTERESTING(e) \
150 (!! (global_event_mask & EVENT_MASK_(e)))
152 /** Macro: true if any event from the bitfield 'e' is interesting. */
153 #define ANY_EVENT_IS_INTERESTING(e) \
154 (!! (global_event_mask & (e)))
156 /** If we're using cookie-type authentication, how long should our cookies be?
158 #define AUTHENTICATION_COOKIE_LEN 32
160 /** If true, we've set authentication_cookie to a secret code and
161 * stored it to disk. */
162 static int authentication_cookie_is_set
= 0;
163 /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
164 * and which we're using to authenticate controllers. (If the controller can
165 * read it off disk, it has permission to connect.) */
166 static uint8_t *authentication_cookie
= NULL
;
168 #define SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT \
169 "Tor safe cookie authentication server-to-controller hash"
170 #define SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT \
171 "Tor safe cookie authentication controller-to-server hash"
172 #define SAFECOOKIE_SERVER_NONCE_LEN DIGEST256_LEN
174 /** The list of onion services that have been added via ADD_ONION that do not
175 * belong to any particular control connection.
177 static smartlist_t
*detached_onion_services
= NULL
;
179 /** A sufficiently large size to record the last bootstrap phase string. */
180 #define BOOTSTRAP_MSG_LEN 1024
182 /** What was the last bootstrap phase message we sent? We keep track
183 * of this so we can respond to getinfo status/bootstrap-phase queries. */
184 static char last_sent_bootstrap_message
[BOOTSTRAP_MSG_LEN
];
186 static void connection_printf_to_buf(control_connection_t
*conn
,
187 const char *format
, ...)
189 static void send_control_event_impl(uint16_t event
,
190 const char *format
, va_list ap
)
192 static int control_event_status(int type
, int severity
, const char *format
,
196 static void send_control_done(control_connection_t
*conn
);
197 static void send_control_event(uint16_t event
,
198 const char *format
, ...)
200 static int handle_control_setconf(control_connection_t
*conn
, uint32_t len
,
202 static int handle_control_resetconf(control_connection_t
*conn
, uint32_t len
,
204 static int handle_control_getconf(control_connection_t
*conn
, uint32_t len
,
206 static int handle_control_loadconf(control_connection_t
*conn
, uint32_t len
,
208 static int handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
210 static int handle_control_authenticate(control_connection_t
*conn
,
213 static int handle_control_signal(control_connection_t
*conn
, uint32_t len
,
215 static int handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
217 static char *list_getinfo_options(void);
218 static int handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
220 static int handle_control_extendcircuit(control_connection_t
*conn
,
223 static int handle_control_setcircuitpurpose(control_connection_t
*conn
,
224 uint32_t len
, const char *body
);
225 static int handle_control_attachstream(control_connection_t
*conn
,
228 static int handle_control_postdescriptor(control_connection_t
*conn
,
231 static int handle_control_redirectstream(control_connection_t
*conn
,
234 static int handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
236 static int handle_control_closecircuit(control_connection_t
*conn
,
239 static int handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
241 static int handle_control_usefeature(control_connection_t
*conn
,
244 static int handle_control_hsfetch(control_connection_t
*conn
, uint32_t len
,
246 static int handle_control_hspost(control_connection_t
*conn
, uint32_t len
,
248 static int handle_control_add_onion(control_connection_t
*conn
, uint32_t len
,
250 static int handle_control_del_onion(control_connection_t
*conn
, uint32_t len
,
252 static int write_stream_target_to_buf(entry_connection_t
*conn
, char *buf
,
254 static void orconn_target_get_name(char *buf
, size_t len
,
255 or_connection_t
*conn
);
257 static int get_cached_network_liveness(void);
258 static void set_cached_network_liveness(int liveness
);
260 static void flush_queued_events_cb(mainloop_event_t
*event
, void *arg
);
262 static char * download_status_to_string(const download_status_t
*dl
);
263 static void control_get_bytes_rw_last_sec(uint64_t *r
, uint64_t *w
);
265 /** Convert a connection_t* to an control_connection_t*; assert if the cast is
267 control_connection_t
*
268 TO_CONTROL_CONN(connection_t
*c
)
270 tor_assert(c
->magic
== CONTROL_CONNECTION_MAGIC
);
271 return DOWNCAST(control_connection_t
, c
);
274 /** Given a control event code for a message event, return the corresponding
277 event_to_log_severity(int event
)
280 case EVENT_DEBUG_MSG
: return LOG_DEBUG
;
281 case EVENT_INFO_MSG
: return LOG_INFO
;
282 case EVENT_NOTICE_MSG
: return LOG_NOTICE
;
283 case EVENT_WARN_MSG
: return LOG_WARN
;
284 case EVENT_ERR_MSG
: return LOG_ERR
;
289 /** Given a log severity, return the corresponding control event code. */
291 log_severity_to_event(int severity
)
294 case LOG_DEBUG
: return EVENT_DEBUG_MSG
;
295 case LOG_INFO
: return EVENT_INFO_MSG
;
296 case LOG_NOTICE
: return EVENT_NOTICE_MSG
;
297 case LOG_WARN
: return EVENT_WARN_MSG
;
298 case LOG_ERR
: return EVENT_ERR_MSG
;
303 /** Helper: clear bandwidth counters of all origin circuits. */
305 clear_circ_bw_fields(void)
307 origin_circuit_t
*ocirc
;
308 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t
*, circ
) {
309 if (!CIRCUIT_IS_ORIGIN(circ
))
311 ocirc
= TO_ORIGIN_CIRCUIT(circ
);
312 ocirc
->n_written_circ_bw
= ocirc
->n_read_circ_bw
= 0;
313 ocirc
->n_overhead_written_circ_bw
= ocirc
->n_overhead_read_circ_bw
= 0;
314 ocirc
->n_delivered_written_circ_bw
= ocirc
->n_delivered_read_circ_bw
= 0;
316 SMARTLIST_FOREACH_END(circ
);
319 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
320 * connection's event_mask field. */
322 control_update_global_event_mask(void)
324 smartlist_t
*conns
= get_connection_array();
325 event_mask_t old_mask
, new_mask
;
326 old_mask
= global_event_mask
;
327 int any_old_per_sec_events
= control_any_per_second_event_enabled();
329 global_event_mask
= 0;
330 SMARTLIST_FOREACH(conns
, connection_t
*, _conn
,
332 if (_conn
->type
== CONN_TYPE_CONTROL
&&
333 STATE_IS_OPEN(_conn
->state
)) {
334 control_connection_t
*conn
= TO_CONTROL_CONN(_conn
);
335 global_event_mask
|= conn
->event_mask
;
339 new_mask
= global_event_mask
;
341 /* Handle the aftermath. Set up the log callback to tell us only what
342 * we want to hear...*/
343 control_adjust_event_log_severity();
345 /* Macro: true if ev was false before and is true now. */
346 #define NEWLY_ENABLED(ev) \
347 (! (old_mask & (ev)) && (new_mask & (ev)))
349 /* ...then, if we've started logging stream or circ bw, clear the
350 * appropriate fields. */
351 if (NEWLY_ENABLED(EVENT_STREAM_BANDWIDTH_USED
)) {
352 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
354 if (conn
->type
== CONN_TYPE_AP
) {
355 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
356 edge_conn
->n_written
= edge_conn
->n_read
= 0;
360 if (NEWLY_ENABLED(EVENT_CIRC_BANDWIDTH_USED
)) {
361 clear_circ_bw_fields();
363 if (NEWLY_ENABLED(EVENT_BANDWIDTH_USED
)) {
365 control_get_bytes_rw_last_sec(&r
, &w
);
367 if (any_old_per_sec_events
!= control_any_per_second_event_enabled()) {
368 reschedule_per_second_timer();
374 /** Adjust the log severities that result in control_event_logmsg being called
375 * to match the severity of log messages that any controllers are interested
378 control_adjust_event_log_severity(void)
381 int min_log_event
=EVENT_ERR_MSG
, max_log_event
=EVENT_DEBUG_MSG
;
383 for (i
= EVENT_DEBUG_MSG
; i
<= EVENT_ERR_MSG
; ++i
) {
384 if (EVENT_IS_INTERESTING(i
)) {
389 for (i
= EVENT_ERR_MSG
; i
>= EVENT_DEBUG_MSG
; --i
) {
390 if (EVENT_IS_INTERESTING(i
)) {
395 if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
)) {
396 if (min_log_event
> EVENT_NOTICE_MSG
)
397 min_log_event
= EVENT_NOTICE_MSG
;
398 if (max_log_event
< EVENT_ERR_MSG
)
399 max_log_event
= EVENT_ERR_MSG
;
401 if (min_log_event
<= max_log_event
)
402 change_callback_log_severity(event_to_log_severity(min_log_event
),
403 event_to_log_severity(max_log_event
),
404 control_event_logmsg
);
406 change_callback_log_severity(LOG_ERR
, LOG_ERR
,
407 control_event_logmsg
);
410 /** Return true iff the event with code <b>c</b> is being sent to any current
411 * control connection. This is useful if the amount of work needed to prepare
412 * to call the appropriate control_event_...() function is high.
415 control_event_is_interesting(int event
)
417 return EVENT_IS_INTERESTING(event
);
420 /** Return true if any event that needs to fire once a second is enabled. */
422 control_any_per_second_event_enabled(void)
424 return ANY_EVENT_IS_INTERESTING(
425 EVENT_MASK_(EVENT_BANDWIDTH_USED
) |
426 EVENT_MASK_(EVENT_CELL_STATS
) |
427 EVENT_MASK_(EVENT_CIRC_BANDWIDTH_USED
) |
428 EVENT_MASK_(EVENT_CONN_BW
) |
429 EVENT_MASK_(EVENT_STREAM_BANDWIDTH_USED
)
433 /* The value of 'get_bytes_read()' the previous time that
434 * control_get_bytes_rw_last_sec() as called. */
435 static uint64_t stats_prev_n_read
= 0;
436 /* The value of 'get_bytes_written()' the previous time that
437 * control_get_bytes_rw_last_sec() as called. */
438 static uint64_t stats_prev_n_written
= 0;
441 * Set <b>n_read</b> and <b>n_written</b> to the total number of bytes read
442 * and written by Tor since the last call to this function.
444 * Call this only from the main thread.
447 control_get_bytes_rw_last_sec(uint64_t *n_read
,
450 const uint64_t stats_n_bytes_read
= get_bytes_read();
451 const uint64_t stats_n_bytes_written
= get_bytes_written();
453 *n_read
= stats_n_bytes_read
- stats_prev_n_read
;
454 *n_written
= stats_n_bytes_written
- stats_prev_n_written
;
455 stats_prev_n_read
= stats_n_bytes_read
;
456 stats_prev_n_written
= stats_n_bytes_written
;
460 * Run all the controller events (if any) that are scheduled to trigger once
464 control_per_second_events(void)
466 if (!control_any_per_second_event_enabled())
469 uint64_t bytes_read
, bytes_written
;
470 control_get_bytes_rw_last_sec(&bytes_read
, &bytes_written
);
471 control_event_bandwidth_used((uint32_t)bytes_read
,(uint32_t)bytes_written
);
473 control_event_stream_bandwidth_used();
474 control_event_conn_bandwidth_used();
475 control_event_circ_bandwidth_used();
476 control_event_circuit_cell_stats();
479 /** Append a NUL-terminated string <b>s</b> to the end of
480 * <b>conn</b>-\>outbuf.
483 connection_write_str_to_buf(const char *s
, control_connection_t
*conn
)
485 size_t len
= strlen(s
);
486 connection_buf_add(s
, len
, TO_CONN(conn
));
489 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
490 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
491 * contents of <b>data</b> into *<b>out</b>, adding a period before any period
492 * that appears at the start of a line, and adding a period-CRLF line at
493 * the end. Replace all LF characters sequences with CRLF. Return the number
494 * of bytes in *<b>out</b>.
497 write_escaped_data(const char *data
, size_t len
, char **out
)
499 tor_assert(len
< SIZE_MAX
- 9);
500 size_t sz_out
= len
+8+1;
502 const char *start
= data
, *end
;
505 for (i
=0; i
< len
; ++i
) {
506 if (data
[i
] == '\n') {
507 sz_out
+= 2; /* Maybe add a CR; maybe add a dot. */
508 if (sz_out
>= SIZE_T_CEILING
) {
509 log_warn(LD_BUG
, "Input to write_escaped_data was too long");
510 *out
= tor_strdup(".\r\n");
515 *out
= outp
= tor_malloc(sz_out
);
520 if (data
> start
&& data
[-1] != '\r')
523 } else if (*data
== '.') {
533 if (outp
< *out
+2 || fast_memcmp(outp
-2, "\r\n", 2)) {
540 *outp
= '\0'; /* NUL-terminate just in case. */
541 tor_assert(outp
>= *out
);
542 tor_assert((size_t)(outp
- *out
) <= sz_out
);
546 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
547 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
548 * the contents of <b>data</b> into *<b>out</b>, removing any period
549 * that appears at the start of a line, and replacing all CRLF sequences
550 * with LF. Return the number of
551 * bytes in *<b>out</b>. */
553 read_escaped_data(const char *data
, size_t len
, char **out
)
559 *out
= outp
= tor_malloc(len
+1);
564 /* we're at the start of a line. */
567 next
= memchr(data
, '\n', end
-data
);
569 size_t n_to_copy
= next
-data
;
570 /* Don't copy a CR that precedes this LF. */
571 if (n_to_copy
&& *(next
-1) == '\r')
573 memcpy(outp
, data
, n_to_copy
);
575 data
= next
+1; /* This will point at the start of the next line,
576 * or the end of the string, or a period. */
578 memcpy(outp
, data
, end
-data
);
590 /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
591 * double-quoted string with escaped characters, return the length of that
592 * string (as encoded, including quotes). Otherwise return -1. */
594 get_escaped_string_length(const char *start
, size_t in_len_max
,
597 const char *cp
, *end
;
604 end
= start
+in_len_max
;
606 /* Calculate length. */
609 return -1; /* Too long. */
610 } else if (*cp
== '\\') {
612 return -1; /* Can't escape EOS. */
615 } else if (*cp
== '\"') {
624 return (int)(cp
- start
+1);
627 /** As decode_escaped_string, but does not decode the string: copies the
628 * entire thing, including quotation marks. */
630 extract_escaped_string(const char *start
, size_t in_len_max
,
631 char **out
, size_t *out_len
)
633 int length
= get_escaped_string_length(start
, in_len_max
, NULL
);
637 *out
= tor_strndup(start
, *out_len
);
641 /** Given a pointer to a string starting at <b>start</b> containing
642 * <b>in_len_max</b> characters, decode a string beginning with one double
643 * quote, containing any number of non-quote characters or characters escaped
644 * with a backslash, and ending with a final double quote. Place the resulting
645 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
646 * store its length in <b>out_len</b>. On success, return a pointer to the
647 * character immediately following the escaped string. On failure, return
650 decode_escaped_string(const char *start
, size_t in_len_max
,
651 char **out
, size_t *out_len
)
653 const char *cp
, *end
;
655 int len
, n_chars
= 0;
657 len
= get_escaped_string_length(start
, in_len_max
, &n_chars
);
661 end
= start
+len
-1; /* Index of last quote. */
662 tor_assert(*end
== '\"');
663 outp
= *out
= tor_malloc(len
+1);
673 tor_assert((outp
- *out
) == (int)*out_len
);
678 /** Create and add a new controller connection on <b>sock</b>. If
679 * <b>CC_LOCAL_FD_IS_OWNER</b> is set in <b>flags</b>, this Tor process should
680 * exit when the connection closes. If <b>CC_LOCAL_FD_IS_AUTHENTICATED</b>
681 * is set, then the connection does not need to authenticate.
684 control_connection_add_local_fd(tor_socket_t sock
, unsigned flags
)
686 if (BUG(! SOCKET_OK(sock
)))
688 const int is_owner
= !!(flags
& CC_LOCAL_FD_IS_OWNER
);
689 const int is_authenticated
= !!(flags
& CC_LOCAL_FD_IS_AUTHENTICATED
);
690 control_connection_t
*control_conn
= control_connection_new(AF_UNSPEC
);
691 connection_t
*conn
= TO_CONN(control_conn
);
693 tor_addr_make_unspec(&conn
->addr
);
695 conn
->address
= tor_strdup("<local socket>");
697 /* We take ownership of this socket so that later, when we close it,
698 * we don't freak out. */
699 tor_take_socket_ownership(sock
);
701 if (set_socket_nonblocking(sock
) < 0 ||
702 connection_add(conn
) < 0) {
703 connection_free(conn
);
707 control_conn
->is_owning_control_connection
= is_owner
;
709 if (connection_init_accepted_conn(conn
, NULL
) < 0) {
710 connection_mark_for_close(conn
);
714 if (is_authenticated
) {
715 conn
->state
= CONTROL_CONN_STATE_OPEN
;
721 /** Acts like sprintf, but writes its formatted string to the end of
722 * <b>conn</b>-\>outbuf. */
724 connection_printf_to_buf(control_connection_t
*conn
, const char *format
, ...)
731 len
= tor_vasprintf(&buf
, format
, ap
);
735 log_err(LD_BUG
, "Unable to format string for controller.");
739 connection_buf_add(buf
, (size_t)len
, TO_CONN(conn
));
744 /** Write all of the open control ports to ControlPortWriteToFile */
746 control_ports_write_to_file(void)
750 const or_options_t
*options
= get_options();
752 if (!options
->ControlPortWriteToFile
)
755 lines
= smartlist_new();
757 SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t
*, conn
) {
758 if (conn
->type
!= CONN_TYPE_CONTROL_LISTENER
|| conn
->marked_for_close
)
761 if (conn
->socket_family
== AF_UNIX
) {
762 smartlist_add_asprintf(lines
, "UNIX_PORT=%s\n", conn
->address
);
765 #endif /* defined(AF_UNIX) */
766 smartlist_add_asprintf(lines
, "PORT=%s:%d\n", conn
->address
, conn
->port
);
767 } SMARTLIST_FOREACH_END(conn
);
769 joined
= smartlist_join_strings(lines
, "", 0, NULL
);
771 if (write_str_to_file(options
->ControlPortWriteToFile
, joined
, 0) < 0) {
772 log_warn(LD_CONTROL
, "Writing %s failed: %s",
773 options
->ControlPortWriteToFile
, strerror(errno
));
776 if (options
->ControlPortFileGroupReadable
) {
777 if (chmod(options
->ControlPortWriteToFile
, 0640)) {
778 log_warn(LD_FS
,"Unable to make %s group-readable.",
779 options
->ControlPortWriteToFile
);
782 #endif /* !defined(_WIN32) */
784 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
785 smartlist_free(lines
);
788 /** Send a "DONE" message down the control connection <b>conn</b>. */
790 send_control_done(control_connection_t
*conn
)
792 connection_write_str_to_buf("250 OK\r\n", conn
);
795 /** Represents an event that's queued to be sent to one or more
797 typedef struct queued_event_s
{
802 /** Pointer to int. If this is greater than 0, we don't allow new events to be
804 static tor_threadlocal_t block_event_queue_flag
;
806 /** Holds a smartlist of queued_event_t objects that may need to be sent
807 * to one or more controllers */
808 static smartlist_t
*queued_control_events
= NULL
;
810 /** True if the flush_queued_events_event is pending. */
811 static int flush_queued_event_pending
= 0;
813 /** Lock to protect the above fields. */
814 static tor_mutex_t
*queued_control_events_lock
= NULL
;
816 /** An event that should fire in order to flush the contents of
817 * queued_control_events. */
818 static mainloop_event_t
*flush_queued_events_event
= NULL
;
821 control_initialize_event_queue(void)
823 if (queued_control_events
== NULL
) {
824 queued_control_events
= smartlist_new();
827 if (flush_queued_events_event
== NULL
) {
828 struct event_base
*b
= tor_libevent_get_base();
830 flush_queued_events_event
=
831 mainloop_event_new(flush_queued_events_cb
, NULL
);
832 tor_assert(flush_queued_events_event
);
836 if (queued_control_events_lock
== NULL
) {
837 queued_control_events_lock
= tor_mutex_new();
838 tor_threadlocal_init(&block_event_queue_flag
);
843 get_block_event_queue(void)
845 int *val
= tor_threadlocal_get(&block_event_queue_flag
);
846 if (PREDICT_UNLIKELY(val
== NULL
)) {
847 val
= tor_malloc_zero(sizeof(int));
848 tor_threadlocal_set(&block_event_queue_flag
, val
);
853 /** Helper: inserts an event on the list of events queued to be sent to
854 * one or more controllers, and schedules the events to be flushed if needed.
856 * This function takes ownership of <b>msg</b>, and may free it.
858 * We queue these events rather than send them immediately in order to break
859 * the dependency in our callgraph from code that generates events for the
860 * controller, and the network layer at large. Otherwise, nearly every
861 * interesting part of Tor would potentially call every other interesting part
864 MOCK_IMPL(STATIC
void,
865 queue_control_event_string
,(uint16_t event
, char *msg
))
867 /* This is redundant with checks done elsewhere, but it's a last-ditch
868 * attempt to avoid queueing something we shouldn't have to queue. */
869 if (PREDICT_UNLIKELY( ! EVENT_IS_INTERESTING(event
) )) {
874 int *block_event_queue
= get_block_event_queue();
875 if (*block_event_queue
) {
880 queued_event_t
*ev
= tor_malloc(sizeof(*ev
));
884 /* No queueing an event while queueing an event */
885 ++*block_event_queue
;
887 tor_mutex_acquire(queued_control_events_lock
);
888 tor_assert(queued_control_events
);
889 smartlist_add(queued_control_events
, ev
);
891 int activate_event
= 0;
892 if (! flush_queued_event_pending
&& in_main_thread()) {
894 flush_queued_event_pending
= 1;
897 tor_mutex_release(queued_control_events_lock
);
899 --*block_event_queue
;
901 /* We just put an event on the queue; mark the queue to be
902 * flushed. We only do this from the main thread for now; otherwise,
903 * we'd need to incur locking overhead in Libevent or use a socket.
905 if (activate_event
) {
906 tor_assert(flush_queued_events_event
);
907 mainloop_event_activate(flush_queued_events_event
);
911 #define queued_event_free(ev) \
912 FREE_AND_NULL(queued_event_t, queued_event_free_, (ev))
914 /** Release all storage held by <b>ev</b>. */
916 queued_event_free_(queued_event_t
*ev
)
925 /** Send every queued event to every controller that's interested in it,
926 * and remove the events from the queue. If <b>force</b> is true,
927 * then make all controllers send their data out immediately, since we
928 * may be about to shut down. */
930 queued_events_flush_all(int force
)
932 /* Make sure that we get all the pending log events, if there are any. */
933 flush_pending_log_callbacks();
935 if (PREDICT_UNLIKELY(queued_control_events
== NULL
)) {
938 smartlist_t
*all_conns
= get_connection_array();
939 smartlist_t
*controllers
= smartlist_new();
940 smartlist_t
*queued_events
;
942 int *block_event_queue
= get_block_event_queue();
943 ++*block_event_queue
;
945 tor_mutex_acquire(queued_control_events_lock
);
946 /* No queueing an event while flushing events. */
947 flush_queued_event_pending
= 0;
948 queued_events
= queued_control_events
;
949 queued_control_events
= smartlist_new();
950 tor_mutex_release(queued_control_events_lock
);
952 /* Gather all the controllers that will care... */
953 SMARTLIST_FOREACH_BEGIN(all_conns
, connection_t
*, conn
) {
954 if (conn
->type
== CONN_TYPE_CONTROL
&&
955 !conn
->marked_for_close
&&
956 conn
->state
== CONTROL_CONN_STATE_OPEN
) {
957 control_connection_t
*control_conn
= TO_CONTROL_CONN(conn
);
959 smartlist_add(controllers
, control_conn
);
961 } SMARTLIST_FOREACH_END(conn
);
963 SMARTLIST_FOREACH_BEGIN(queued_events
, queued_event_t
*, ev
) {
964 const event_mask_t bit
= ((event_mask_t
)1) << ev
->event
;
965 const size_t msg_len
= strlen(ev
->msg
);
966 SMARTLIST_FOREACH_BEGIN(controllers
, control_connection_t
*,
968 if (control_conn
->event_mask
& bit
) {
969 connection_buf_add(ev
->msg
, msg_len
, TO_CONN(control_conn
));
971 } SMARTLIST_FOREACH_END(control_conn
);
973 queued_event_free(ev
);
974 } SMARTLIST_FOREACH_END(ev
);
977 SMARTLIST_FOREACH_BEGIN(controllers
, control_connection_t
*,
979 connection_flush(TO_CONN(control_conn
));
980 } SMARTLIST_FOREACH_END(control_conn
);
983 smartlist_free(queued_events
);
984 smartlist_free(controllers
);
986 --*block_event_queue
;
989 /** Libevent callback: Flushes pending events to controllers that are
990 * interested in them. */
992 flush_queued_events_cb(mainloop_event_t
*event
, void *arg
)
996 queued_events_flush_all(0);
999 /** Send an event to all v1 controllers that are listening for code
1000 * <b>event</b>. The event's body is given by <b>msg</b>.
1002 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
1003 * respect to the EXTENDED_EVENTS feature. */
1004 MOCK_IMPL(STATIC
void,
1005 send_control_event_string
,(uint16_t event
,
1008 tor_assert(event
>= EVENT_MIN_
&& event
<= EVENT_MAX_
);
1009 queue_control_event_string(event
, tor_strdup(msg
));
1012 /** Helper for send_control_event and control_event_status:
1013 * Send an event to all v1 controllers that are listening for code
1014 * <b>event</b>. The event's body is created by the printf-style format in
1015 * <b>format</b>, and other arguments as provided. */
1017 send_control_event_impl(uint16_t event
,
1018 const char *format
, va_list ap
)
1023 len
= tor_vasprintf(&buf
, format
, ap
);
1025 log_warn(LD_BUG
, "Unable to format event for controller.");
1029 queue_control_event_string(event
, buf
);
1032 /** Send an event to all v1 controllers that are listening for code
1033 * <b>event</b>. The event's body is created by the printf-style format in
1034 * <b>format</b>, and other arguments as provided. */
1036 send_control_event(uint16_t event
,
1037 const char *format
, ...)
1040 va_start(ap
, format
);
1041 send_control_event_impl(event
, format
, ap
);
1045 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
1046 static origin_circuit_t
*
1047 get_circ(const char *id
)
1051 n_id
= (uint32_t) tor_parse_ulong(id
, 10, 0, UINT32_MAX
, &ok
, NULL
);
1054 return circuit_get_by_global_id(n_id
);
1057 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
1058 static entry_connection_t
*
1059 get_stream(const char *id
)
1064 n_id
= tor_parse_uint64(id
, 10, 0, UINT64_MAX
, &ok
, NULL
);
1067 conn
= connection_get_by_global_id(n_id
);
1068 if (!conn
|| conn
->type
!= CONN_TYPE_AP
|| conn
->marked_for_close
)
1070 return TO_ENTRY_CONN(conn
);
1073 /** Helper for setconf and resetconf. Acts like setconf, except
1074 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
1078 control_setconf_helper(control_connection_t
*conn
, uint32_t len
, char *body
,
1081 setopt_err_t opt_err
;
1082 config_line_t
*lines
=NULL
;
1084 char *errstring
= NULL
;
1085 const unsigned flags
=
1086 CAL_CLEAR_FIRST
| (use_defaults
? CAL_USE_DEFAULTS
: 0);
1089 smartlist_t
*entries
= smartlist_new();
1091 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
1092 * separated by space. break it into a list of configuration entries. */
1097 while (!TOR_ISSPACE(*eq
) && *eq
!= '=')
1099 key
= tor_strndup(body
, eq
-body
);
1104 if (*body
!= '\"') {
1105 char *val_start
= body
;
1106 while (!TOR_ISSPACE(*body
))
1108 val
= tor_strndup(val_start
, body
-val_start
);
1109 val_len
= strlen(val
);
1111 body
= (char*)extract_escaped_string(body
, (len
- (body
-start
)),
1114 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn
);
1115 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
1116 smartlist_free(entries
);
1121 tor_asprintf(&entry
, "%s %s", key
, val
);
1127 smartlist_add(entries
, entry
);
1128 while (TOR_ISSPACE(*body
))
1132 smartlist_add_strdup(entries
, "");
1133 config
= smartlist_join_strings(entries
, "\n", 0, NULL
);
1134 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
1135 smartlist_free(entries
);
1137 if (config_get_lines(config
, &lines
, 0) < 0) {
1138 log_warn(LD_CONTROL
,"Controller gave us config lines we can't parse.");
1139 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
1146 opt_err
= options_trial_assign(lines
, flags
, &errstring
);
1150 case SETOPT_ERR_MISC
:
1151 msg
= "552 Unrecognized option";
1153 case SETOPT_ERR_PARSE
:
1154 msg
= "513 Unacceptable option value";
1156 case SETOPT_ERR_TRANSITION
:
1157 msg
= "553 Transition not allowed";
1159 case SETOPT_ERR_SETTING
:
1161 msg
= "553 Unable to set option";
1164 config_free_lines(lines
);
1165 send_control_done(conn
);
1168 log_warn(LD_CONTROL
,
1169 "Controller gave us config lines that didn't validate: %s",
1171 connection_printf_to_buf(conn
, "%s: %s\r\n", msg
, errstring
);
1172 config_free_lines(lines
);
1173 tor_free(errstring
);
1178 /** Called when we receive a SETCONF message: parse the body and try
1179 * to update our configuration. Reply with a DONE or ERROR message.
1180 * Modifies the contents of body.*/
1182 handle_control_setconf(control_connection_t
*conn
, uint32_t len
, char *body
)
1184 return control_setconf_helper(conn
, len
, body
, 0);
1187 /** Called when we receive a RESETCONF message: parse the body and try
1188 * to update our configuration. Reply with a DONE or ERROR message.
1189 * Modifies the contents of body. */
1191 handle_control_resetconf(control_connection_t
*conn
, uint32_t len
, char *body
)
1193 return control_setconf_helper(conn
, len
, body
, 1);
1196 /** Called when we receive a GETCONF message. Parse the request, and
1197 * reply with a CONFVALUE or an ERROR message */
1199 handle_control_getconf(control_connection_t
*conn
, uint32_t body_len
,
1202 smartlist_t
*questions
= smartlist_new();
1203 smartlist_t
*answers
= smartlist_new();
1204 smartlist_t
*unrecognized
= smartlist_new();
1207 const or_options_t
*options
= get_options();
1210 (void) body_len
; /* body is NUL-terminated; so we can ignore len. */
1211 smartlist_split_string(questions
, body
, " ",
1212 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1213 SMARTLIST_FOREACH_BEGIN(questions
, const char *, q
) {
1214 if (!option_is_recognized(q
)) {
1215 smartlist_add(unrecognized
, (char*) q
);
1217 config_line_t
*answer
= option_get_assignment(options
,q
);
1219 const char *name
= option_get_canonical_name(q
);
1220 smartlist_add_asprintf(answers
, "250-%s\r\n", name
);
1224 config_line_t
*next
;
1225 smartlist_add_asprintf(answers
, "250-%s=%s\r\n",
1226 answer
->key
, answer
->value
);
1228 next
= answer
->next
;
1229 tor_free(answer
->key
);
1230 tor_free(answer
->value
);
1235 } SMARTLIST_FOREACH_END(q
);
1237 if ((len
= smartlist_len(unrecognized
))) {
1238 for (i
=0; i
< len
-1; ++i
)
1239 connection_printf_to_buf(conn
,
1240 "552-Unrecognized configuration key \"%s\"\r\n",
1241 (char*)smartlist_get(unrecognized
, i
));
1242 connection_printf_to_buf(conn
,
1243 "552 Unrecognized configuration key \"%s\"\r\n",
1244 (char*)smartlist_get(unrecognized
, len
-1));
1245 } else if ((len
= smartlist_len(answers
))) {
1246 char *tmp
= smartlist_get(answers
, len
-1);
1247 tor_assert(strlen(tmp
)>4);
1249 msg
= smartlist_join_strings(answers
, "", 0, &msg_len
);
1250 connection_buf_add(msg
, msg_len
, TO_CONN(conn
));
1252 connection_write_str_to_buf("250 OK\r\n", conn
);
1255 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
1256 smartlist_free(answers
);
1257 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
1258 smartlist_free(questions
);
1259 smartlist_free(unrecognized
);
1266 /** Called when we get a +LOADCONF message. */
1268 handle_control_loadconf(control_connection_t
*conn
, uint32_t len
,
1271 setopt_err_t retval
;
1272 char *errstring
= NULL
;
1273 const char *msg
= NULL
;
1276 retval
= options_init_from_string(NULL
, body
, CMD_RUN_TOR
, NULL
, &errstring
);
1278 if (retval
!= SETOPT_OK
)
1279 log_warn(LD_CONTROL
,
1280 "Controller gave us config file that didn't validate: %s",
1284 case SETOPT_ERR_PARSE
:
1285 msg
= "552 Invalid config file";
1287 case SETOPT_ERR_TRANSITION
:
1288 msg
= "553 Transition not allowed";
1290 case SETOPT_ERR_SETTING
:
1291 msg
= "553 Unable to set option";
1293 case SETOPT_ERR_MISC
:
1295 msg
= "550 Unable to load config";
1302 connection_printf_to_buf(conn
, "%s: %s\r\n", msg
, errstring
);
1304 connection_printf_to_buf(conn
, "%s\r\n", msg
);
1306 send_control_done(conn
);
1308 tor_free(errstring
);
1312 /** Helper structure: maps event values to their names. */
1313 struct control_event_t
{
1314 uint16_t event_code
;
1315 const char *event_name
;
1317 /** Table mapping event values to their names. Used to implement SETEVENTS
1318 * and GETINFO events/names, and to keep they in sync. */
1319 static const struct control_event_t control_event_table
[] = {
1320 { EVENT_CIRCUIT_STATUS
, "CIRC" },
1321 { EVENT_CIRCUIT_STATUS_MINOR
, "CIRC_MINOR" },
1322 { EVENT_STREAM_STATUS
, "STREAM" },
1323 { EVENT_OR_CONN_STATUS
, "ORCONN" },
1324 { EVENT_BANDWIDTH_USED
, "BW" },
1325 { EVENT_DEBUG_MSG
, "DEBUG" },
1326 { EVENT_INFO_MSG
, "INFO" },
1327 { EVENT_NOTICE_MSG
, "NOTICE" },
1328 { EVENT_WARN_MSG
, "WARN" },
1329 { EVENT_ERR_MSG
, "ERR" },
1330 { EVENT_NEW_DESC
, "NEWDESC" },
1331 { EVENT_ADDRMAP
, "ADDRMAP" },
1332 { EVENT_DESCCHANGED
, "DESCCHANGED" },
1334 { EVENT_STATUS_GENERAL
, "STATUS_GENERAL" },
1335 { EVENT_STATUS_CLIENT
, "STATUS_CLIENT" },
1336 { EVENT_STATUS_SERVER
, "STATUS_SERVER" },
1337 { EVENT_GUARD
, "GUARD" },
1338 { EVENT_STREAM_BANDWIDTH_USED
, "STREAM_BW" },
1339 { EVENT_CLIENTS_SEEN
, "CLIENTS_SEEN" },
1340 { EVENT_NEWCONSENSUS
, "NEWCONSENSUS" },
1341 { EVENT_BUILDTIMEOUT_SET
, "BUILDTIMEOUT_SET" },
1342 { EVENT_GOT_SIGNAL
, "SIGNAL" },
1343 { EVENT_CONF_CHANGED
, "CONF_CHANGED"},
1344 { EVENT_CONN_BW
, "CONN_BW" },
1345 { EVENT_CELL_STATS
, "CELL_STATS" },
1346 { EVENT_CIRC_BANDWIDTH_USED
, "CIRC_BW" },
1347 { EVENT_TRANSPORT_LAUNCHED
, "TRANSPORT_LAUNCHED" },
1348 { EVENT_HS_DESC
, "HS_DESC" },
1349 { EVENT_HS_DESC_CONTENT
, "HS_DESC_CONTENT" },
1350 { EVENT_NETWORK_LIVENESS
, "NETWORK_LIVENESS" },
1354 /** Called when we get a SETEVENTS message: update conn->event_mask,
1355 * and reply with DONE or ERROR. */
1357 handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
1361 event_mask_t event_mask
= 0;
1362 smartlist_t
*events
= smartlist_new();
1366 smartlist_split_string(events
, body
, " ",
1367 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1368 SMARTLIST_FOREACH_BEGIN(events
, const char *, ev
)
1370 if (!strcasecmp(ev
, "EXTENDED") ||
1371 !strcasecmp(ev
, "AUTHDIR_NEWDESCS")) {
1372 log_warn(LD_CONTROL
, "The \"%s\" SETEVENTS argument is no longer "
1379 for (i
= 0; control_event_table
[i
].event_name
!= NULL
; ++i
) {
1380 if (!strcasecmp(ev
, control_event_table
[i
].event_name
)) {
1381 event_code
= control_event_table
[i
].event_code
;
1386 if (event_code
== -1) {
1387 connection_printf_to_buf(conn
, "552 Unrecognized event \"%s\"\r\n",
1389 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
1390 smartlist_free(events
);
1394 event_mask
|= (((event_mask_t
)1) << event_code
);
1396 SMARTLIST_FOREACH_END(ev
);
1397 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
1398 smartlist_free(events
);
1400 conn
->event_mask
= event_mask
;
1402 control_update_global_event_mask();
1403 send_control_done(conn
);
1407 /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
1408 * Return a smartlist of acceptable passwords (unterminated strings of
1409 * length S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on
1413 decode_hashed_passwords(config_line_t
*passwords
)
1417 smartlist_t
*sl
= smartlist_new();
1419 tor_assert(passwords
);
1421 for (cl
= passwords
; cl
; cl
= cl
->next
) {
1422 const char *hashed
= cl
->value
;
1424 if (!strcmpstart(hashed
, "16:")) {
1425 if (base16_decode(decoded
, sizeof(decoded
), hashed
+3, strlen(hashed
+3))
1426 != S2K_RFC2440_SPECIFIER_LEN
+ DIGEST_LEN
1427 || strlen(hashed
+3) != (S2K_RFC2440_SPECIFIER_LEN
+DIGEST_LEN
)*2) {
1431 if (base64_decode(decoded
, sizeof(decoded
), hashed
, strlen(hashed
))
1432 != S2K_RFC2440_SPECIFIER_LEN
+DIGEST_LEN
) {
1437 tor_memdup(decoded
, S2K_RFC2440_SPECIFIER_LEN
+DIGEST_LEN
));
1443 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
1448 /** Called when we get an AUTHENTICATE message. Check whether the
1449 * authentication is valid, and if so, update the connection's state to
1450 * OPEN. Reply with DONE or ERROR.
1453 handle_control_authenticate(control_connection_t
*conn
, uint32_t len
,
1456 int used_quoted_string
= 0;
1457 const or_options_t
*options
= get_options();
1458 const char *errstr
= "Unknown error";
1460 size_t password_len
;
1463 int bad_cookie
=0, bad_password
=0;
1464 smartlist_t
*sl
= NULL
;
1467 password
= tor_strdup("");
1469 } else if (TOR_ISXDIGIT(body
[0])) {
1471 while (TOR_ISXDIGIT(*cp
))
1473 i
= (int)(cp
- body
);
1476 password
= tor_malloc(password_len
+ 1);
1477 if (base16_decode(password
, password_len
+1, body
, i
)
1478 != (int) password_len
) {
1479 connection_write_str_to_buf(
1480 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1481 "password? If so, the standard requires that you put it in "
1482 "double quotes.\r\n", conn
);
1483 connection_mark_for_close(TO_CONN(conn
));
1488 if (!decode_escaped_string(body
, len
, &password
, &password_len
)) {
1489 connection_write_str_to_buf("551 Invalid quoted string. You need "
1490 "to put the password in double quotes.\r\n", conn
);
1491 connection_mark_for_close(TO_CONN(conn
));
1494 used_quoted_string
= 1;
1497 if (conn
->safecookie_client_hash
!= NULL
) {
1498 /* The controller has chosen safe cookie authentication; the only
1499 * acceptable authentication value is the controller-to-server
1502 tor_assert(authentication_cookie_is_set
);
1504 if (password_len
!= DIGEST256_LEN
) {
1505 log_warn(LD_CONTROL
,
1506 "Got safe cookie authentication response with wrong length "
1507 "(%d)", (int)password_len
);
1508 errstr
= "Wrong length for safe cookie response.";
1512 if (tor_memneq(conn
->safecookie_client_hash
, password
, DIGEST256_LEN
)) {
1513 log_warn(LD_CONTROL
,
1514 "Got incorrect safe cookie authentication response");
1515 errstr
= "Safe cookie response did not match expected value.";
1519 tor_free(conn
->safecookie_client_hash
);
1523 if (!options
->CookieAuthentication
&& !options
->HashedControlPassword
&&
1524 !options
->HashedControlSessionPassword
) {
1525 /* if Tor doesn't demand any stronger authentication, then
1526 * the controller can get in with anything. */
1530 if (options
->CookieAuthentication
) {
1531 int also_password
= options
->HashedControlPassword
!= NULL
||
1532 options
->HashedControlSessionPassword
!= NULL
;
1533 if (password_len
!= AUTHENTICATION_COOKIE_LEN
) {
1534 if (!also_password
) {
1535 log_warn(LD_CONTROL
, "Got authentication cookie with wrong length "
1536 "(%d)", (int)password_len
);
1537 errstr
= "Wrong length on authentication cookie.";
1541 } else if (tor_memneq(authentication_cookie
, password
, password_len
)) {
1542 if (!also_password
) {
1543 log_warn(LD_CONTROL
, "Got mismatched authentication cookie");
1544 errstr
= "Authentication cookie did not match expected value.";
1553 if (options
->HashedControlPassword
||
1554 options
->HashedControlSessionPassword
) {
1556 smartlist_t
*sl_tmp
;
1557 char received
[DIGEST_LEN
];
1558 int also_cookie
= options
->CookieAuthentication
;
1559 sl
= smartlist_new();
1560 if (options
->HashedControlPassword
) {
1561 sl_tmp
= decode_hashed_passwords(options
->HashedControlPassword
);
1565 smartlist_add_all(sl
, sl_tmp
);
1566 smartlist_free(sl_tmp
);
1569 if (options
->HashedControlSessionPassword
) {
1570 sl_tmp
= decode_hashed_passwords(options
->HashedControlSessionPassword
);
1574 smartlist_add_all(sl
, sl_tmp
);
1575 smartlist_free(sl_tmp
);
1581 "Couldn't decode HashedControlPassword: invalid base16");
1582 errstr
="Couldn't decode HashedControlPassword value in configuration.";
1586 SMARTLIST_FOREACH(sl
, char *, str
, tor_free(str
));
1590 SMARTLIST_FOREACH(sl
, char *, expected
,
1592 secret_to_key_rfc2440(received
,DIGEST_LEN
,
1593 password
,password_len
,expected
);
1594 if (tor_memeq(expected
+ S2K_RFC2440_SPECIFIER_LEN
,
1595 received
, DIGEST_LEN
))
1598 SMARTLIST_FOREACH(sl
, char *, str
, tor_free(str
));
1602 if (used_quoted_string
)
1603 errstr
= "Password did not match HashedControlPassword value from "
1606 errstr
= "Password did not match HashedControlPassword value from "
1607 "configuration. Maybe you tried a plain text password? "
1608 "If so, the standard requires that you put it in double quotes.";
1615 /** We only get here if both kinds of authentication failed. */
1616 tor_assert(bad_password
&& bad_cookie
);
1617 log_warn(LD_CONTROL
, "Bad password or authentication cookie on controller.");
1618 errstr
= "Password did not match HashedControlPassword *or* authentication "
1623 connection_printf_to_buf(conn
, "515 Authentication failed: %s\r\n", errstr
);
1624 connection_mark_for_close(TO_CONN(conn
));
1625 if (sl
) { /* clean up */
1626 SMARTLIST_FOREACH(sl
, char *, str
, tor_free(str
));
1631 log_info(LD_CONTROL
, "Authenticated control connection ("TOR_SOCKET_T_FORMAT
1632 ")", conn
->base_
.s
);
1633 send_control_done(conn
);
1634 conn
->base_
.state
= CONTROL_CONN_STATE_OPEN
;
1636 if (sl
) { /* clean up */
1637 SMARTLIST_FOREACH(sl
, char *, str
, tor_free(str
));
1643 /** Called when we get a SAVECONF command. Try to flush the current options to
1644 * disk, and report success or failure. */
1646 handle_control_saveconf(control_connection_t
*conn
, uint32_t len
,
1651 int force
= !strcmpstart(body
, "FORCE");
1652 const or_options_t
*options
= get_options();
1653 if ((!force
&& options
->IncludeUsed
) || options_save_current() < 0) {
1654 connection_write_str_to_buf(
1655 "551 Unable to write configuration to disk.\r\n", conn
);
1657 send_control_done(conn
);
1664 const char *signal_name
;
1667 static const struct signal_t signal_table
[] = {
1668 { SIGHUP
, "RELOAD" },
1670 { SIGINT
, "SHUTDOWN" },
1671 { SIGUSR1
, "DUMP" },
1672 { SIGUSR1
, "USR1" },
1673 { SIGUSR2
, "DEBUG" },
1674 { SIGUSR2
, "USR2" },
1675 { SIGTERM
, "HALT" },
1676 { SIGTERM
, "TERM" },
1678 { SIGNEWNYM
, "NEWNYM" },
1679 { SIGCLEARDNSCACHE
, "CLEARDNSCACHE"},
1680 { SIGHEARTBEAT
, "HEARTBEAT"},
1684 /** Called when we get a SIGNAL command. React to the provided signal, and
1685 * report success or failure. (If the signal results in a shutdown, success
1686 * may not be reported.) */
1688 handle_control_signal(control_connection_t
*conn
, uint32_t len
,
1698 while (body
[n
] && ! TOR_ISSPACE(body
[n
]))
1700 s
= tor_strndup(body
, n
);
1702 for (i
= 0; signal_table
[i
].signal_name
!= NULL
; ++i
) {
1703 if (!strcasecmp(s
, signal_table
[i
].signal_name
)) {
1704 sig
= signal_table
[i
].sig
;
1710 connection_printf_to_buf(conn
, "552 Unrecognized signal code \"%s\"\r\n",
1716 send_control_done(conn
);
1717 /* Flush the "done" first if the signal might make us shut down. */
1718 if (sig
== SIGTERM
|| sig
== SIGINT
)
1719 connection_flush(TO_CONN(conn
));
1721 activate_signal(sig
);
1726 /** Called when we get a TAKEOWNERSHIP command. Mark this connection
1727 * as an owning connection, so that we will exit if the connection
1730 handle_control_takeownership(control_connection_t
*conn
, uint32_t len
,
1736 conn
->is_owning_control_connection
= 1;
1738 log_info(LD_CONTROL
, "Control connection %d has taken ownership of this "
1740 (int)(conn
->base_
.s
));
1742 send_control_done(conn
);
1746 /** Return true iff <b>addr</b> is unusable as a mapaddress target because of
1747 * containing funny characters. */
1749 address_is_invalid_mapaddress_target(const char *addr
)
1751 if (!strcmpstart(addr
, "*."))
1752 return address_is_invalid_destination(addr
+2, 1);
1754 return address_is_invalid_destination(addr
, 1);
1757 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1758 * and report success or failure. */
1760 handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
1768 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
1770 lines
= smartlist_new();
1771 elts
= smartlist_new();
1772 reply
= smartlist_new();
1773 smartlist_split_string(lines
, body
, " ",
1774 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1775 SMARTLIST_FOREACH_BEGIN(lines
, char *, line
) {
1777 smartlist_split_string(elts
, line
, "=", 0, 2);
1778 if (smartlist_len(elts
) == 2) {
1779 const char *from
= smartlist_get(elts
,0);
1780 const char *to
= smartlist_get(elts
,1);
1781 if (address_is_invalid_mapaddress_target(to
)) {
1782 smartlist_add_asprintf(reply
,
1783 "512-syntax error: invalid address '%s'", to
);
1784 log_warn(LD_CONTROL
,
1785 "Skipping invalid argument '%s' in MapAddress msg", to
);
1786 } else if (!strcmp(from
, ".") || !strcmp(from
, "0.0.0.0") ||
1787 !strcmp(from
, "::")) {
1789 !strcmp(from
,".") ? RESOLVED_TYPE_HOSTNAME
:
1790 (!strcmp(from
, "0.0.0.0") ? RESOLVED_TYPE_IPV4
: RESOLVED_TYPE_IPV6
);
1791 const char *address
= addressmap_register_virtual_address(
1792 type
, tor_strdup(to
));
1794 smartlist_add_asprintf(reply
,
1795 "451-resource exhausted: skipping '%s'", line
);
1796 log_warn(LD_CONTROL
,
1797 "Unable to allocate address for '%s' in MapAddress msg",
1798 safe_str_client(line
));
1800 smartlist_add_asprintf(reply
, "250-%s=%s", address
, to
);
1804 if (addressmap_register_auto(from
, to
, 1,
1805 ADDRMAPSRC_CONTROLLER
, &msg
) < 0) {
1806 smartlist_add_asprintf(reply
,
1807 "512-syntax error: invalid address mapping "
1808 " '%s': %s", line
, msg
);
1809 log_warn(LD_CONTROL
,
1810 "Skipping invalid argument '%s' in MapAddress msg: %s",
1813 smartlist_add_asprintf(reply
, "250-%s", line
);
1817 smartlist_add_asprintf(reply
, "512-syntax error: mapping '%s' is "
1818 "not of expected form 'foo=bar'.", line
);
1819 log_info(LD_CONTROL
, "Skipping MapAddress '%s': wrong "
1821 safe_str_client(line
));
1823 SMARTLIST_FOREACH(elts
, char *, cp
, tor_free(cp
));
1824 smartlist_clear(elts
);
1825 } SMARTLIST_FOREACH_END(line
);
1826 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
1827 smartlist_free(lines
);
1828 smartlist_free(elts
);
1830 if (smartlist_len(reply
)) {
1831 ((char*)smartlist_get(reply
,smartlist_len(reply
)-1))[3] = ' ';
1832 r
= smartlist_join_strings(reply
, "\r\n", 1, &sz
);
1833 connection_buf_add(r
, sz
, TO_CONN(conn
));
1836 const char *response
=
1837 "512 syntax error: not enough arguments to mapaddress.\r\n";
1838 connection_buf_add(response
, strlen(response
), TO_CONN(conn
));
1841 SMARTLIST_FOREACH(reply
, char *, cp
, tor_free(cp
));
1842 smartlist_free(reply
);
1846 /** Implementation helper for GETINFO: knows the answers for various
1847 * trivial-to-implement questions. */
1849 getinfo_helper_misc(control_connection_t
*conn
, const char *question
,
1850 char **answer
, const char **errmsg
)
1853 if (!strcmp(question
, "version")) {
1854 *answer
= tor_strdup(get_version());
1855 } else if (!strcmp(question
, "bw-event-cache")) {
1856 *answer
= get_bw_samples();
1857 } else if (!strcmp(question
, "config-file")) {
1858 const char *a
= get_torrc_fname(0);
1860 *answer
= tor_strdup(a
);
1861 } else if (!strcmp(question
, "config-defaults-file")) {
1862 const char *a
= get_torrc_fname(1);
1864 *answer
= tor_strdup(a
);
1865 } else if (!strcmp(question
, "config-text")) {
1866 *answer
= options_dump(get_options(), OPTIONS_DUMP_MINIMAL
);
1867 } else if (!strcmp(question
, "config-can-saveconf")) {
1868 *answer
= tor_strdup(get_options()->IncludeUsed
? "0" : "1");
1869 } else if (!strcmp(question
, "info/names")) {
1870 *answer
= list_getinfo_options();
1871 } else if (!strcmp(question
, "dormant")) {
1872 int dormant
= rep_hist_circbuilding_dormant(time(NULL
));
1873 *answer
= tor_strdup(dormant
? "1" : "0");
1874 } else if (!strcmp(question
, "events/names")) {
1876 smartlist_t
*event_names
= smartlist_new();
1878 for (i
= 0; control_event_table
[i
].event_name
!= NULL
; ++i
) {
1879 smartlist_add(event_names
, (char *)control_event_table
[i
].event_name
);
1882 *answer
= smartlist_join_strings(event_names
, " ", 0, NULL
);
1884 smartlist_free(event_names
);
1885 } else if (!strcmp(question
, "signal/names")) {
1886 smartlist_t
*signal_names
= smartlist_new();
1888 for (j
= 0; signal_table
[j
].signal_name
!= NULL
; ++j
) {
1889 smartlist_add(signal_names
, (char*)signal_table
[j
].signal_name
);
1892 *answer
= smartlist_join_strings(signal_names
, " ", 0, NULL
);
1894 smartlist_free(signal_names
);
1895 } else if (!strcmp(question
, "features/names")) {
1896 *answer
= tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1897 } else if (!strcmp(question
, "address")) {
1899 if (router_pick_published_address(get_options(), &addr
, 0) < 0) {
1900 *errmsg
= "Address unknown";
1903 *answer
= tor_dup_ip(addr
);
1904 } else if (!strcmp(question
, "traffic/read")) {
1905 tor_asprintf(answer
, "%"PRIu64
, (get_bytes_read()));
1906 } else if (!strcmp(question
, "traffic/written")) {
1907 tor_asprintf(answer
, "%"PRIu64
, (get_bytes_written()));
1908 } else if (!strcmp(question
, "uptime")) {
1909 long uptime_secs
= get_uptime();
1910 tor_asprintf(answer
, "%ld", uptime_secs
);
1911 } else if (!strcmp(question
, "process/pid")) {
1920 tor_asprintf(answer
, "%d", myPid
);
1921 } else if (!strcmp(question
, "process/uid")) {
1923 *answer
= tor_strdup("-1");
1925 int myUid
= geteuid();
1926 tor_asprintf(answer
, "%d", myUid
);
1927 #endif /* defined(_WIN32) */
1928 } else if (!strcmp(question
, "process/user")) {
1930 *answer
= tor_strdup("");
1932 int myUid
= geteuid();
1933 const struct passwd
*myPwEntry
= tor_getpwuid(myUid
);
1936 *answer
= tor_strdup(myPwEntry
->pw_name
);
1938 *answer
= tor_strdup("");
1940 #endif /* defined(_WIN32) */
1941 } else if (!strcmp(question
, "process/descriptor-limit")) {
1942 int max_fds
= get_max_sockets();
1943 tor_asprintf(answer
, "%d", max_fds
);
1944 } else if (!strcmp(question
, "limits/max-mem-in-queues")) {
1945 tor_asprintf(answer
, "%"PRIu64
,
1946 (get_options()->MaxMemInQueues
));
1947 } else if (!strcmp(question
, "fingerprint")) {
1948 crypto_pk_t
*server_key
;
1949 if (!server_mode(get_options())) {
1950 *errmsg
= "Not running in server mode";
1953 server_key
= get_server_identity_key();
1954 *answer
= tor_malloc(HEX_DIGEST_LEN
+1);
1955 crypto_pk_get_fingerprint(server_key
, *answer
, 0);
1960 /** Awful hack: return a newly allocated string based on a routerinfo and
1961 * (possibly) an extrainfo, sticking the read-history and write-history from
1962 * <b>ei</b> into the resulting string. The thing you get back won't
1963 * necessarily have a valid signature.
1965 * New code should never use this; it's for backward compatibility.
1967 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1968 * not be NUL-terminated. */
1970 munge_extrainfo_into_routerinfo(const char *ri_body
,
1971 const signed_descriptor_t
*ri
,
1972 const signed_descriptor_t
*ei
)
1974 char *out
= NULL
, *outp
;
1976 const char *router_sig
;
1977 const char *ei_body
= signed_descriptor_get_body(ei
);
1978 size_t ri_len
= ri
->signed_descriptor_len
;
1979 size_t ei_len
= ei
->signed_descriptor_len
;
1983 outp
= out
= tor_malloc(ri_len
+ei_len
+1);
1984 if (!(router_sig
= tor_memstr(ri_body
, ri_len
, "\nrouter-signature")))
1987 memcpy(out
, ri_body
, router_sig
-ri_body
);
1988 outp
+= router_sig
-ri_body
;
1990 for (i
=0; i
< 2; ++i
) {
1991 const char *kwd
= i
? "\nwrite-history " : "\nread-history ";
1992 const char *cp
, *eol
;
1993 if (!(cp
= tor_memstr(ei_body
, ei_len
, kwd
)))
1996 if (!(eol
= memchr(cp
, '\n', ei_len
- (cp
-ei_body
))))
1998 memcpy(outp
, cp
, eol
-cp
+1);
2001 memcpy(outp
, router_sig
, ri_len
- (router_sig
-ri_body
));
2003 tor_assert(outp
-out
< (int)(ri_len
+ei_len
+1));
2008 return tor_strndup(ri_body
, ri
->signed_descriptor_len
);
2011 /** Implementation helper for GETINFO: answers requests for information about
2012 * which ports are bound. */
2014 getinfo_helper_listeners(control_connection_t
*control_conn
,
2015 const char *question
,
2016 char **answer
, const char **errmsg
)
2024 if (!strcmp(question
, "net/listeners/or"))
2025 type
= CONN_TYPE_OR_LISTENER
;
2026 else if (!strcmp(question
, "net/listeners/extor"))
2027 type
= CONN_TYPE_EXT_OR_LISTENER
;
2028 else if (!strcmp(question
, "net/listeners/dir"))
2029 type
= CONN_TYPE_DIR_LISTENER
;
2030 else if (!strcmp(question
, "net/listeners/socks"))
2031 type
= CONN_TYPE_AP_LISTENER
;
2032 else if (!strcmp(question
, "net/listeners/trans"))
2033 type
= CONN_TYPE_AP_TRANS_LISTENER
;
2034 else if (!strcmp(question
, "net/listeners/natd"))
2035 type
= CONN_TYPE_AP_NATD_LISTENER
;
2036 else if (!strcmp(question
, "net/listeners/httptunnel"))
2037 type
= CONN_TYPE_AP_HTTP_CONNECT_LISTENER
;
2038 else if (!strcmp(question
, "net/listeners/dns"))
2039 type
= CONN_TYPE_AP_DNS_LISTENER
;
2040 else if (!strcmp(question
, "net/listeners/control"))
2041 type
= CONN_TYPE_CONTROL_LISTENER
;
2043 return 0; /* unknown key */
2045 res
= smartlist_new();
2046 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t
*, conn
) {
2047 struct sockaddr_storage ss
;
2048 socklen_t ss_len
= sizeof(ss
);
2050 if (conn
->type
!= type
|| conn
->marked_for_close
|| !SOCKET_OK(conn
->s
))
2053 if (getsockname(conn
->s
, (struct sockaddr
*)&ss
, &ss_len
) < 0) {
2054 smartlist_add_asprintf(res
, "%s:%d", conn
->address
, (int)conn
->port
);
2056 char *tmp
= tor_sockaddr_to_str((struct sockaddr
*)&ss
);
2057 smartlist_add(res
, esc_for_log(tmp
));
2061 } SMARTLIST_FOREACH_END(conn
);
2063 *answer
= smartlist_join_strings(res
, " ", 0, NULL
);
2065 SMARTLIST_FOREACH(res
, char *, cp
, tor_free(cp
));
2066 smartlist_free(res
);
2070 /** Implementation helper for GETINFO: answers requests for information about
2071 * the current time in both local and UTC forms. */
2073 getinfo_helper_current_time(control_connection_t
*control_conn
,
2074 const char *question
,
2075 char **answer
, const char **errmsg
)
2081 tor_gettimeofday(&now
);
2082 char timebuf
[ISO_TIME_LEN
+1];
2084 if (!strcmp(question
, "current-time/local"))
2085 format_local_iso_time_nospace(timebuf
, (time_t)now
.tv_sec
);
2086 else if (!strcmp(question
, "current-time/utc"))
2087 format_iso_time_nospace(timebuf
, (time_t)now
.tv_sec
);
2091 *answer
= tor_strdup(timebuf
);
2095 /** Implementation helper for GETINFO: knows the answers for questions about
2096 * directory information. */
2098 getinfo_helper_dir(control_connection_t
*control_conn
,
2099 const char *question
, char **answer
,
2100 const char **errmsg
)
2102 (void) control_conn
;
2103 if (!strcmpstart(question
, "desc/id/")) {
2104 const routerinfo_t
*ri
= NULL
;
2105 const node_t
*node
= node_get_by_hex_id(question
+strlen("desc/id/"), 0);
2109 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
2111 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
2112 } else if (! we_fetch_router_descriptors(get_options())) {
2113 /* Descriptors won't be available, provide proper error */
2114 *errmsg
= "We fetch microdescriptors, not router "
2115 "descriptors. You'll need to use md/id/* "
2116 "instead of desc/id/*.";
2119 } else if (!strcmpstart(question
, "desc/name/")) {
2120 const routerinfo_t
*ri
= NULL
;
2121 /* XXX Setting 'warn_if_unnamed' here is a bit silly -- the
2122 * warning goes to the user, not to the controller. */
2123 const node_t
*node
=
2124 node_get_by_nickname(question
+strlen("desc/name/"), 0);
2128 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
2130 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
2131 } else if (! we_fetch_router_descriptors(get_options())) {
2132 /* Descriptors won't be available, provide proper error */
2133 *errmsg
= "We fetch microdescriptors, not router "
2134 "descriptors. You'll need to use md/name/* "
2135 "instead of desc/name/*.";
2138 } else if (!strcmp(question
, "desc/download-enabled")) {
2139 int r
= we_fetch_router_descriptors(get_options());
2140 tor_asprintf(answer
, "%d", !!r
);
2141 } else if (!strcmp(question
, "desc/all-recent")) {
2142 routerlist_t
*routerlist
= router_get_routerlist();
2143 smartlist_t
*sl
= smartlist_new();
2144 if (routerlist
&& routerlist
->routers
) {
2145 SMARTLIST_FOREACH(routerlist
->routers
, const routerinfo_t
*, ri
,
2147 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
2150 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
2153 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
2154 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
2156 } else if (!strcmp(question
, "desc/all-recent-extrainfo-hack")) {
2157 /* XXXX Remove this once Torstat asks for extrainfos. */
2158 routerlist_t
*routerlist
= router_get_routerlist();
2159 smartlist_t
*sl
= smartlist_new();
2160 if (routerlist
&& routerlist
->routers
) {
2161 SMARTLIST_FOREACH_BEGIN(routerlist
->routers
, const routerinfo_t
*, ri
) {
2162 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
2163 signed_descriptor_t
*ei
= extrainfo_get_by_descriptor_digest(
2164 ri
->cache_info
.extra_info_digest
);
2166 smartlist_add(sl
, munge_extrainfo_into_routerinfo(body
,
2167 &ri
->cache_info
, ei
));
2170 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
2172 } SMARTLIST_FOREACH_END(ri
);
2174 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
2175 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
2177 } else if (!strcmpstart(question
, "hs/client/desc/id/")) {
2178 hostname_type_t addr_type
;
2180 question
+= strlen("hs/client/desc/id/");
2181 if (rend_valid_v2_service_id(question
)) {
2182 addr_type
= ONION_V2_HOSTNAME
;
2183 } else if (hs_address_is_valid(question
)) {
2184 addr_type
= ONION_V3_HOSTNAME
;
2186 *errmsg
= "Invalid address";
2190 if (addr_type
== ONION_V2_HOSTNAME
) {
2191 rend_cache_entry_t
*e
= NULL
;
2192 if (!rend_cache_lookup_entry(question
, -1, &e
)) {
2193 /* Descriptor found in cache */
2194 *answer
= tor_strdup(e
->desc
);
2196 *errmsg
= "Not found in cache";
2200 ed25519_public_key_t service_pk
;
2203 /* The check before this if/else makes sure of this. */
2204 tor_assert(addr_type
== ONION_V3_HOSTNAME
);
2206 if (hs_parse_address(question
, &service_pk
, NULL
, NULL
) < 0) {
2207 *errmsg
= "Invalid v3 address";
2211 desc
= hs_cache_lookup_encoded_as_client(&service_pk
);
2213 *answer
= tor_strdup(desc
);
2215 *errmsg
= "Not found in cache";
2219 } else if (!strcmpstart(question
, "hs/service/desc/id/")) {
2220 hostname_type_t addr_type
;
2222 question
+= strlen("hs/service/desc/id/");
2223 if (rend_valid_v2_service_id(question
)) {
2224 addr_type
= ONION_V2_HOSTNAME
;
2225 } else if (hs_address_is_valid(question
)) {
2226 addr_type
= ONION_V3_HOSTNAME
;
2228 *errmsg
= "Invalid address";
2231 rend_cache_entry_t
*e
= NULL
;
2233 if (addr_type
== ONION_V2_HOSTNAME
) {
2234 if (!rend_cache_lookup_v2_desc_as_service(question
, &e
)) {
2235 /* Descriptor found in cache */
2236 *answer
= tor_strdup(e
->desc
);
2238 *errmsg
= "Not found in cache";
2242 ed25519_public_key_t service_pk
;
2245 /* The check before this if/else makes sure of this. */
2246 tor_assert(addr_type
== ONION_V3_HOSTNAME
);
2248 if (hs_parse_address(question
, &service_pk
, NULL
, NULL
) < 0) {
2249 *errmsg
= "Invalid v3 address";
2253 desc
= hs_service_lookup_current_desc(&service_pk
);
2255 /* Newly allocated string, we have ownership. */
2258 *errmsg
= "Not found in cache";
2262 } else if (!strcmp(question
, "md/all")) {
2263 const smartlist_t
*nodes
= nodelist_get_list();
2266 if (smartlist_len(nodes
) == 0) {
2267 *answer
= tor_strdup("");
2271 smartlist_t
*microdescs
= smartlist_new();
2273 SMARTLIST_FOREACH_BEGIN(nodes
, node_t
*, n
) {
2274 if (n
->md
&& n
->md
->body
) {
2275 char *copy
= tor_strndup(n
->md
->body
, n
->md
->bodylen
);
2276 smartlist_add(microdescs
, copy
);
2278 } SMARTLIST_FOREACH_END(n
);
2280 *answer
= smartlist_join_strings(microdescs
, "", 0, NULL
);
2281 SMARTLIST_FOREACH(microdescs
, char *, md
, tor_free(md
));
2282 smartlist_free(microdescs
);
2283 } else if (!strcmpstart(question
, "md/id/")) {
2284 const node_t
*node
= node_get_by_hex_id(question
+strlen("md/id/"), 0);
2285 const microdesc_t
*md
= NULL
;
2286 if (node
) md
= node
->md
;
2287 if (md
&& md
->body
) {
2288 *answer
= tor_strndup(md
->body
, md
->bodylen
);
2290 } else if (!strcmpstart(question
, "md/name/")) {
2291 /* XXX Setting 'warn_if_unnamed' here is a bit silly -- the
2292 * warning goes to the user, not to the controller. */
2293 const node_t
*node
= node_get_by_nickname(question
+strlen("md/name/"), 0);
2294 /* XXXX duplicated code */
2295 const microdesc_t
*md
= NULL
;
2296 if (node
) md
= node
->md
;
2297 if (md
&& md
->body
) {
2298 *answer
= tor_strndup(md
->body
, md
->bodylen
);
2300 } else if (!strcmp(question
, "md/download-enabled")) {
2301 int r
= we_fetch_microdescriptors(get_options());
2302 tor_asprintf(answer
, "%d", !!r
);
2303 } else if (!strcmpstart(question
, "desc-annotations/id/")) {
2304 const routerinfo_t
*ri
= NULL
;
2305 const node_t
*node
=
2306 node_get_by_hex_id(question
+strlen("desc-annotations/id/"), 0);
2310 const char *annotations
=
2311 signed_descriptor_get_annotations(&ri
->cache_info
);
2313 *answer
= tor_strndup(annotations
,
2314 ri
->cache_info
.annotations_len
);
2316 } else if (!strcmpstart(question
, "dir/server/")) {
2317 size_t answer_len
= 0;
2319 smartlist_t
*descs
= smartlist_new();
2323 tor_asprintf(&url
, "/tor/%s", question
+4);
2324 res
= dirserv_get_routerdescs(descs
, url
, &msg
);
2326 log_warn(LD_CONTROL
, "getinfo '%s': %s", question
, msg
);
2327 smartlist_free(descs
);
2332 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
2333 answer_len
+= sd
->signed_descriptor_len
);
2334 cp
= *answer
= tor_malloc(answer_len
+1);
2335 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
2337 memcpy(cp
, signed_descriptor_get_body(sd
),
2338 sd
->signed_descriptor_len
);
2339 cp
+= sd
->signed_descriptor_len
;
2343 smartlist_free(descs
);
2344 } else if (!strcmpstart(question
, "dir/status/")) {
2345 *answer
= tor_strdup("");
2346 } else if (!strcmp(question
, "dir/status-vote/current/consensus")) { /* v3 */
2347 if (we_want_to_fetch_flavor(get_options(), FLAV_NS
)) {
2348 const cached_dir_t
*consensus
= dirserv_get_consensus("ns");
2350 *answer
= tor_strdup(consensus
->dir
);
2352 if (!*answer
) { /* try loading it from disk */
2353 *answer
= networkstatus_read_cached_consensus("ns");
2354 if (!*answer
) { /* generate an error */
2355 *errmsg
= "Could not open cached consensus. "
2356 "Make sure FetchUselessDescriptors is set to 1.";
2360 } else if (!strcmp(question
, "network-status")) { /* v1 */
2361 static int network_status_warned
= 0;
2362 if (!network_status_warned
) {
2363 log_warn(LD_CONTROL
, "GETINFO network-status is deprecated; it will "
2364 "go away in a future version of Tor.");
2365 network_status_warned
= 1;
2367 routerlist_t
*routerlist
= router_get_routerlist();
2368 if (!routerlist
|| !routerlist
->routers
||
2369 list_server_status_v1(routerlist
->routers
, answer
, 1) < 0) {
2372 } else if (!strcmpstart(question
, "extra-info/digest/")) {
2373 question
+= strlen("extra-info/digest/");
2374 if (strlen(question
) == HEX_DIGEST_LEN
) {
2376 signed_descriptor_t
*sd
= NULL
;
2377 if (base16_decode(d
, sizeof(d
), question
, strlen(question
))
2379 /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
2380 * but I don't want to risk affecting other parts of the code,
2381 * especially since the rules for using our own extrainfo (including
2382 * when it might be freed) are different from those for using one
2383 * we have downloaded. */
2384 if (router_extrainfo_digest_is_me(d
))
2385 sd
= &(router_get_my_extrainfo()->cache_info
);
2387 sd
= extrainfo_get_by_descriptor_digest(d
);
2390 const char *body
= signed_descriptor_get_body(sd
);
2392 *answer
= tor_strndup(body
, sd
->signed_descriptor_len
);
2400 /** Given a smartlist of 20-byte digests, return a newly allocated string
2401 * containing each of those digests in order, formatted in HEX, and terminated
2402 * with a newline. */
2404 digest_list_to_string(const smartlist_t
*sl
)
2409 /* Allow for newlines, and a \0 at the end */
2410 len
= smartlist_len(sl
) * (HEX_DIGEST_LEN
+ 1) + 1;
2411 result
= tor_malloc_zero(len
);
2414 SMARTLIST_FOREACH_BEGIN(sl
, const char *, digest
) {
2415 base16_encode(s
, HEX_DIGEST_LEN
+ 1, digest
, DIGEST_LEN
);
2416 s
[HEX_DIGEST_LEN
] = '\n';
2417 s
+= HEX_DIGEST_LEN
+ 1;
2418 } SMARTLIST_FOREACH_END(digest
);
2424 /** Turn a download_status_t into a human-readable description in a newly
2425 * allocated string. The format is specified in control-spec.txt, under
2426 * the documentation for "GETINFO download/..." . */
2428 download_status_to_string(const download_status_t
*dl
)
2431 char tbuf
[ISO_TIME_LEN
+1];
2432 const char *schedule_str
, *want_authority_str
;
2433 const char *increment_on_str
, *backoff_str
;
2436 /* Get some substrings of the eventual output ready */
2437 format_iso_time(tbuf
, download_status_get_next_attempt_at(dl
));
2439 switch (dl
->schedule
) {
2440 case DL_SCHED_GENERIC
:
2441 schedule_str
= "DL_SCHED_GENERIC";
2443 case DL_SCHED_CONSENSUS
:
2444 schedule_str
= "DL_SCHED_CONSENSUS";
2446 case DL_SCHED_BRIDGE
:
2447 schedule_str
= "DL_SCHED_BRIDGE";
2450 schedule_str
= "unknown";
2454 switch (dl
->want_authority
) {
2455 case DL_WANT_ANY_DIRSERVER
:
2456 want_authority_str
= "DL_WANT_ANY_DIRSERVER";
2458 case DL_WANT_AUTHORITY
:
2459 want_authority_str
= "DL_WANT_AUTHORITY";
2462 want_authority_str
= "unknown";
2466 switch (dl
->increment_on
) {
2467 case DL_SCHED_INCREMENT_FAILURE
:
2468 increment_on_str
= "DL_SCHED_INCREMENT_FAILURE";
2470 case DL_SCHED_INCREMENT_ATTEMPT
:
2471 increment_on_str
= "DL_SCHED_INCREMENT_ATTEMPT";
2474 increment_on_str
= "unknown";
2478 backoff_str
= "DL_SCHED_RANDOM_EXPONENTIAL";
2480 /* Now assemble them */
2482 "next-attempt-at %s\n"
2483 "n-download-failures %u\n"
2484 "n-download-attempts %u\n"
2486 "want-authority %s\n"
2489 "last-backoff-position %u\n"
2490 "last-delay-used %d\n",
2492 dl
->n_download_failures
,
2493 dl
->n_download_attempts
,
2498 dl
->last_backoff_position
,
2499 dl
->last_delay_used
);
2505 /** Handle the consensus download cases for getinfo_helper_downloads() */
2507 getinfo_helper_downloads_networkstatus(const char *flavor
,
2508 download_status_t
**dl_to_emit
,
2509 const char **errmsg
)
2512 * We get the one for the current bootstrapped status by default, or
2513 * take an extra /bootstrap or /running suffix
2515 if (strcmp(flavor
, "ns") == 0) {
2516 *dl_to_emit
= networkstatus_get_dl_status_by_flavor(FLAV_NS
);
2517 } else if (strcmp(flavor
, "ns/bootstrap") == 0) {
2518 *dl_to_emit
= networkstatus_get_dl_status_by_flavor_bootstrap(FLAV_NS
);
2519 } else if (strcmp(flavor
, "ns/running") == 0 ) {
2520 *dl_to_emit
= networkstatus_get_dl_status_by_flavor_running(FLAV_NS
);
2521 } else if (strcmp(flavor
, "microdesc") == 0) {
2522 *dl_to_emit
= networkstatus_get_dl_status_by_flavor(FLAV_MICRODESC
);
2523 } else if (strcmp(flavor
, "microdesc/bootstrap") == 0) {
2525 networkstatus_get_dl_status_by_flavor_bootstrap(FLAV_MICRODESC
);
2526 } else if (strcmp(flavor
, "microdesc/running") == 0) {
2528 networkstatus_get_dl_status_by_flavor_running(FLAV_MICRODESC
);
2530 *errmsg
= "Unknown flavor";
2534 /** Handle the cert download cases for getinfo_helper_downloads() */
2536 getinfo_helper_downloads_cert(const char *fp_sk_req
,
2537 download_status_t
**dl_to_emit
,
2538 smartlist_t
**digest_list
,
2539 const char **errmsg
)
2542 char id_digest
[DIGEST_LEN
];
2543 char sk_digest
[DIGEST_LEN
];
2546 * We have to handle four cases; fp_sk_req is the request with
2547 * a prefix of "downloads/cert/" snipped off.
2549 * Case 1: fp_sk_req = "fps"
2550 * - We should emit a digest_list with a list of all the identity
2551 * fingerprints that can be queried for certificate download status;
2552 * get it by calling list_authority_ids_with_downloads().
2554 * Case 2: fp_sk_req = "fp/<fp>" for some fingerprint fp
2555 * - We want the default certificate for this identity fingerprint's
2556 * download status; this is the download we get from URLs starting
2557 * in /fp/ on the directory server. We can get it with
2558 * id_only_download_status_for_authority_id().
2560 * Case 3: fp_sk_req = "fp/<fp>/sks" for some fingerprint fp
2561 * - We want a list of all signing key digests for this identity
2562 * fingerprint which can be queried for certificate download status.
2563 * Get it with list_sk_digests_for_authority_id().
2565 * Case 4: fp_sk_req = "fp/<fp>/<sk>" for some fingerprint fp and
2566 * signing key digest sk
2567 * - We want the download status for the certificate for this specific
2568 * signing key and fingerprint. These correspond to the ones we get
2569 * from URLs starting in /fp-sk/ on the directory server. Get it with
2570 * list_sk_digests_for_authority_id().
2573 if (strcmp(fp_sk_req
, "fps") == 0) {
2574 *digest_list
= list_authority_ids_with_downloads();
2575 if (!(*digest_list
)) {
2576 *errmsg
= "Failed to get list of authority identity digests (!)";
2578 } else if (!strcmpstart(fp_sk_req
, "fp/")) {
2579 fp_sk_req
+= strlen("fp/");
2580 /* Okay, look for another / to tell the fp from fp-sk cases */
2581 sk_req
= strchr(fp_sk_req
, '/');
2583 /* okay, split it here and try to parse <fp> */
2584 if (base16_decode(id_digest
, DIGEST_LEN
,
2585 fp_sk_req
, sk_req
- fp_sk_req
) == DIGEST_LEN
) {
2586 /* Skip past the '/' */
2588 if (strcmp(sk_req
, "sks") == 0) {
2589 /* We're asking for the list of signing key fingerprints */
2590 *digest_list
= list_sk_digests_for_authority_id(id_digest
);
2591 if (!(*digest_list
)) {
2592 *errmsg
= "Failed to get list of signing key digests for this "
2593 "authority identity digest";
2596 /* We've got a signing key digest */
2597 if (base16_decode(sk_digest
, DIGEST_LEN
,
2598 sk_req
, strlen(sk_req
)) == DIGEST_LEN
) {
2600 download_status_for_authority_id_and_sk(id_digest
, sk_digest
);
2601 if (!(*dl_to_emit
)) {
2602 *errmsg
= "Failed to get download status for this identity/"
2603 "signing key digest pair";
2606 *errmsg
= "That didn't look like a signing key digest";
2610 *errmsg
= "That didn't look like an identity digest";
2613 /* We're either in downloads/certs/fp/<fp>, or we can't parse <fp> */
2614 if (strlen(fp_sk_req
) == HEX_DIGEST_LEN
) {
2615 if (base16_decode(id_digest
, DIGEST_LEN
,
2616 fp_sk_req
, strlen(fp_sk_req
)) == DIGEST_LEN
) {
2617 *dl_to_emit
= id_only_download_status_for_authority_id(id_digest
);
2618 if (!(*dl_to_emit
)) {
2619 *errmsg
= "Failed to get download status for this authority "
2623 *errmsg
= "That didn't look like a digest";
2626 *errmsg
= "That didn't look like a digest";
2630 *errmsg
= "Unknown certificate download status query";
2634 /** Handle the routerdesc download cases for getinfo_helper_downloads() */
2636 getinfo_helper_downloads_desc(const char *desc_req
,
2637 download_status_t
**dl_to_emit
,
2638 smartlist_t
**digest_list
,
2639 const char **errmsg
)
2641 char desc_digest
[DIGEST_LEN
];
2643 * Two cases to handle here:
2645 * Case 1: desc_req = "descs"
2646 * - Emit a list of all router descriptor digests, which we get by
2647 * calling router_get_descriptor_digests(); this can return NULL
2648 * if we have no current ns-flavor consensus.
2650 * Case 2: desc_req = <fp>
2651 * - Check on the specified fingerprint and emit its download_status_t
2652 * using router_get_dl_status_by_descriptor_digest().
2655 if (strcmp(desc_req
, "descs") == 0) {
2656 *digest_list
= router_get_descriptor_digests();
2657 if (!(*digest_list
)) {
2658 *errmsg
= "We don't seem to have a networkstatus-flavored consensus";
2661 * Microdescs don't use the download_status_t mechanism, so we don't
2662 * answer queries about their downloads here; see microdesc.c.
2664 } else if (strlen(desc_req
) == HEX_DIGEST_LEN
) {
2665 if (base16_decode(desc_digest
, DIGEST_LEN
,
2666 desc_req
, strlen(desc_req
)) == DIGEST_LEN
) {
2667 /* Okay we got a digest-shaped thing; try asking for it */
2668 *dl_to_emit
= router_get_dl_status_by_descriptor_digest(desc_digest
);
2669 if (!(*dl_to_emit
)) {
2670 *errmsg
= "No such descriptor digest found";
2673 *errmsg
= "That didn't look like a digest";
2676 *errmsg
= "Unknown router descriptor download status query";
2680 /** Handle the bridge download cases for getinfo_helper_downloads() */
2682 getinfo_helper_downloads_bridge(const char *bridge_req
,
2683 download_status_t
**dl_to_emit
,
2684 smartlist_t
**digest_list
,
2685 const char **errmsg
)
2687 char bridge_digest
[DIGEST_LEN
];
2689 * Two cases to handle here:
2691 * Case 1: bridge_req = "bridges"
2692 * - Emit a list of all bridge identity digests, which we get by
2693 * calling list_bridge_identities(); this can return NULL if we are
2694 * not using bridges.
2696 * Case 2: bridge_req = <fp>
2697 * - Check on the specified fingerprint and emit its download_status_t
2698 * using get_bridge_dl_status_by_id().
2701 if (strcmp(bridge_req
, "bridges") == 0) {
2702 *digest_list
= list_bridge_identities();
2703 if (!(*digest_list
)) {
2704 *errmsg
= "We don't seem to be using bridges";
2706 } else if (strlen(bridge_req
) == HEX_DIGEST_LEN
) {
2707 if (base16_decode(bridge_digest
, DIGEST_LEN
,
2708 bridge_req
, strlen(bridge_req
)) == DIGEST_LEN
) {
2709 /* Okay we got a digest-shaped thing; try asking for it */
2710 *dl_to_emit
= get_bridge_dl_status_by_id(bridge_digest
);
2711 if (!(*dl_to_emit
)) {
2712 *errmsg
= "No such bridge identity digest found";
2715 *errmsg
= "That didn't look like a digest";
2718 *errmsg
= "Unknown bridge descriptor download status query";
2722 /** Implementation helper for GETINFO: knows the answers for questions about
2723 * download status information. */
2725 getinfo_helper_downloads(control_connection_t
*control_conn
,
2726 const char *question
, char **answer
,
2727 const char **errmsg
)
2729 download_status_t
*dl_to_emit
= NULL
;
2730 smartlist_t
*digest_list
= NULL
;
2732 /* Assert args are sane */
2733 tor_assert(control_conn
!= NULL
);
2734 tor_assert(question
!= NULL
);
2735 tor_assert(answer
!= NULL
);
2736 tor_assert(errmsg
!= NULL
);
2738 /* We check for this later to see if we should supply a default */
2741 /* Are we after networkstatus downloads? */
2742 if (!strcmpstart(question
, "downloads/networkstatus/")) {
2743 getinfo_helper_downloads_networkstatus(
2744 question
+ strlen("downloads/networkstatus/"),
2745 &dl_to_emit
, errmsg
);
2747 } else if (!strcmpstart(question
, "downloads/cert/")) {
2748 getinfo_helper_downloads_cert(
2749 question
+ strlen("downloads/cert/"),
2750 &dl_to_emit
, &digest_list
, errmsg
);
2751 /* Router descriptors? */
2752 } else if (!strcmpstart(question
, "downloads/desc/")) {
2753 getinfo_helper_downloads_desc(
2754 question
+ strlen("downloads/desc/"),
2755 &dl_to_emit
, &digest_list
, errmsg
);
2756 /* Bridge descriptors? */
2757 } else if (!strcmpstart(question
, "downloads/bridge/")) {
2758 getinfo_helper_downloads_bridge(
2759 question
+ strlen("downloads/bridge/"),
2760 &dl_to_emit
, &digest_list
, errmsg
);
2762 *errmsg
= "Unknown download status query";
2766 *answer
= download_status_to_string(dl_to_emit
);
2769 } else if (digest_list
) {
2770 *answer
= digest_list_to_string(digest_list
);
2771 SMARTLIST_FOREACH(digest_list
, void *, s
, tor_free(s
));
2772 smartlist_free(digest_list
);
2777 *errmsg
= "Unknown error";
2784 /** Allocate and return a description of <b>circ</b>'s current status,
2785 * including its path (if any). */
2787 circuit_describe_status_for_controller(origin_circuit_t
*circ
)
2790 smartlist_t
*descparts
= smartlist_new();
2793 char *vpath
= circuit_list_path_for_controller(circ
);
2795 smartlist_add(descparts
, vpath
);
2797 tor_free(vpath
); /* empty path; don't put an extra space in the result */
2802 cpath_build_state_t
*build_state
= circ
->build_state
;
2803 smartlist_t
*flaglist
= smartlist_new();
2804 char *flaglist_joined
;
2806 if (build_state
->onehop_tunnel
)
2807 smartlist_add(flaglist
, (void *)"ONEHOP_TUNNEL");
2808 if (build_state
->is_internal
)
2809 smartlist_add(flaglist
, (void *)"IS_INTERNAL");
2810 if (build_state
->need_capacity
)
2811 smartlist_add(flaglist
, (void *)"NEED_CAPACITY");
2812 if (build_state
->need_uptime
)
2813 smartlist_add(flaglist
, (void *)"NEED_UPTIME");
2815 /* Only emit a BUILD_FLAGS argument if it will have a non-empty value. */
2816 if (smartlist_len(flaglist
)) {
2817 flaglist_joined
= smartlist_join_strings(flaglist
, ",", 0, NULL
);
2819 smartlist_add_asprintf(descparts
, "BUILD_FLAGS=%s", flaglist_joined
);
2821 tor_free(flaglist_joined
);
2824 smartlist_free(flaglist
);
2827 smartlist_add_asprintf(descparts
, "PURPOSE=%s",
2828 circuit_purpose_to_controller_string(circ
->base_
.purpose
));
2831 const char *hs_state
=
2832 circuit_purpose_to_controller_hs_state_string(circ
->base_
.purpose
);
2834 if (hs_state
!= NULL
) {
2835 smartlist_add_asprintf(descparts
, "HS_STATE=%s", hs_state
);
2839 if (circ
->rend_data
!= NULL
|| circ
->hs_ident
!= NULL
) {
2840 char addr
[HS_SERVICE_ADDR_LEN_BASE32
+ 1];
2841 const char *onion_address
;
2842 if (circ
->rend_data
) {
2843 onion_address
= rend_data_get_address(circ
->rend_data
);
2845 hs_build_address(&circ
->hs_ident
->identity_pk
, HS_VERSION_THREE
, addr
);
2846 onion_address
= addr
;
2848 smartlist_add_asprintf(descparts
, "REND_QUERY=%s", onion_address
);
2852 char tbuf
[ISO_TIME_USEC_LEN
+1];
2853 format_iso_time_nospace_usec(tbuf
, &circ
->base_
.timestamp_created
);
2855 smartlist_add_asprintf(descparts
, "TIME_CREATED=%s", tbuf
);
2858 // Show username and/or password if available.
2859 if (circ
->socks_username_len
> 0) {
2860 char* socks_username_escaped
= esc_for_log_len(circ
->socks_username
,
2861 (size_t) circ
->socks_username_len
);
2862 smartlist_add_asprintf(descparts
, "SOCKS_USERNAME=%s",
2863 socks_username_escaped
);
2864 tor_free(socks_username_escaped
);
2866 if (circ
->socks_password_len
> 0) {
2867 char* socks_password_escaped
= esc_for_log_len(circ
->socks_password
,
2868 (size_t) circ
->socks_password_len
);
2869 smartlist_add_asprintf(descparts
, "SOCKS_PASSWORD=%s",
2870 socks_password_escaped
);
2871 tor_free(socks_password_escaped
);
2874 rv
= smartlist_join_strings(descparts
, " ", 0, NULL
);
2876 SMARTLIST_FOREACH(descparts
, char *, cp
, tor_free(cp
));
2877 smartlist_free(descparts
);
2882 /** Implementation helper for GETINFO: knows how to generate summaries of the
2883 * current states of things we send events about. */
2885 getinfo_helper_events(control_connection_t
*control_conn
,
2886 const char *question
, char **answer
,
2887 const char **errmsg
)
2889 const or_options_t
*options
= get_options();
2890 (void) control_conn
;
2891 if (!strcmp(question
, "circuit-status")) {
2892 smartlist_t
*status
= smartlist_new();
2893 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t
*, circ_
) {
2894 origin_circuit_t
*circ
;
2897 if (! CIRCUIT_IS_ORIGIN(circ_
) || circ_
->marked_for_close
)
2899 circ
= TO_ORIGIN_CIRCUIT(circ_
);
2901 if (circ
->base_
.state
== CIRCUIT_STATE_OPEN
)
2903 else if (circ
->base_
.state
== CIRCUIT_STATE_GUARD_WAIT
)
2904 state
= "GUARD_WAIT";
2905 else if (circ
->cpath
)
2910 circdesc
= circuit_describe_status_for_controller(circ
);
2912 smartlist_add_asprintf(status
, "%lu %s%s%s",
2913 (unsigned long)circ
->global_identifier
,
2914 state
, *circdesc
? " " : "", circdesc
);
2917 SMARTLIST_FOREACH_END(circ_
);
2918 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
2919 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
2920 smartlist_free(status
);
2921 } else if (!strcmp(question
, "stream-status")) {
2922 smartlist_t
*conns
= get_connection_array();
2923 smartlist_t
*status
= smartlist_new();
2925 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
2927 entry_connection_t
*conn
;
2929 origin_circuit_t
*origin_circ
= NULL
;
2930 if (base_conn
->type
!= CONN_TYPE_AP
||
2931 base_conn
->marked_for_close
||
2932 base_conn
->state
== AP_CONN_STATE_SOCKS_WAIT
||
2933 base_conn
->state
== AP_CONN_STATE_NATD_WAIT
)
2935 conn
= TO_ENTRY_CONN(base_conn
);
2936 switch (base_conn
->state
)
2938 case AP_CONN_STATE_CONTROLLER_WAIT
:
2939 case AP_CONN_STATE_CIRCUIT_WAIT
:
2940 if (conn
->socks_request
&&
2941 SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
))
2942 state
= "NEWRESOLVE";
2946 case AP_CONN_STATE_RENDDESC_WAIT
:
2947 case AP_CONN_STATE_CONNECT_WAIT
:
2948 state
= "SENTCONNECT"; break;
2949 case AP_CONN_STATE_RESOLVE_WAIT
:
2950 state
= "SENTRESOLVE"; break;
2951 case AP_CONN_STATE_OPEN
:
2952 state
= "SUCCEEDED"; break;
2954 log_warn(LD_BUG
, "Asked for stream in unknown state %d",
2958 circ
= circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn
));
2959 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
2960 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
2961 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
2962 smartlist_add_asprintf(status
, "%lu %s %lu %s",
2963 (unsigned long) base_conn
->global_identifier
,state
,
2965 (unsigned long)origin_circ
->global_identifier
: 0ul,
2967 } SMARTLIST_FOREACH_END(base_conn
);
2968 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
2969 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
2970 smartlist_free(status
);
2971 } else if (!strcmp(question
, "orconn-status")) {
2972 smartlist_t
*conns
= get_connection_array();
2973 smartlist_t
*status
= smartlist_new();
2974 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
2977 or_connection_t
*conn
;
2978 if (base_conn
->type
!= CONN_TYPE_OR
|| base_conn
->marked_for_close
)
2980 conn
= TO_OR_CONN(base_conn
);
2981 if (conn
->base_
.state
== OR_CONN_STATE_OPEN
)
2982 state
= "CONNECTED";
2983 else if (conn
->nickname
)
2987 orconn_target_get_name(name
, sizeof(name
), conn
);
2988 smartlist_add_asprintf(status
, "%s %s", name
, state
);
2989 } SMARTLIST_FOREACH_END(base_conn
);
2990 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
2991 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
2992 smartlist_free(status
);
2993 } else if (!strcmpstart(question
, "address-mappings/")) {
2994 time_t min_e
, max_e
;
2995 smartlist_t
*mappings
;
2996 question
+= strlen("address-mappings/");
2997 if (!strcmp(question
, "all")) {
2998 min_e
= 0; max_e
= TIME_MAX
;
2999 } else if (!strcmp(question
, "cache")) {
3000 min_e
= 2; max_e
= TIME_MAX
;
3001 } else if (!strcmp(question
, "config")) {
3002 min_e
= 0; max_e
= 0;
3003 } else if (!strcmp(question
, "control")) {
3004 min_e
= 1; max_e
= 1;
3008 mappings
= smartlist_new();
3009 addressmap_get_mappings(mappings
, min_e
, max_e
, 1);
3010 *answer
= smartlist_join_strings(mappings
, "\r\n", 0, NULL
);
3011 SMARTLIST_FOREACH(mappings
, char *, cp
, tor_free(cp
));
3012 smartlist_free(mappings
);
3013 } else if (!strcmpstart(question
, "status/")) {
3014 /* Note that status/ is not a catch-all for events; there's only supposed
3015 * to be a status GETINFO if there's a corresponding STATUS event. */
3016 if (!strcmp(question
, "status/circuit-established")) {
3017 *answer
= tor_strdup(have_completed_a_circuit() ? "1" : "0");
3018 } else if (!strcmp(question
, "status/enough-dir-info")) {
3019 *answer
= tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
3020 } else if (!strcmp(question
, "status/good-server-descriptor") ||
3021 !strcmp(question
, "status/accepted-server-descriptor")) {
3022 /* They're equivalent for now, until we can figure out how to make
3023 * good-server-descriptor be what we want. See comment in
3024 * control-spec.txt. */
3025 *answer
= tor_strdup(directories_have_accepted_server_descriptor()
3027 } else if (!strcmp(question
, "status/reachability-succeeded/or")) {
3028 *answer
= tor_strdup(check_whether_orport_reachable(options
) ?
3030 } else if (!strcmp(question
, "status/reachability-succeeded/dir")) {
3031 *answer
= tor_strdup(check_whether_dirport_reachable(options
) ?
3033 } else if (!strcmp(question
, "status/reachability-succeeded")) {
3034 tor_asprintf(answer
, "OR=%d DIR=%d",
3035 check_whether_orport_reachable(options
) ? 1 : 0,
3036 check_whether_dirport_reachable(options
) ? 1 : 0);
3037 } else if (!strcmp(question
, "status/bootstrap-phase")) {
3038 *answer
= tor_strdup(last_sent_bootstrap_message
);
3039 } else if (!strcmpstart(question
, "status/version/")) {
3040 int is_server
= server_mode(options
);
3041 networkstatus_t
*c
= networkstatus_get_latest_consensus();
3042 version_status_t status
;
3043 const char *recommended
;
3045 recommended
= is_server
? c
->server_versions
: c
->client_versions
;
3046 status
= tor_version_is_obsolete(VERSION
, recommended
);
3049 status
= VS_UNKNOWN
;
3052 if (!strcmp(question
, "status/version/recommended")) {
3053 *answer
= tor_strdup(recommended
);
3056 if (!strcmp(question
, "status/version/current")) {
3059 case VS_RECOMMENDED
: *answer
= tor_strdup("recommended"); break;
3060 case VS_OLD
: *answer
= tor_strdup("obsolete"); break;
3061 case VS_NEW
: *answer
= tor_strdup("new"); break;
3062 case VS_NEW_IN_SERIES
: *answer
= tor_strdup("new in series"); break;
3063 case VS_UNRECOMMENDED
: *answer
= tor_strdup("unrecommended"); break;
3064 case VS_EMPTY
: *answer
= tor_strdup("none recommended"); break;
3065 case VS_UNKNOWN
: *answer
= tor_strdup("unknown"); break;
3066 default: tor_fragile_assert();
3068 } else if (!strcmp(question
, "status/version/num-versioning") ||
3069 !strcmp(question
, "status/version/num-concurring")) {
3070 tor_asprintf(answer
, "%d", get_n_authorities(V3_DIRINFO
));
3071 log_warn(LD_GENERAL
, "%s is deprecated; it no longer gives useful "
3072 "information", question
);
3074 } else if (!strcmp(question
, "status/clients-seen")) {
3075 char *bridge_stats
= geoip_get_bridge_stats_controller(time(NULL
));
3076 if (!bridge_stats
) {
3077 *errmsg
= "No bridge-client stats available";
3080 *answer
= bridge_stats
;
3081 } else if (!strcmp(question
, "status/fresh-relay-descs")) {
3082 if (!server_mode(options
)) {
3083 *errmsg
= "Only relays have descriptors";
3088 if (router_build_fresh_descriptor(&r
, &e
) < 0) {
3089 *errmsg
= "Error generating descriptor";
3092 size_t size
= r
->cache_info
.signed_descriptor_len
+ 1;
3094 size
+= e
->cache_info
.signed_descriptor_len
+ 1;
3096 tor_assert(r
->cache_info
.signed_descriptor_len
);
3097 char *descs
= tor_malloc(size
);
3099 memcpy(cp
, signed_descriptor_get_body(&r
->cache_info
),
3100 r
->cache_info
.signed_descriptor_len
);
3101 cp
+= r
->cache_info
.signed_descriptor_len
- 1;
3103 if (cp
[0] == '\0') {
3105 } else if (cp
[0] != '\n') {
3109 memcpy(cp
, signed_descriptor_get_body(&e
->cache_info
),
3110 e
->cache_info
.signed_descriptor_len
);
3111 cp
+= e
->cache_info
.signed_descriptor_len
- 1;
3113 if (cp
[0] == '\n') {
3115 } else if (cp
[0] != '\0') {
3128 /** Implementation helper for GETINFO: knows how to enumerate hidden services
3129 * created via the control port. */
3131 getinfo_helper_onions(control_connection_t
*control_conn
,
3132 const char *question
, char **answer
,
3133 const char **errmsg
)
3135 smartlist_t
*onion_list
= NULL
;
3136 (void) errmsg
; /* no errors from this method */
3138 if (control_conn
&& !strcmp(question
, "onions/current")) {
3139 onion_list
= control_conn
->ephemeral_onion_services
;
3140 } else if (!strcmp(question
, "onions/detached")) {
3141 onion_list
= detached_onion_services
;
3145 if (!onion_list
|| smartlist_len(onion_list
) == 0) {
3147 *answer
= tor_strdup("");
3151 *answer
= smartlist_join_strings(onion_list
, "\r\n", 0, NULL
);
3158 /** Implementation helper for GETINFO: answers queries about network
3161 getinfo_helper_liveness(control_connection_t
*control_conn
,
3162 const char *question
, char **answer
,
3163 const char **errmsg
)
3167 if (strcmp(question
, "network-liveness") == 0) {
3168 if (get_cached_network_liveness()) {
3169 *answer
= tor_strdup("up");
3171 *answer
= tor_strdup("down");
3178 /** Implementation helper for GETINFO: answers queries about shared random
3181 getinfo_helper_sr(control_connection_t
*control_conn
,
3182 const char *question
, char **answer
,
3183 const char **errmsg
)
3185 (void) control_conn
;
3188 if (!strcmp(question
, "sr/current")) {
3189 *answer
= sr_get_current_for_control();
3190 } else if (!strcmp(question
, "sr/previous")) {
3191 *answer
= sr_get_previous_for_control();
3193 /* Else statement here is unrecognized key so do nothing. */
3198 /** Callback function for GETINFO: on a given control connection, try to
3199 * answer the question <b>q</b> and store the newly-allocated answer in
3200 * *<b>a</b>. If an internal error occurs, return -1 and optionally set
3201 * *<b>error_out</b> to point to an error message to be delivered to the
3202 * controller. On success, _or if the key is not recognized_, return 0. Do not
3203 * set <b>a</b> if the key is not recognized but you may set <b>error_out</b>
3204 * to improve the error message.
3206 typedef int (*getinfo_helper_t
)(control_connection_t
*,
3207 const char *q
, char **a
,
3208 const char **error_out
);
3210 /** A single item for the GETINFO question-to-answer-function table. */
3211 typedef struct getinfo_item_t
{
3212 const char *varname
; /**< The value (or prefix) of the question. */
3213 getinfo_helper_t fn
; /**< The function that knows the answer: NULL if
3214 * this entry is documentation-only. */
3215 const char *desc
; /**< Description of the variable. */
3216 int is_prefix
; /** Must varname match exactly, or must it be a prefix? */
3219 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
3220 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
3221 #define DOC(name, desc) { name, NULL, desc, 0 }
3223 /** Table mapping questions accepted by GETINFO to the functions that know how
3224 * to answer them. */
3225 static const getinfo_item_t getinfo_items
[] = {
3226 ITEM("version", misc
, "The current version of Tor."),
3227 ITEM("bw-event-cache", misc
, "Cached BW events for a short interval."),
3228 ITEM("config-file", misc
, "Current location of the \"torrc\" file."),
3229 ITEM("config-defaults-file", misc
, "Current location of the defaults file."),
3230 ITEM("config-text", misc
,
3231 "Return the string that would be written by a saveconf command."),
3232 ITEM("config-can-saveconf", misc
,
3233 "Is it possible to save the configuration to the \"torrc\" file?"),
3234 ITEM("accounting/bytes", accounting
,
3235 "Number of bytes read/written so far in the accounting interval."),
3236 ITEM("accounting/bytes-left", accounting
,
3237 "Number of bytes left to write/read so far in the accounting interval."),
3238 ITEM("accounting/enabled", accounting
, "Is accounting currently enabled?"),
3239 ITEM("accounting/hibernating", accounting
, "Are we hibernating or awake?"),
3240 ITEM("accounting/interval-start", accounting
,
3241 "Time when the accounting period starts."),
3242 ITEM("accounting/interval-end", accounting
,
3243 "Time when the accounting period ends."),
3244 ITEM("accounting/interval-wake", accounting
,
3245 "Time to wake up in this accounting period."),
3246 ITEM("helper-nodes", entry_guards
, NULL
), /* deprecated */
3247 ITEM("entry-guards", entry_guards
,
3248 "Which nodes are we using as entry guards?"),
3249 ITEM("fingerprint", misc
, NULL
),
3250 PREFIX("config/", config
, "Current configuration values."),
3252 "List of configuration options, types, and documentation."),
3253 DOC("config/defaults",
3254 "List of default values for configuration options. "
3255 "See also config/names"),
3256 PREFIX("current-time/", current_time
, "Current time."),
3257 DOC("current-time/local", "Current time on the local system."),
3258 DOC("current-time/utc", "Current UTC time."),
3259 PREFIX("downloads/networkstatus/", downloads
,
3260 "Download statuses for networkstatus objects"),
3261 DOC("downloads/networkstatus/ns",
3262 "Download status for current-mode networkstatus download"),
3263 DOC("downloads/networkstatus/ns/bootstrap",
3264 "Download status for bootstrap-time networkstatus download"),
3265 DOC("downloads/networkstatus/ns/running",
3266 "Download status for run-time networkstatus download"),
3267 DOC("downloads/networkstatus/microdesc",
3268 "Download status for current-mode microdesc download"),
3269 DOC("downloads/networkstatus/microdesc/bootstrap",
3270 "Download status for bootstrap-time microdesc download"),
3271 DOC("downloads/networkstatus/microdesc/running",
3272 "Download status for run-time microdesc download"),
3273 PREFIX("downloads/cert/", downloads
,
3274 "Download statuses for certificates, by id fingerprint and "
3276 DOC("downloads/cert/fps",
3277 "List of authority fingerprints for which any download statuses "
3279 DOC("downloads/cert/fp/<fp>",
3280 "Download status for <fp> with the default signing key; corresponds "
3281 "to /fp/ URLs on directory server."),
3282 DOC("downloads/cert/fp/<fp>/sks",
3283 "List of signing keys for which specific download statuses are "
3284 "available for this id fingerprint"),
3285 DOC("downloads/cert/fp/<fp>/<sk>",
3286 "Download status for <fp> with signing key <sk>; corresponds "
3287 "to /fp-sk/ URLs on directory server."),
3288 PREFIX("downloads/desc/", downloads
,
3289 "Download statuses for router descriptors, by descriptor digest"),
3290 DOC("downloads/desc/descs",
3291 "Return a list of known router descriptor digests"),
3292 DOC("downloads/desc/<desc>",
3293 "Return a download status for a given descriptor digest"),
3294 PREFIX("downloads/bridge/", downloads
,
3295 "Download statuses for bridge descriptors, by bridge identity "
3297 DOC("downloads/bridge/bridges",
3298 "Return a list of configured bridge identity digests with download "
3300 DOC("downloads/bridge/<desc>",
3301 "Return a download status for a given bridge identity digest"),
3302 ITEM("info/names", misc
,
3303 "List of GETINFO options, types, and documentation."),
3304 ITEM("events/names", misc
,
3305 "Events that the controller can ask for with SETEVENTS."),
3306 ITEM("signal/names", misc
, "Signal names recognized by the SIGNAL command"),
3307 ITEM("features/names", misc
, "What arguments can USEFEATURE take?"),
3308 PREFIX("desc/id/", dir
, "Router descriptors by ID."),
3309 PREFIX("desc/name/", dir
, "Router descriptors by nickname."),
3310 ITEM("desc/all-recent", dir
,
3311 "All non-expired, non-superseded router descriptors."),
3312 ITEM("desc/download-enabled", dir
,
3313 "Do we try to download router descriptors?"),
3314 ITEM("desc/all-recent-extrainfo-hack", dir
, NULL
), /* Hack. */
3315 ITEM("md/all", dir
, "All known microdescriptors."),
3316 PREFIX("md/id/", dir
, "Microdescriptors by ID"),
3317 PREFIX("md/name/", dir
, "Microdescriptors by name"),
3318 ITEM("md/download-enabled", dir
,
3319 "Do we try to download microdescriptors?"),
3320 PREFIX("extra-info/digest/", dir
, "Extra-info documents by digest."),
3321 PREFIX("hs/client/desc/id", dir
,
3322 "Hidden Service descriptor in client's cache by onion."),
3323 PREFIX("hs/service/desc/id/", dir
,
3324 "Hidden Service descriptor in services's cache by onion."),
3325 PREFIX("net/listeners/", listeners
, "Bound addresses by type"),
3326 ITEM("ns/all", networkstatus
,
3327 "Brief summary of router status (v2 directory format)"),
3328 PREFIX("ns/id/", networkstatus
,
3329 "Brief summary of router status by ID (v2 directory format)."),
3330 PREFIX("ns/name/", networkstatus
,
3331 "Brief summary of router status by nickname (v2 directory format)."),
3332 PREFIX("ns/purpose/", networkstatus
,
3333 "Brief summary of router status by purpose (v2 directory format)."),
3334 PREFIX("consensus/", networkstatus
,
3335 "Information about and from the ns consensus."),
3336 ITEM("network-status", dir
,
3337 "Brief summary of router status (v1 directory format)"),
3338 ITEM("network-liveness", liveness
,
3339 "Current opinion on whether the network is live"),
3340 ITEM("circuit-status", events
, "List of current circuits originating here."),
3341 ITEM("stream-status", events
,"List of current streams."),
3342 ITEM("orconn-status", events
, "A list of current OR connections."),
3343 ITEM("dormant", misc
,
3344 "Is Tor dormant (not building circuits because it's idle)?"),
3345 PREFIX("address-mappings/", events
, NULL
),
3346 DOC("address-mappings/all", "Current address mappings."),
3347 DOC("address-mappings/cache", "Current cached DNS replies."),
3348 DOC("address-mappings/config",
3349 "Current address mappings from configuration."),
3350 DOC("address-mappings/control", "Current address mappings from controller."),
3351 PREFIX("status/", events
, NULL
),
3352 DOC("status/circuit-established",
3353 "Whether we think client functionality is working."),
3354 DOC("status/enough-dir-info",
3355 "Whether we have enough up-to-date directory information to build "
3357 DOC("status/bootstrap-phase",
3358 "The last bootstrap phase status event that Tor sent."),
3359 DOC("status/clients-seen",
3360 "Breakdown of client countries seen by a bridge."),
3361 DOC("status/fresh-relay-descs",
3362 "A fresh relay/ei descriptor pair for Tor's current state. Not stored."),
3363 DOC("status/version/recommended", "List of currently recommended versions."),
3364 DOC("status/version/current", "Status of the current version."),
3365 DOC("status/version/num-versioning", "Number of versioning authorities."),
3366 DOC("status/version/num-concurring",
3367 "Number of versioning authorities agreeing on the status of the "
3369 ITEM("address", misc
, "IP address of this Tor host, if we can guess it."),
3370 ITEM("traffic/read", misc
,"Bytes read since the process was started."),
3371 ITEM("traffic/written", misc
,
3372 "Bytes written since the process was started."),
3373 ITEM("uptime", misc
, "Uptime of the Tor daemon in seconds."),
3374 ITEM("process/pid", misc
, "Process id belonging to the main tor process."),
3375 ITEM("process/uid", misc
, "User id running the tor process."),
3376 ITEM("process/user", misc
,
3377 "Username under which the tor process is running."),
3378 ITEM("process/descriptor-limit", misc
, "File descriptor limit."),
3379 ITEM("limits/max-mem-in-queues", misc
, "Actual limit on memory in queues"),
3380 PREFIX("desc-annotations/id/", dir
, "Router annotations by hexdigest."),
3381 PREFIX("dir/server/", dir
,"Router descriptors as retrieved from a DirPort."),
3382 PREFIX("dir/status/", dir
,
3383 "v2 networkstatus docs as retrieved from a DirPort."),
3384 ITEM("dir/status-vote/current/consensus", dir
,
3385 "v3 Networkstatus consensus as retrieved from a DirPort."),
3386 ITEM("exit-policy/default", policies
,
3387 "The default value appended to the configured exit policy."),
3388 ITEM("exit-policy/reject-private/default", policies
,
3389 "The default rules appended to the configured exit policy by"
3390 " ExitPolicyRejectPrivate."),
3391 ITEM("exit-policy/reject-private/relay", policies
,
3392 "The relay-specific rules appended to the configured exit policy by"
3393 " ExitPolicyRejectPrivate and/or ExitPolicyRejectLocalInterfaces."),
3394 ITEM("exit-policy/full", policies
, "The entire exit policy of onion router"),
3395 ITEM("exit-policy/ipv4", policies
, "IPv4 parts of exit policy"),
3396 ITEM("exit-policy/ipv6", policies
, "IPv6 parts of exit policy"),
3397 PREFIX("ip-to-country/", geoip
, "Perform a GEOIP lookup"),
3398 ITEM("onions/current", onions
,
3399 "Onion services owned by the current control connection."),
3400 ITEM("onions/detached", onions
,
3401 "Onion services detached from the control connection."),
3402 ITEM("sr/current", sr
, "Get current shared random value."),
3403 ITEM("sr/previous", sr
, "Get previous shared random value."),
3404 { NULL
, NULL
, NULL
, 0 }
3407 /** Allocate and return a list of recognized GETINFO options. */
3409 list_getinfo_options(void)
3412 smartlist_t
*lines
= smartlist_new();
3414 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
3415 if (!getinfo_items
[i
].desc
)
3418 smartlist_add_asprintf(lines
, "%s%s -- %s\n",
3419 getinfo_items
[i
].varname
,
3420 getinfo_items
[i
].is_prefix
? "*" : "",
3421 getinfo_items
[i
].desc
);
3423 smartlist_sort_strings(lines
);
3425 ans
= smartlist_join_strings(lines
, "", 0, NULL
);
3426 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
3427 smartlist_free(lines
);
3432 /** Lookup the 'getinfo' entry <b>question</b>, and return
3433 * the answer in <b>*answer</b> (or NULL if key not recognized).
3434 * Return 0 if success or unrecognized, or -1 if recognized but
3435 * internal error. */
3437 handle_getinfo_helper(control_connection_t
*control_conn
,
3438 const char *question
, char **answer
,
3439 const char **err_out
)
3442 *answer
= NULL
; /* unrecognized key by default */
3444 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
3446 if (getinfo_items
[i
].is_prefix
)
3447 match
= !strcmpstart(question
, getinfo_items
[i
].varname
);
3449 match
= !strcmp(question
, getinfo_items
[i
].varname
);
3451 tor_assert(getinfo_items
[i
].fn
);
3452 return getinfo_items
[i
].fn(control_conn
, question
, answer
, err_out
);
3456 return 0; /* unrecognized */
3459 /** Called when we receive a GETINFO command. Try to fetch all requested
3460 * information, and reply with information or error message. */
3462 handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
3465 smartlist_t
*questions
= smartlist_new();
3466 smartlist_t
*answers
= smartlist_new();
3467 smartlist_t
*unrecognized
= smartlist_new();
3470 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
3472 smartlist_split_string(questions
, body
, " ",
3473 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3474 SMARTLIST_FOREACH_BEGIN(questions
, const char *, q
) {
3475 const char *errmsg
= NULL
;
3477 if (handle_getinfo_helper(conn
, q
, &ans
, &errmsg
) < 0) {
3479 errmsg
= "Internal error";
3480 connection_printf_to_buf(conn
, "551 %s\r\n", errmsg
);
3484 if (errmsg
) /* use provided error message */
3485 smartlist_add_strdup(unrecognized
, errmsg
);
3486 else /* use default error message */
3487 smartlist_add_asprintf(unrecognized
, "Unrecognized key \"%s\"", q
);
3489 smartlist_add_strdup(answers
, q
);
3490 smartlist_add(answers
, ans
);
3492 } SMARTLIST_FOREACH_END(q
);
3494 if (smartlist_len(unrecognized
)) {
3495 /* control-spec section 2.3, mid-reply '-' or end of reply ' ' */
3496 for (i
=0; i
< smartlist_len(unrecognized
)-1; ++i
)
3497 connection_printf_to_buf(conn
,
3499 (char *)smartlist_get(unrecognized
, i
));
3501 connection_printf_to_buf(conn
,
3503 (char *)smartlist_get(unrecognized
, i
));
3507 for (i
= 0; i
< smartlist_len(answers
); i
+= 2) {
3508 char *k
= smartlist_get(answers
, i
);
3509 char *v
= smartlist_get(answers
, i
+1);
3510 if (!strchr(v
, '\n') && !strchr(v
, '\r')) {
3511 connection_printf_to_buf(conn
, "250-%s=", k
);
3512 connection_write_str_to_buf(v
, conn
);
3513 connection_write_str_to_buf("\r\n", conn
);
3517 esc_len
= write_escaped_data(v
, strlen(v
), &esc
);
3518 connection_printf_to_buf(conn
, "250+%s=\r\n", k
);
3519 connection_buf_add(esc
, esc_len
, TO_CONN(conn
));
3523 connection_write_str_to_buf("250 OK\r\n", conn
);
3526 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
3527 smartlist_free(answers
);
3528 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
3529 smartlist_free(questions
);
3530 SMARTLIST_FOREACH(unrecognized
, char *, cp
, tor_free(cp
));
3531 smartlist_free(unrecognized
);
3536 /** Given a string, convert it to a circuit purpose. */
3538 circuit_purpose_from_string(const char *string
)
3540 if (!strcasecmpstart(string
, "purpose="))
3541 string
+= strlen("purpose=");
3543 if (!strcasecmp(string
, "general"))
3544 return CIRCUIT_PURPOSE_C_GENERAL
;
3545 else if (!strcasecmp(string
, "controller"))
3546 return CIRCUIT_PURPOSE_CONTROLLER
;
3548 return CIRCUIT_PURPOSE_UNKNOWN
;
3551 /** Return a newly allocated smartlist containing the arguments to the command
3552 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
3553 * or if <b>max_args</b> is nonnegative and there are more than
3554 * <b>max_args</b> arguments, send a 512 error to the controller, using
3555 * <b>command</b> as the command name in the error message. */
3556 static smartlist_t
*
3557 getargs_helper(const char *command
, control_connection_t
*conn
,
3558 const char *body
, int min_args
, int max_args
)
3560 smartlist_t
*args
= smartlist_new();
3561 smartlist_split_string(args
, body
, " ",
3562 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3563 if (smartlist_len(args
) < min_args
) {
3564 connection_printf_to_buf(conn
, "512 Missing argument to %s\r\n",command
);
3566 } else if (max_args
>= 0 && smartlist_len(args
) > max_args
) {
3567 connection_printf_to_buf(conn
, "512 Too many arguments to %s\r\n",command
);
3572 SMARTLIST_FOREACH(args
, char *, s
, tor_free(s
));
3573 smartlist_free(args
);
3577 /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
3578 * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
3579 * such element exists. */
3581 find_element_starting_with(smartlist_t
*sl
, int start_at
, const char *prefix
)
3584 for (i
= start_at
; i
< smartlist_len(sl
); ++i
) {
3585 const char *elt
= smartlist_get(sl
, i
);
3586 if (!strcasecmpstart(elt
, prefix
))
3592 /** Helper. Return true iff s is an argument that we should treat as a
3593 * key-value pair. */
3595 is_keyval_pair(const char *s
)
3597 /* An argument is a key-value pair if it has an =, and it isn't of the form
3598 * $fingeprint=name */
3599 return strchr(s
, '=') && s
[0] != '$';
3602 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
3603 * circuit, and report success or failure. */
3605 handle_control_extendcircuit(control_connection_t
*conn
, uint32_t len
,
3608 smartlist_t
*router_nicknames
=NULL
, *nodes
=NULL
;
3609 origin_circuit_t
*circ
= NULL
;
3611 uint8_t intended_purpose
= CIRCUIT_PURPOSE_C_GENERAL
;
3615 router_nicknames
= smartlist_new();
3617 args
= getargs_helper("EXTENDCIRCUIT", conn
, body
, 1, -1);
3621 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,0));
3624 const char *purp
= find_element_starting_with(args
, 1, "PURPOSE=");
3627 intended_purpose
= circuit_purpose_from_string(purp
);
3628 if (intended_purpose
== CIRCUIT_PURPOSE_UNKNOWN
) {
3629 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
3630 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3631 smartlist_free(args
);
3636 if ((smartlist_len(args
) == 1) ||
3637 (smartlist_len(args
) >= 2 && is_keyval_pair(smartlist_get(args
, 1)))) {
3638 // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
3639 circ
= circuit_launch(intended_purpose
, CIRCLAUNCH_NEED_CAPACITY
);
3641 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
3643 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
3644 (unsigned long)circ
->global_identifier
);
3646 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3647 smartlist_free(args
);
3650 // "EXTENDCIRCUIT 0 router1,router2" ||
3651 // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
3654 if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
,0)))) {
3655 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
3656 (char*)smartlist_get(args
, 0));
3657 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3658 smartlist_free(args
);
3662 if (smartlist_len(args
) < 2) {
3663 connection_printf_to_buf(conn
,
3664 "512 syntax error: not enough arguments.\r\n");
3665 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3666 smartlist_free(args
);
3670 smartlist_split_string(router_nicknames
, smartlist_get(args
,1), ",", 0, 0);
3672 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3673 smartlist_free(args
);
3675 nodes
= smartlist_new();
3676 int first_node
= zero_circ
;
3677 SMARTLIST_FOREACH_BEGIN(router_nicknames
, const char *, n
) {
3678 const node_t
*node
= node_get_by_nickname(n
, 0);
3680 connection_printf_to_buf(conn
, "552 No such router \"%s\"\r\n", n
);
3683 if (!node_has_preferred_descriptor(node
, first_node
)) {
3684 connection_printf_to_buf(conn
, "552 No descriptor for \"%s\"\r\n", n
);
3687 smartlist_add(nodes
, (void*)node
);
3689 } SMARTLIST_FOREACH_END(n
);
3690 if (!smartlist_len(nodes
)) {
3691 connection_write_str_to_buf("512 No router names provided\r\n", conn
);
3696 /* start a new circuit */
3697 circ
= origin_circuit_init(intended_purpose
, 0);
3700 /* now circ refers to something that is ready to be extended */
3701 first_node
= zero_circ
;
3702 SMARTLIST_FOREACH(nodes
, const node_t
*, node
,
3704 extend_info_t
*info
= extend_info_from_node(node
, first_node
);
3706 tor_assert_nonfatal(first_node
);
3707 log_warn(LD_CONTROL
,
3708 "controller tried to connect to a node that lacks a suitable "
3709 "descriptor, or which doesn't have any "
3710 "addresses that are allowed by the firewall configuration; "
3711 "circuit marked for closing.");
3712 circuit_mark_for_close(TO_CIRCUIT(circ
), -END_CIRC_REASON_CONNECTFAILED
);
3713 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
3716 circuit_append_new_exit(circ
, info
);
3717 if (circ
->build_state
->desired_path_len
> 1) {
3718 circ
->build_state
->onehop_tunnel
= 0;
3720 extend_info_free(info
);
3724 /* now that we've populated the cpath, start extending */
3727 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
3728 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
3729 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
3733 if (circ
->base_
.state
== CIRCUIT_STATE_OPEN
||
3734 circ
->base_
.state
== CIRCUIT_STATE_GUARD_WAIT
) {
3736 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
3737 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
3738 log_info(LD_CONTROL
,
3739 "send_next_onion_skin failed; circuit marked for closing.");
3740 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
3741 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn
);
3747 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
3748 (unsigned long)circ
->global_identifier
);
3749 if (zero_circ
) /* send a 'launched' event, for completeness */
3750 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
3752 SMARTLIST_FOREACH(router_nicknames
, char *, n
, tor_free(n
));
3753 smartlist_free(router_nicknames
);
3754 smartlist_free(nodes
);
3758 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
3759 * circuit and it's a valid purpose, change it. */
3761 handle_control_setcircuitpurpose(control_connection_t
*conn
,
3762 uint32_t len
, const char *body
)
3764 origin_circuit_t
*circ
= NULL
;
3765 uint8_t new_purpose
;
3767 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
3769 args
= getargs_helper("SETCIRCUITPURPOSE", conn
, body
, 2, -1);
3773 if (!(circ
= get_circ(smartlist_get(args
,0)))) {
3774 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
3775 (char*)smartlist_get(args
, 0));
3780 const char *purp
= find_element_starting_with(args
,1,"PURPOSE=");
3782 connection_write_str_to_buf("552 No purpose given\r\n", conn
);
3785 new_purpose
= circuit_purpose_from_string(purp
);
3786 if (new_purpose
== CIRCUIT_PURPOSE_UNKNOWN
) {
3787 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
3792 circuit_change_purpose(TO_CIRCUIT(circ
), new_purpose
);
3793 connection_write_str_to_buf("250 OK\r\n", conn
);
3797 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3798 smartlist_free(args
);
3803 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
3804 * stream, and report success or failure. */
3806 handle_control_attachstream(control_connection_t
*conn
, uint32_t len
,
3809 entry_connection_t
*ap_conn
= NULL
;
3810 origin_circuit_t
*circ
= NULL
;
3813 crypt_path_t
*cpath
=NULL
;
3814 int hop
=0, hop_line_ok
=1;
3817 args
= getargs_helper("ATTACHSTREAM", conn
, body
, 2, -1);
3821 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,1));
3823 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))) {
3824 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
3825 (char*)smartlist_get(args
, 0));
3826 } else if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
, 1)))) {
3827 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
3828 (char*)smartlist_get(args
, 1));
3830 const char *hopstring
= find_element_starting_with(args
,2,"HOP=");
3832 hopstring
+= strlen("HOP=");
3833 hop
= (int) tor_parse_ulong(hopstring
, 10, 0, INT_MAX
,
3834 &hop_line_ok
, NULL
);
3835 if (!hop_line_ok
) { /* broken hop line */
3836 connection_printf_to_buf(conn
, "552 Bad value hop=%s\r\n", hopstring
);
3840 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3841 smartlist_free(args
);
3842 if (!ap_conn
|| (!zero_circ
&& !circ
) || !hop_line_ok
)
3845 if (ENTRY_TO_CONN(ap_conn
)->state
!= AP_CONN_STATE_CONTROLLER_WAIT
&&
3846 ENTRY_TO_CONN(ap_conn
)->state
!= AP_CONN_STATE_CONNECT_WAIT
&&
3847 ENTRY_TO_CONN(ap_conn
)->state
!= AP_CONN_STATE_RESOLVE_WAIT
) {
3848 connection_write_str_to_buf(
3849 "555 Connection is not managed by controller.\r\n",
3854 /* Do we need to detach it first? */
3855 if (ENTRY_TO_CONN(ap_conn
)->state
!= AP_CONN_STATE_CONTROLLER_WAIT
) {
3856 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(ap_conn
);
3857 circuit_t
*tmpcirc
= circuit_get_by_edge_conn(edge_conn
);
3858 connection_edge_end(edge_conn
, END_STREAM_REASON_TIMEOUT
);
3859 /* Un-mark it as ending, since we're going to reuse it. */
3860 edge_conn
->edge_has_sent_end
= 0;
3861 edge_conn
->end_reason
= 0;
3863 circuit_detach_stream(tmpcirc
, edge_conn
);
3864 CONNECTION_AP_EXPECT_NONPENDING(ap_conn
);
3865 TO_CONN(edge_conn
)->state
= AP_CONN_STATE_CONTROLLER_WAIT
;
3868 if (circ
&& (circ
->base_
.state
!= CIRCUIT_STATE_OPEN
)) {
3869 connection_write_str_to_buf(
3870 "551 Can't attach stream to non-open origin circuit\r\n",
3874 /* Is this a single hop circuit? */
3875 if (circ
&& (circuit_get_cpath_len(circ
)<2 || hop
==1)) {
3876 connection_write_str_to_buf(
3877 "551 Can't attach stream to this one-hop circuit.\r\n", conn
);
3881 if (circ
&& hop
>0) {
3882 /* find this hop in the circuit, and set cpath */
3883 cpath
= circuit_get_cpath_hop(circ
, hop
);
3885 connection_printf_to_buf(conn
,
3886 "551 Circuit doesn't have %d hops.\r\n", hop
);
3890 if (connection_ap_handshake_rewrite_and_attach(ap_conn
, circ
, cpath
) < 0) {
3891 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn
);
3894 send_control_done(conn
);
3898 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
3899 * descriptor, and report success or failure. */
3901 handle_control_postdescriptor(control_connection_t
*conn
, uint32_t len
,
3905 const char *msg
=NULL
;
3906 uint8_t purpose
= ROUTER_PURPOSE_GENERAL
;
3907 int cache
= 0; /* eventually, we may switch this to 1 */
3909 const char *cp
= memchr(body
, '\n', len
);
3912 connection_printf_to_buf(conn
, "251 Empty body\r\n");
3917 char *cmdline
= tor_memdup_nulterm(body
, cp
-body
);
3918 smartlist_t
*args
= smartlist_new();
3919 smartlist_split_string(args
, cmdline
, " ",
3920 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3921 SMARTLIST_FOREACH_BEGIN(args
, char *, option
) {
3922 if (!strcasecmpstart(option
, "purpose=")) {
3923 option
+= strlen("purpose=");
3924 purpose
= router_purpose_from_string(option
);
3925 if (purpose
== ROUTER_PURPOSE_UNKNOWN
) {
3926 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n",
3930 } else if (!strcasecmpstart(option
, "cache=")) {
3931 option
+= strlen("cache=");
3932 if (!strcasecmp(option
, "no"))
3934 else if (!strcasecmp(option
, "yes"))
3937 connection_printf_to_buf(conn
, "552 Unknown cache request \"%s\"\r\n",
3941 } else { /* unrecognized argument? */
3942 connection_printf_to_buf(conn
,
3943 "512 Unexpected argument \"%s\" to postdescriptor\r\n", option
);
3946 } SMARTLIST_FOREACH_END(option
);
3948 read_escaped_data(cp
, len
-(cp
-body
), &desc
);
3950 switch (router_load_single_router(desc
, purpose
, cache
, &msg
)) {
3952 if (!msg
) msg
= "Could not parse descriptor";
3953 connection_printf_to_buf(conn
, "554 %s\r\n", msg
);
3956 if (!msg
) msg
= "Descriptor not added";
3957 connection_printf_to_buf(conn
, "251 %s\r\n",msg
);
3960 send_control_done(conn
);
3966 SMARTLIST_FOREACH(args
, char *, arg
, tor_free(arg
));
3967 smartlist_free(args
);
3972 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
3973 * address of the named AP stream, and report success or failure. */
3975 handle_control_redirectstream(control_connection_t
*conn
, uint32_t len
,
3978 entry_connection_t
*ap_conn
= NULL
;
3979 char *new_addr
= NULL
;
3980 uint16_t new_port
= 0;
3984 args
= getargs_helper("REDIRECTSTREAM", conn
, body
, 2, -1);
3988 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))
3989 || !ap_conn
->socks_request
) {
3990 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
3991 (char*)smartlist_get(args
, 0));
3994 if (smartlist_len(args
) > 2) { /* they included a port too */
3995 new_port
= (uint16_t) tor_parse_ulong(smartlist_get(args
, 2),
3996 10, 1, 65535, &ok
, NULL
);
3999 connection_printf_to_buf(conn
, "512 Cannot parse port \"%s\"\r\n",
4000 (char*)smartlist_get(args
, 2));
4002 new_addr
= tor_strdup(smartlist_get(args
, 1));
4006 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4007 smartlist_free(args
);
4011 strlcpy(ap_conn
->socks_request
->address
, new_addr
,
4012 sizeof(ap_conn
->socks_request
->address
));
4014 ap_conn
->socks_request
->port
= new_port
;
4016 send_control_done(conn
);
4020 /** Called when we get a CLOSESTREAM command; try to close the named stream
4021 * and report success or failure. */
4023 handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
4026 entry_connection_t
*ap_conn
=NULL
;
4032 args
= getargs_helper("CLOSESTREAM", conn
, body
, 2, -1);
4036 else if (!(ap_conn
= get_stream(smartlist_get(args
, 0))))
4037 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
4038 (char*)smartlist_get(args
, 0));
4040 reason
= (uint8_t) tor_parse_ulong(smartlist_get(args
,1), 10, 0, 255,
4043 connection_printf_to_buf(conn
, "552 Unrecognized reason \"%s\"\r\n",
4044 (char*)smartlist_get(args
, 1));
4048 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4049 smartlist_free(args
);
4053 connection_mark_unattached_ap(ap_conn
, reason
);
4054 send_control_done(conn
);
4058 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
4059 * and report success or failure. */
4061 handle_control_closecircuit(control_connection_t
*conn
, uint32_t len
,
4064 origin_circuit_t
*circ
= NULL
;
4069 args
= getargs_helper("CLOSECIRCUIT", conn
, body
, 1, -1);
4073 if (!(circ
=get_circ(smartlist_get(args
, 0))))
4074 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
4075 (char*)smartlist_get(args
, 0));
4078 for (i
=1; i
< smartlist_len(args
); ++i
) {
4079 if (!strcasecmp(smartlist_get(args
, i
), "IfUnused"))
4082 log_info(LD_CONTROL
, "Skipping unknown option %s",
4083 (char*)smartlist_get(args
,i
));
4086 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4087 smartlist_free(args
);
4091 if (!safe
|| !circ
->p_streams
) {
4092 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_REQUESTED
);
4095 send_control_done(conn
);
4099 /** Called when we get a RESOLVE command: start trying to resolve
4100 * the listed addresses. */
4102 handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
4105 smartlist_t
*args
, *failed
;
4107 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
4109 if (!(conn
->event_mask
& (((event_mask_t
)1)<<EVENT_ADDRMAP
))) {
4110 log_warn(LD_CONTROL
, "Controller asked us to resolve an address, but "
4111 "isn't listening for ADDRMAP events. It probably won't see "
4114 args
= smartlist_new();
4115 smartlist_split_string(args
, body
, " ",
4116 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
4118 const char *modearg
= find_element_starting_with(args
, 0, "mode=");
4119 if (modearg
&& !strcasecmp(modearg
, "mode=reverse"))
4122 failed
= smartlist_new();
4123 SMARTLIST_FOREACH(args
, const char *, arg
, {
4124 if (!is_keyval_pair(arg
)) {
4125 if (dnsserv_launch_request(arg
, is_reverse
, conn
)<0)
4126 smartlist_add(failed
, (char*)arg
);
4130 send_control_done(conn
);
4131 SMARTLIST_FOREACH(failed
, const char *, arg
, {
4132 control_event_address_mapped(arg
, arg
, time(NULL
),
4136 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4137 smartlist_free(args
);
4138 smartlist_free(failed
);
4142 /** Called when we get a PROTOCOLINFO command: send back a reply. */
4144 handle_control_protocolinfo(control_connection_t
*conn
, uint32_t len
,
4147 const char *bad_arg
= NULL
;
4151 conn
->have_sent_protocolinfo
= 1;
4152 args
= smartlist_new();
4153 smartlist_split_string(args
, body
, " ",
4154 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
4155 SMARTLIST_FOREACH(args
, const char *, arg
, {
4157 tor_parse_long(arg
, 10, 0, LONG_MAX
, &ok
, NULL
);
4164 connection_printf_to_buf(conn
, "513 No such version %s\r\n",
4166 /* Don't tolerate bad arguments when not authenticated. */
4167 if (!STATE_IS_OPEN(TO_CONN(conn
)->state
))
4168 connection_mark_for_close(TO_CONN(conn
));
4171 const or_options_t
*options
= get_options();
4172 int cookies
= options
->CookieAuthentication
;
4173 char *cfile
= get_controller_cookie_file_name();
4177 abs_cfile
= make_path_absolute(cfile
);
4178 esc_cfile
= esc_for_log(abs_cfile
);
4180 int passwd
= (options
->HashedControlPassword
!= NULL
||
4181 options
->HashedControlSessionPassword
!= NULL
);
4182 smartlist_t
*mlist
= smartlist_new();
4184 smartlist_add(mlist
, (char*)"COOKIE");
4185 smartlist_add(mlist
, (char*)"SAFECOOKIE");
4188 smartlist_add(mlist
, (char*)"HASHEDPASSWORD");
4189 if (!cookies
&& !passwd
)
4190 smartlist_add(mlist
, (char*)"NULL");
4191 methods
= smartlist_join_strings(mlist
, ",", 0, NULL
);
4192 smartlist_free(mlist
);
4195 connection_printf_to_buf(conn
,
4196 "250-PROTOCOLINFO 1\r\n"
4197 "250-AUTH METHODS=%s%s%s\r\n"
4198 "250-VERSION Tor=%s\r\n"
4201 cookies
?" COOKIEFILE=":"",
4202 cookies
?esc_cfile
:"",
4206 tor_free(abs_cfile
);
4207 tor_free(esc_cfile
);
4210 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4211 smartlist_free(args
);
4215 /** Called when we get an AUTHCHALLENGE command. */
4217 handle_control_authchallenge(control_connection_t
*conn
, uint32_t len
,
4220 const char *cp
= body
;
4222 size_t client_nonce_len
;
4223 char server_hash
[DIGEST256_LEN
];
4224 char server_hash_encoded
[HEX_DIGEST256_LEN
+1];
4225 char server_nonce
[SAFECOOKIE_SERVER_NONCE_LEN
];
4226 char server_nonce_encoded
[(2*SAFECOOKIE_SERVER_NONCE_LEN
) + 1];
4228 cp
+= strspn(cp
, " \t\n\r");
4229 if (!strcasecmpstart(cp
, "SAFECOOKIE")) {
4230 cp
+= strlen("SAFECOOKIE");
4232 connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
4233 "authentication\r\n", conn
);
4234 connection_mark_for_close(TO_CONN(conn
));
4238 if (!authentication_cookie_is_set
) {
4239 connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
4241 connection_mark_for_close(TO_CONN(conn
));
4245 cp
+= strspn(cp
, " \t\n\r");
4248 decode_escaped_string(cp
, len
- (cp
- body
),
4249 &client_nonce
, &client_nonce_len
);
4250 if (newcp
== NULL
) {
4251 connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
4253 connection_mark_for_close(TO_CONN(conn
));
4258 size_t client_nonce_encoded_len
= strspn(cp
, "0123456789ABCDEFabcdef");
4260 client_nonce_len
= client_nonce_encoded_len
/ 2;
4261 client_nonce
= tor_malloc_zero(client_nonce_len
);
4263 if (base16_decode(client_nonce
, client_nonce_len
,
4264 cp
, client_nonce_encoded_len
)
4265 != (int) client_nonce_len
) {
4266 connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
4268 connection_mark_for_close(TO_CONN(conn
));
4269 tor_free(client_nonce
);
4273 cp
+= client_nonce_encoded_len
;
4276 cp
+= strspn(cp
, " \t\n\r");
4279 connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
4281 connection_mark_for_close(TO_CONN(conn
));
4282 tor_free(client_nonce
);
4285 crypto_rand(server_nonce
, SAFECOOKIE_SERVER_NONCE_LEN
);
4287 /* Now compute and send the server-to-controller response, and the
4288 * server's nonce. */
4289 tor_assert(authentication_cookie
!= NULL
);
4292 size_t tmp_len
= (AUTHENTICATION_COOKIE_LEN
+
4294 SAFECOOKIE_SERVER_NONCE_LEN
);
4295 char *tmp
= tor_malloc_zero(tmp_len
);
4296 char *client_hash
= tor_malloc_zero(DIGEST256_LEN
);
4297 memcpy(tmp
, authentication_cookie
, AUTHENTICATION_COOKIE_LEN
);
4298 memcpy(tmp
+ AUTHENTICATION_COOKIE_LEN
, client_nonce
, client_nonce_len
);
4299 memcpy(tmp
+ AUTHENTICATION_COOKIE_LEN
+ client_nonce_len
,
4300 server_nonce
, SAFECOOKIE_SERVER_NONCE_LEN
);
4302 crypto_hmac_sha256(server_hash
,
4303 SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT
,
4304 strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT
),
4308 crypto_hmac_sha256(client_hash
,
4309 SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT
,
4310 strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT
),
4314 conn
->safecookie_client_hash
= client_hash
;
4319 base16_encode(server_hash_encoded
, sizeof(server_hash_encoded
),
4320 server_hash
, sizeof(server_hash
));
4321 base16_encode(server_nonce_encoded
, sizeof(server_nonce_encoded
),
4322 server_nonce
, sizeof(server_nonce
));
4324 connection_printf_to_buf(conn
,
4325 "250 AUTHCHALLENGE SERVERHASH=%s "
4326 "SERVERNONCE=%s\r\n",
4327 server_hash_encoded
,
4328 server_nonce_encoded
);
4330 tor_free(client_nonce
);
4334 /** Called when we get a USEFEATURE command: parse the feature list, and
4335 * set up the control_connection's options properly. */
4337 handle_control_usefeature(control_connection_t
*conn
,
4343 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
4344 args
= smartlist_new();
4345 smartlist_split_string(args
, body
, " ",
4346 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
4347 SMARTLIST_FOREACH_BEGIN(args
, const char *, arg
) {
4348 if (!strcasecmp(arg
, "VERBOSE_NAMES"))
4350 else if (!strcasecmp(arg
, "EXTENDED_EVENTS"))
4353 connection_printf_to_buf(conn
, "552 Unrecognized feature \"%s\"\r\n",
4358 } SMARTLIST_FOREACH_END(arg
);
4361 send_control_done(conn
);
4364 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4365 smartlist_free(args
);
4369 /** Implementation for the DROPGUARDS command. */
4371 handle_control_dropguards(control_connection_t
*conn
,
4376 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
4377 args
= smartlist_new();
4378 smartlist_split_string(args
, body
, " ",
4379 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
4381 static int have_warned
= 0;
4382 if (! have_warned
) {
4383 log_warn(LD_CONTROL
, "DROPGUARDS is dangerous; make sure you understand "
4384 "the risks before using it. It may be removed in a future "
4389 if (smartlist_len(args
)) {
4390 connection_printf_to_buf(conn
, "512 Too many arguments to DROPGUARDS\r\n");
4392 remove_all_entry_guards();
4393 send_control_done(conn
);
4396 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4397 smartlist_free(args
);
4401 /** Implementation for the HSFETCH command. */
4403 handle_control_hsfetch(control_connection_t
*conn
, uint32_t len
,
4407 char digest
[DIGEST_LEN
], *hsaddress
= NULL
, *arg1
= NULL
, *desc_id
= NULL
;
4408 smartlist_t
*args
= NULL
, *hsdirs
= NULL
;
4409 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
4410 static const char *hsfetch_command
= "HSFETCH";
4411 static const char *v2_str
= "v2-";
4412 const size_t v2_str_len
= strlen(v2_str
);
4413 rend_data_t
*rend_query
= NULL
;
4415 /* Make sure we have at least one argument, the HSAddress. */
4416 args
= getargs_helper(hsfetch_command
, conn
, body
, 1, -1);
4421 /* Extract the first argument (either HSAddress or DescID). */
4422 arg1
= smartlist_get(args
, 0);
4423 /* Test if it's an HS address without the .onion part. */
4424 if (rend_valid_v2_service_id(arg1
)) {
4426 } else if (strcmpstart(arg1
, v2_str
) == 0 &&
4427 rend_valid_descriptor_id(arg1
+ v2_str_len
) &&
4428 base32_decode(digest
, sizeof(digest
), arg1
+ v2_str_len
,
4429 REND_DESC_ID_V2_LEN_BASE32
) == 0) {
4430 /* We have a well formed version 2 descriptor ID. Keep the decoded value
4434 connection_printf_to_buf(conn
, "513 Invalid argument \"%s\"\r\n",
4439 static const char *opt_server
= "SERVER=";
4441 /* Skip first argument because it's the HSAddress or DescID. */
4442 for (i
= 1; i
< smartlist_len(args
); ++i
) {
4443 const char *arg
= smartlist_get(args
, i
);
4446 if (!strcasecmpstart(arg
, opt_server
)) {
4449 server
= arg
+ strlen(opt_server
);
4450 node
= node_get_by_hex_id(server
, 0);
4452 connection_printf_to_buf(conn
, "552 Server \"%s\" not found\r\n",
4457 /* Stores routerstatus_t object for each specified server. */
4458 hsdirs
= smartlist_new();
4460 /* Valid server, add it to our local list. */
4461 smartlist_add(hsdirs
, node
->rs
);
4463 connection_printf_to_buf(conn
, "513 Unexpected argument \"%s\"\r\n",
4469 rend_query
= rend_data_client_create(hsaddress
, desc_id
, NULL
,
4471 if (rend_query
== NULL
) {
4472 connection_printf_to_buf(conn
, "551 Error creating the HS query\r\n");
4476 /* Using a descriptor ID, we force the user to provide at least one
4477 * hsdir server using the SERVER= option. */
4478 if (desc_id
&& (!hsdirs
|| !smartlist_len(hsdirs
))) {
4479 connection_printf_to_buf(conn
, "512 %s option is required\r\n",
4484 /* We are about to trigger HSDir fetch so send the OK now because after
4485 * that 650 event(s) are possible so better to have the 250 OK before them
4486 * to avoid out of order replies. */
4487 send_control_done(conn
);
4489 /* Trigger the fetch using the built rend query and possibly a list of HS
4490 * directory to use. This function ignores the client cache thus this will
4491 * always send a fetch command. */
4492 rend_client_fetch_v2_desc(rend_query
, hsdirs
);
4495 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4496 smartlist_free(args
);
4497 /* Contains data pointer that we don't own thus no cleanup. */
4498 smartlist_free(hsdirs
);
4499 rend_data_free(rend_query
);
4504 /** Implementation for the HSPOST command. */
4506 handle_control_hspost(control_connection_t
*conn
,
4510 static const char *opt_server
= "SERVER=";
4511 static const char *opt_hsaddress
= "HSADDRESS=";
4512 smartlist_t
*hs_dirs
= NULL
;
4513 const char *encoded_desc
= body
;
4514 size_t encoded_desc_len
= len
;
4515 const char *onion_address
= NULL
;
4517 char *cp
= memchr(body
, '\n', len
);
4519 connection_printf_to_buf(conn
, "251 Empty body\r\n");
4522 char *argline
= tor_strndup(body
, cp
-body
);
4524 smartlist_t
*args
= smartlist_new();
4526 /* If any SERVER= or HSADDRESS= options were specified, try to parse
4527 * the options line. */
4528 if (!strcasecmpstart(argline
, opt_server
) ||
4529 !strcasecmpstart(argline
, opt_hsaddress
)) {
4530 /* encoded_desc begins after a newline character */
4533 encoded_desc_len
= len
-(cp
-body
);
4535 smartlist_split_string(args
, argline
, " ",
4536 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
4537 SMARTLIST_FOREACH_BEGIN(args
, const char *, arg
) {
4538 if (!strcasecmpstart(arg
, opt_server
)) {
4539 const char *server
= arg
+ strlen(opt_server
);
4540 const node_t
*node
= node_get_by_hex_id(server
, 0);
4542 if (!node
|| !node
->rs
) {
4543 connection_printf_to_buf(conn
, "552 Server \"%s\" not found\r\n",
4547 /* Valid server, add it to our local list. */
4549 hs_dirs
= smartlist_new();
4550 smartlist_add(hs_dirs
, node
->rs
);
4551 } else if (!strcasecmpstart(arg
, opt_hsaddress
)) {
4552 const char *address
= arg
+ strlen(opt_hsaddress
);
4553 if (!hs_address_is_valid(address
)) {
4554 connection_printf_to_buf(conn
, "512 Malformed onion address\r\n");
4557 onion_address
= address
;
4559 connection_printf_to_buf(conn
, "512 Unexpected argument \"%s\"\r\n",
4563 } SMARTLIST_FOREACH_END(arg
);
4566 /* Handle the v3 case. */
4567 if (onion_address
) {
4568 char *desc_str
= NULL
;
4569 read_escaped_data(encoded_desc
, encoded_desc_len
, &desc_str
);
4570 if (hs_control_hspost_command(desc_str
, onion_address
, hs_dirs
) < 0) {
4571 connection_printf_to_buf(conn
, "554 Invalid descriptor\r\n");
4573 send_control_done(conn
);
4579 /* From this point on, it is only v2. */
4581 /* Read the dot encoded descriptor, and parse it. */
4582 rend_encoded_v2_service_descriptor_t
*desc
=
4583 tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t
));
4584 read_escaped_data(encoded_desc
, encoded_desc_len
, &desc
->desc_str
);
4586 rend_service_descriptor_t
*parsed
= NULL
;
4587 char *intro_content
= NULL
;
4589 size_t encoded_size
;
4590 const char *next_desc
;
4591 if (!rend_parse_v2_service_descriptor(&parsed
, desc
->desc_id
, &intro_content
,
4592 &intro_size
, &encoded_size
,
4593 &next_desc
, desc
->desc_str
, 1)) {
4594 /* Post the descriptor. */
4595 char serviceid
[REND_SERVICE_ID_LEN_BASE32
+1];
4596 if (!rend_get_service_id(parsed
->pk
, serviceid
)) {
4597 smartlist_t
*descs
= smartlist_new();
4598 smartlist_add(descs
, desc
);
4600 /* We are about to trigger HS descriptor upload so send the OK now
4601 * because after that 650 event(s) are possible so better to have the
4602 * 250 OK before them to avoid out of order replies. */
4603 send_control_done(conn
);
4605 /* Trigger the descriptor upload */
4606 directory_post_to_hs_dir(parsed
, descs
, hs_dirs
, serviceid
, 0);
4607 smartlist_free(descs
);
4610 rend_service_descriptor_free(parsed
);
4612 connection_printf_to_buf(conn
, "554 Invalid descriptor\r\n");
4615 tor_free(intro_content
);
4616 rend_encoded_v2_service_descriptor_free(desc
);
4619 smartlist_free(hs_dirs
); /* Contents belong to the rend service code. */
4620 SMARTLIST_FOREACH(args
, char *, arg
, tor_free(arg
));
4621 smartlist_free(args
);
4625 /* Helper function for ADD_ONION that adds an ephemeral service depending on
4626 * the given hs_version.
4628 * The secret key in pk depends on the hs_version. The ownership of the key
4629 * used in pk is given to the HS subsystem so the caller must stop accessing
4632 * The port_cfgs is a list of service port. Ownership transferred to service.
4633 * The max_streams refers to the MaxStreams= key.
4634 * The max_streams_close_circuit refers to the MaxStreamsCloseCircuit key.
4635 * The auth_type is the authentication type of the clients in auth_clients.
4636 * The ownership of that list is transferred to the service.
4638 * On success (RSAE_OKAY), the address_out points to a newly allocated string
4639 * containing the onion address without the .onion part. On error, address_out
4641 static hs_service_add_ephemeral_status_t
4642 add_onion_helper_add_service(int hs_version
,
4643 add_onion_secret_key_t
*pk
,
4644 smartlist_t
*port_cfgs
, int max_streams
,
4645 int max_streams_close_circuit
, int auth_type
,
4646 smartlist_t
*auth_clients
, char **address_out
)
4648 hs_service_add_ephemeral_status_t ret
;
4651 tor_assert(port_cfgs
);
4652 tor_assert(address_out
);
4654 switch (hs_version
) {
4655 case HS_VERSION_TWO
:
4656 ret
= rend_service_add_ephemeral(pk
->v2
, port_cfgs
, max_streams
,
4657 max_streams_close_circuit
, auth_type
,
4658 auth_clients
, address_out
);
4660 case HS_VERSION_THREE
:
4661 ret
= hs_service_add_ephemeral(pk
->v3
, port_cfgs
, max_streams
,
4662 max_streams_close_circuit
, address_out
);
4665 tor_assert_unreached();
4671 /** Called when we get a ADD_ONION command; parse the body, and set up
4672 * the new ephemeral Onion Service. */
4674 handle_control_add_onion(control_connection_t
*conn
,
4680 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
4681 args
= getargs_helper("ADD_ONION", conn
, body
, 2, -1);
4684 arg_len
= smartlist_len(args
);
4686 /* Parse all of the arguments that do not involve handling cryptographic
4687 * material first, since there's no reason to touch that at all if any of
4688 * the other arguments are malformed.
4690 smartlist_t
*port_cfgs
= smartlist_new();
4691 smartlist_t
*auth_clients
= NULL
;
4692 smartlist_t
*auth_created_clients
= NULL
;
4695 int max_streams
= 0;
4696 int max_streams_close_circuit
= 0;
4697 rend_auth_type_t auth_type
= REND_NO_AUTH
;
4698 /* Default to adding an anonymous hidden service if no flag is given */
4699 int non_anonymous
= 0;
4700 for (int i
= 1; i
< arg_len
; i
++) {
4701 static const char *port_prefix
= "Port=";
4702 static const char *flags_prefix
= "Flags=";
4703 static const char *max_s_prefix
= "MaxStreams=";
4704 static const char *auth_prefix
= "ClientAuth=";
4706 const char *arg
= smartlist_get(args
, (int)i
);
4707 if (!strcasecmpstart(arg
, port_prefix
)) {
4708 /* "Port=VIRTPORT[,TARGET]". */
4709 const char *port_str
= arg
+ strlen(port_prefix
);
4711 rend_service_port_config_t
*cfg
=
4712 rend_service_parse_port_config(port_str
, ",", NULL
);
4714 connection_printf_to_buf(conn
, "512 Invalid VIRTPORT/TARGET\r\n");
4717 smartlist_add(port_cfgs
, cfg
);
4718 } else if (!strcasecmpstart(arg
, max_s_prefix
)) {
4719 /* "MaxStreams=[0..65535]". */
4720 const char *max_s_str
= arg
+ strlen(max_s_prefix
);
4722 max_streams
= (int)tor_parse_long(max_s_str
, 10, 0, 65535, &ok
, NULL
);
4724 connection_printf_to_buf(conn
, "512 Invalid MaxStreams\r\n");
4727 } else if (!strcasecmpstart(arg
, flags_prefix
)) {
4728 /* "Flags=Flag[,Flag]", where Flag can be:
4729 * * 'DiscardPK' - If tor generates the keypair, do not include it in
4731 * * 'Detach' - Do not tie this onion service to any particular control
4733 * * 'MaxStreamsCloseCircuit' - Close the circuit if MaxStreams is
4735 * * 'BasicAuth' - Client authorization using the 'basic' method.
4736 * * 'NonAnonymous' - Add a non-anonymous Single Onion Service. If this
4737 * flag is present, tor must be in non-anonymous
4738 * hidden service mode. If this flag is absent,
4739 * tor must be in anonymous hidden service mode.
4741 static const char *discard_flag
= "DiscardPK";
4742 static const char *detach_flag
= "Detach";
4743 static const char *max_s_close_flag
= "MaxStreamsCloseCircuit";
4744 static const char *basicauth_flag
= "BasicAuth";
4745 static const char *non_anonymous_flag
= "NonAnonymous";
4747 smartlist_t
*flags
= smartlist_new();
4750 smartlist_split_string(flags
, arg
+ strlen(flags_prefix
), ",",
4751 SPLIT_IGNORE_BLANK
, 0);
4752 if (smartlist_len(flags
) < 1) {
4753 connection_printf_to_buf(conn
, "512 Invalid 'Flags' argument\r\n");
4756 SMARTLIST_FOREACH_BEGIN(flags
, const char *, flag
)
4758 if (!strcasecmp(flag
, discard_flag
)) {
4760 } else if (!strcasecmp(flag
, detach_flag
)) {
4762 } else if (!strcasecmp(flag
, max_s_close_flag
)) {
4763 max_streams_close_circuit
= 1;
4764 } else if (!strcasecmp(flag
, basicauth_flag
)) {
4765 auth_type
= REND_BASIC_AUTH
;
4766 } else if (!strcasecmp(flag
, non_anonymous_flag
)) {
4769 connection_printf_to_buf(conn
,
4770 "512 Invalid 'Flags' argument: %s\r\n",
4775 } SMARTLIST_FOREACH_END(flag
);
4776 SMARTLIST_FOREACH(flags
, char *, cp
, tor_free(cp
));
4777 smartlist_free(flags
);
4780 } else if (!strcasecmpstart(arg
, auth_prefix
)) {
4781 char *err_msg
= NULL
;
4783 rend_authorized_client_t
*client
=
4784 add_onion_helper_clientauth(arg
+ strlen(auth_prefix
),
4785 &created
, &err_msg
);
4788 connection_write_str_to_buf(err_msg
, conn
);
4794 if (auth_clients
!= NULL
) {
4796 SMARTLIST_FOREACH_BEGIN(auth_clients
, rend_authorized_client_t
*, ac
) {
4797 if (strcmp(ac
->client_name
, client
->client_name
) == 0) {
4801 } SMARTLIST_FOREACH_END(ac
);
4803 connection_printf_to_buf(conn
,
4804 "512 Duplicate name in ClientAuth\r\n");
4805 rend_authorized_client_free(client
);
4809 auth_clients
= smartlist_new();
4810 auth_created_clients
= smartlist_new();
4812 smartlist_add(auth_clients
, client
);
4814 smartlist_add(auth_created_clients
, client
);
4817 connection_printf_to_buf(conn
, "513 Invalid argument\r\n");
4821 if (smartlist_len(port_cfgs
) == 0) {
4822 connection_printf_to_buf(conn
, "512 Missing 'Port' argument\r\n");
4824 } else if (auth_type
== REND_NO_AUTH
&& auth_clients
!= NULL
) {
4825 connection_printf_to_buf(conn
, "512 No auth type specified\r\n");
4827 } else if (auth_type
!= REND_NO_AUTH
&& auth_clients
== NULL
) {
4828 connection_printf_to_buf(conn
, "512 No auth clients specified\r\n");
4830 } else if ((auth_type
== REND_BASIC_AUTH
&&
4831 smartlist_len(auth_clients
) > 512) ||
4832 (auth_type
== REND_STEALTH_AUTH
&&
4833 smartlist_len(auth_clients
) > 16)) {
4834 connection_printf_to_buf(conn
, "512 Too many auth clients\r\n");
4836 } else if (non_anonymous
!= rend_service_non_anonymous_mode_enabled(
4838 /* If we failed, and the non-anonymous flag is set, Tor must be in
4839 * anonymous hidden service mode.
4840 * The error message changes based on the current Tor config:
4841 * 512 Tor is in anonymous hidden service mode
4842 * 512 Tor is in non-anonymous hidden service mode
4843 * (I've deliberately written them out in full here to aid searchability.)
4845 connection_printf_to_buf(conn
, "512 Tor is in %sanonymous hidden service "
4847 non_anonymous
? "" : "non-");
4851 /* Parse the "keytype:keyblob" argument. */
4853 add_onion_secret_key_t pk
= { NULL
};
4854 const char *key_new_alg
= NULL
;
4855 char *key_new_blob
= NULL
;
4856 char *err_msg
= NULL
;
4858 if (add_onion_helper_keyarg(smartlist_get(args
, 0), discard_pk
,
4859 &key_new_alg
, &key_new_blob
, &pk
, &hs_version
,
4862 connection_write_str_to_buf(err_msg
, conn
);
4867 tor_assert(!err_msg
);
4869 /* Hidden service version 3 don't have client authentication support so if
4870 * ClientAuth was given, send back an error. */
4871 if (hs_version
== HS_VERSION_THREE
&& auth_clients
) {
4872 connection_printf_to_buf(conn
, "513 ClientAuth not supported\r\n");
4876 /* Create the HS, using private key pk, client authentication auth_type,
4877 * the list of auth_clients, and port config port_cfg.
4878 * rend_service_add_ephemeral() will take ownership of pk and port_cfg,
4879 * regardless of success/failure.
4881 char *service_id
= NULL
;
4882 int ret
= add_onion_helper_add_service(hs_version
, &pk
, port_cfgs
,
4884 max_streams_close_circuit
, auth_type
,
4885 auth_clients
, &service_id
);
4886 port_cfgs
= NULL
; /* port_cfgs is now owned by the rendservice code. */
4887 auth_clients
= NULL
; /* so is auth_clients */
4892 if (!detached_onion_services
)
4893 detached_onion_services
= smartlist_new();
4894 smartlist_add(detached_onion_services
, service_id
);
4896 if (!conn
->ephemeral_onion_services
)
4897 conn
->ephemeral_onion_services
= smartlist_new();
4898 smartlist_add(conn
->ephemeral_onion_services
, service_id
);
4901 tor_assert(service_id
);
4902 connection_printf_to_buf(conn
, "250-ServiceID=%s\r\n", service_id
);
4904 tor_assert(key_new_blob
);
4905 connection_printf_to_buf(conn
, "250-PrivateKey=%s:%s\r\n",
4906 key_new_alg
, key_new_blob
);
4908 if (auth_created_clients
) {
4909 SMARTLIST_FOREACH(auth_created_clients
, rend_authorized_client_t
*, ac
, {
4910 char *encoded
= rend_auth_encode_cookie(ac
->descriptor_cookie
,
4912 tor_assert(encoded
);
4913 connection_printf_to_buf(conn
, "250-ClientAuth=%s:%s\r\n",
4914 ac
->client_name
, encoded
);
4915 memwipe(encoded
, 0, strlen(encoded
));
4920 connection_printf_to_buf(conn
, "250 OK\r\n");
4923 case RSAE_BADPRIVKEY
:
4924 connection_printf_to_buf(conn
, "551 Failed to generate onion address\r\n");
4926 case RSAE_ADDREXISTS
:
4927 connection_printf_to_buf(conn
, "550 Onion address collision\r\n");
4929 case RSAE_BADVIRTPORT
:
4930 connection_printf_to_buf(conn
, "512 Invalid VIRTPORT/TARGET\r\n");
4933 connection_printf_to_buf(conn
, "512 Invalid client authorization\r\n");
4935 case RSAE_INTERNAL
: /* FALLSTHROUGH */
4937 connection_printf_to_buf(conn
, "551 Failed to add Onion Service\r\n");
4940 memwipe(key_new_blob
, 0, strlen(key_new_blob
));
4941 tor_free(key_new_blob
);
4946 SMARTLIST_FOREACH(port_cfgs
, rend_service_port_config_t
*, p
,
4947 rend_service_port_config_free(p
));
4948 smartlist_free(port_cfgs
);
4952 SMARTLIST_FOREACH(auth_clients
, rend_authorized_client_t
*, ac
,
4953 rend_authorized_client_free(ac
));
4954 smartlist_free(auth_clients
);
4956 if (auth_created_clients
) {
4957 // Do not free entries; they are the same as auth_clients
4958 smartlist_free(auth_created_clients
);
4961 SMARTLIST_FOREACH(args
, char *, cp
, {
4962 memwipe(cp
, 0, strlen(cp
));
4965 smartlist_free(args
);
4969 /** Helper function to handle parsing the KeyType:KeyBlob argument to the
4970 * ADD_ONION command. Return a new crypto_pk_t and if a new key was generated
4971 * and the private key not discarded, the algorithm and serialized private key,
4972 * or NULL and an optional control protocol error message on failure. The
4973 * caller is responsible for freeing the returned key_new_blob and err_msg.
4975 * Note: The error messages returned are deliberately vague to avoid echoing
4979 add_onion_helper_keyarg(const char *arg
, int discard_pk
,
4980 const char **key_new_alg_out
, char **key_new_blob_out
,
4981 add_onion_secret_key_t
*decoded_key
, int *hs_version
,
4984 smartlist_t
*key_args
= smartlist_new();
4985 crypto_pk_t
*pk
= NULL
;
4986 const char *key_new_alg
= NULL
;
4987 char *key_new_blob
= NULL
;
4988 char *err_msg
= NULL
;
4991 smartlist_split_string(key_args
, arg
, ":", SPLIT_IGNORE_BLANK
, 0);
4992 if (smartlist_len(key_args
) != 2) {
4993 err_msg
= tor_strdup("512 Invalid key type/blob\r\n");
4997 /* The format is "KeyType:KeyBlob". */
4998 static const char *key_type_new
= "NEW";
4999 static const char *key_type_best
= "BEST";
5000 static const char *key_type_rsa1024
= "RSA1024";
5001 static const char *key_type_ed25519_v3
= "ED25519-V3";
5003 const char *key_type
= smartlist_get(key_args
, 0);
5004 const char *key_blob
= smartlist_get(key_args
, 1);
5006 if (!strcasecmp(key_type_rsa1024
, key_type
)) {
5007 /* "RSA:<Base64 Blob>" - Loading a pre-existing RSA1024 key. */
5008 pk
= crypto_pk_base64_decode_private(key_blob
, strlen(key_blob
));
5010 err_msg
= tor_strdup("512 Failed to decode RSA key\r\n");
5013 if (crypto_pk_num_bits(pk
) != PK_BYTES
*8) {
5015 err_msg
= tor_strdup("512 Invalid RSA key size\r\n");
5018 decoded_key
->v2
= pk
;
5019 *hs_version
= HS_VERSION_TWO
;
5020 } else if (!strcasecmp(key_type_ed25519_v3
, key_type
)) {
5021 /* "ED25519-V3:<Base64 Blob>" - Loading a pre-existing ed25519 key. */
5022 ed25519_secret_key_t
*sk
= tor_malloc_zero(sizeof(*sk
));
5023 if (base64_decode((char *) sk
->seckey
, sizeof(sk
->seckey
), key_blob
,
5024 strlen(key_blob
)) != sizeof(sk
->seckey
)) {
5026 err_msg
= tor_strdup("512 Failed to decode ED25519-V3 key\r\n");
5029 decoded_key
->v3
= sk
;
5030 *hs_version
= HS_VERSION_THREE
;
5031 } else if (!strcasecmp(key_type_new
, key_type
)) {
5032 /* "NEW:<Algorithm>" - Generating a new key, blob as algorithm. */
5033 if (!strcasecmp(key_type_rsa1024
, key_blob
) ||
5034 !strcasecmp(key_type_best
, key_blob
)) {
5035 /* "RSA1024", RSA 1024 bit, also currently "BEST" by default. */
5036 pk
= crypto_pk_new();
5037 if (crypto_pk_generate_key(pk
)) {
5038 tor_asprintf(&err_msg
, "551 Failed to generate %s key\r\n",
5043 if (crypto_pk_base64_encode_private(pk
, &key_new_blob
)) {
5045 tor_asprintf(&err_msg
, "551 Failed to encode %s key\r\n",
5049 key_new_alg
= key_type_rsa1024
;
5051 decoded_key
->v2
= pk
;
5052 *hs_version
= HS_VERSION_TWO
;
5053 } else if (!strcasecmp(key_type_ed25519_v3
, key_blob
)) {
5054 ed25519_secret_key_t
*sk
= tor_malloc_zero(sizeof(*sk
));
5055 if (ed25519_secret_key_generate(sk
, 1) < 0) {
5057 tor_asprintf(&err_msg
, "551 Failed to generate %s key\r\n",
5058 key_type_ed25519_v3
);
5062 ssize_t len
= base64_encode_size(sizeof(sk
->seckey
), 0) + 1;
5063 key_new_blob
= tor_malloc_zero(len
);
5064 if (base64_encode(key_new_blob
, len
, (const char *) sk
->seckey
,
5065 sizeof(sk
->seckey
), 0) != (len
- 1)) {
5067 tor_free(key_new_blob
);
5068 tor_asprintf(&err_msg
, "551 Failed to encode %s key\r\n",
5069 key_type_ed25519_v3
);
5072 key_new_alg
= key_type_ed25519_v3
;
5074 decoded_key
->v3
= sk
;
5075 *hs_version
= HS_VERSION_THREE
;
5077 err_msg
= tor_strdup("513 Invalid key type\r\n");
5081 err_msg
= tor_strdup("513 Invalid key type\r\n");
5085 /* Succeeded in loading or generating a private key. */
5089 SMARTLIST_FOREACH(key_args
, char *, cp
, {
5090 memwipe(cp
, 0, strlen(cp
));
5093 smartlist_free(key_args
);
5096 *err_msg_out
= err_msg
;
5100 *key_new_alg_out
= key_new_alg
;
5101 *key_new_blob_out
= key_new_blob
;
5106 /** Helper function to handle parsing a ClientAuth argument to the
5107 * ADD_ONION command. Return a new rend_authorized_client_t, or NULL
5108 * and an optional control protocol error message on failure. The
5109 * caller is responsible for freeing the returned auth_client and err_msg.
5111 * If 'created' is specified, it will be set to 1 when a new cookie has
5114 STATIC rend_authorized_client_t
*
5115 add_onion_helper_clientauth(const char *arg
, int *created
, char **err_msg
)
5120 tor_assert(created
);
5121 tor_assert(err_msg
);
5124 smartlist_t
*auth_args
= smartlist_new();
5125 rend_authorized_client_t
*client
=
5126 tor_malloc_zero(sizeof(rend_authorized_client_t
));
5127 smartlist_split_string(auth_args
, arg
, ":", 0, 0);
5128 if (smartlist_len(auth_args
) < 1 || smartlist_len(auth_args
) > 2) {
5129 *err_msg
= tor_strdup("512 Invalid ClientAuth syntax\r\n");
5132 client
->client_name
= tor_strdup(smartlist_get(auth_args
, 0));
5133 if (smartlist_len(auth_args
) == 2) {
5134 char *decode_err_msg
= NULL
;
5135 if (rend_auth_decode_cookie(smartlist_get(auth_args
, 1),
5136 client
->descriptor_cookie
,
5137 NULL
, &decode_err_msg
) < 0) {
5138 tor_assert(decode_err_msg
);
5139 tor_asprintf(err_msg
, "512 %s\r\n", decode_err_msg
);
5140 tor_free(decode_err_msg
);
5145 crypto_rand((char *) client
->descriptor_cookie
, REND_DESC_COOKIE_LEN
);
5149 if (!rend_valid_client_name(client
->client_name
)) {
5150 *err_msg
= tor_strdup("512 Invalid name in ClientAuth\r\n");
5156 SMARTLIST_FOREACH(auth_args
, char *, item
, tor_free(item
));
5157 smartlist_free(auth_args
);
5159 rend_authorized_client_free(client
);
5165 /** Called when we get a DEL_ONION command; parse the body, and remove
5166 * the existing ephemeral Onion Service. */
5168 handle_control_del_onion(control_connection_t
*conn
,
5174 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
5175 args
= getargs_helper("DEL_ONION", conn
, body
, 1, 1);
5179 const char *service_id
= smartlist_get(args
, 0);
5180 if (rend_valid_v2_service_id(service_id
)) {
5181 hs_version
= HS_VERSION_TWO
;
5182 } else if (hs_address_is_valid(service_id
)) {
5183 hs_version
= HS_VERSION_THREE
;
5185 connection_printf_to_buf(conn
, "512 Malformed Onion Service id\r\n");
5189 /* Determine if the onion service belongs to this particular control
5190 * connection, or if it is in the global list of detached services. If it
5191 * is in neither, either the service ID is invalid in some way, or it
5192 * explicitly belongs to a different control connection, and an error
5193 * should be returned.
5195 smartlist_t
*services
[2] = {
5196 conn
->ephemeral_onion_services
,
5197 detached_onion_services
5199 smartlist_t
*onion_services
= NULL
;
5201 for (size_t i
= 0; i
< ARRAY_LENGTH(services
); i
++) {
5202 idx
= smartlist_string_pos(services
[i
], service_id
);
5204 onion_services
= services
[i
];
5208 if (onion_services
== NULL
) {
5209 connection_printf_to_buf(conn
, "552 Unknown Onion Service id\r\n");
5212 switch (hs_version
) {
5213 case HS_VERSION_TWO
:
5214 ret
= rend_service_del_ephemeral(service_id
);
5216 case HS_VERSION_THREE
:
5217 ret
= hs_service_del_ephemeral(service_id
);
5220 /* The ret value will be -1 thus hitting the warning below. This should
5221 * never happen because of the check at the start of the function. */
5225 /* This should *NEVER* fail, since the service is on either the
5226 * per-control connection list, or the global one.
5228 log_warn(LD_BUG
, "Failed to remove Onion Service %s.",
5229 escaped(service_id
));
5230 tor_fragile_assert();
5233 /* Remove/scrub the service_id from the appropriate list. */
5234 char *cp
= smartlist_get(onion_services
, idx
);
5235 smartlist_del(onion_services
, idx
);
5236 memwipe(cp
, 0, strlen(cp
));
5239 send_control_done(conn
);
5243 SMARTLIST_FOREACH(args
, char *, cp
, {
5244 memwipe(cp
, 0, strlen(cp
));
5247 smartlist_free(args
);
5251 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
5253 connection_control_finished_flushing(control_connection_t
*conn
)
5259 /** Called when <b>conn</b> has gotten its socket closed. */
5261 connection_control_reached_eof(control_connection_t
*conn
)
5265 log_info(LD_CONTROL
,"Control connection reached EOF. Closing.");
5266 connection_mark_for_close(TO_CONN(conn
));
5270 /** Shut down this Tor instance in the same way that SIGINT would, but
5271 * with a log message appropriate for the loss of an owning controller. */
5273 lost_owning_controller(const char *owner_type
, const char *loss_manner
)
5275 log_notice(LD_CONTROL
, "Owning controller %s has %s -- exiting now.",
5276 owner_type
, loss_manner
);
5278 activate_signal(SIGTERM
);
5281 /** Called when <b>conn</b> is being freed. */
5283 connection_control_closed(control_connection_t
*conn
)
5287 conn
->event_mask
= 0;
5288 control_update_global_event_mask();
5290 /* Close all ephemeral Onion Services if any.
5291 * The list and it's contents are scrubbed/freed in connection_free_.
5293 if (conn
->ephemeral_onion_services
) {
5294 SMARTLIST_FOREACH_BEGIN(conn
->ephemeral_onion_services
, char *, cp
) {
5295 if (rend_valid_v2_service_id(cp
)) {
5296 rend_service_del_ephemeral(cp
);
5297 } else if (hs_address_is_valid(cp
)) {
5298 hs_service_del_ephemeral(cp
);
5300 /* An invalid .onion in our list should NEVER happen */
5301 tor_fragile_assert();
5303 } SMARTLIST_FOREACH_END(cp
);
5306 if (conn
->is_owning_control_connection
) {
5307 lost_owning_controller("connection", "closed");
5311 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
5312 * stage of the protocol. */
5314 is_valid_initial_command(control_connection_t
*conn
, const char *cmd
)
5316 if (conn
->base_
.state
== CONTROL_CONN_STATE_OPEN
)
5318 if (!strcasecmp(cmd
, "PROTOCOLINFO"))
5319 return (!conn
->have_sent_protocolinfo
&&
5320 conn
->safecookie_client_hash
== NULL
);
5321 if (!strcasecmp(cmd
, "AUTHCHALLENGE"))
5322 return (conn
->safecookie_client_hash
== NULL
);
5323 if (!strcasecmp(cmd
, "AUTHENTICATE") ||
5324 !strcasecmp(cmd
, "QUIT"))
5329 /** Do not accept any control command of more than 1MB in length. Anything
5330 * that needs to be anywhere near this long probably means that one of our
5331 * interfaces is broken. */
5332 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
5334 /** Wrapper around peek_buf_has_control0 command: presents the same
5335 * interface as that underlying functions, but takes a connection_t intead of
5339 peek_connection_has_control0_command(connection_t
*conn
)
5341 return peek_buf_has_control0_command(conn
->inbuf
);
5345 peek_connection_has_http_command(connection_t
*conn
)
5347 return peek_buf_has_http_command(conn
->inbuf
);
5350 static const char CONTROLPORT_IS_NOT_AN_HTTP_PROXY_MSG
[] =
5351 "HTTP/1.0 501 Tor ControlPort is not an HTTP proxy"
5352 "\r\nContent-Type: text/html; charset=iso-8859-1\r\n\r\n"
5355 "<title>Tor's ControlPort is not an HTTP proxy</title>\n"
5358 "<h1>Tor's ControlPort is not an HTTP proxy</h1>\n"
5360 "It appears you have configured your web browser to use Tor's control port"
5361 " as an HTTP proxy.\n"
5362 "This is not correct: Tor's default SOCKS proxy port is 9050.\n"
5363 "Please configure your client accordingly.\n"
5366 "See <a href=\"https://www.torproject.org/documentation.html\">"
5367 "https://www.torproject.org/documentation.html</a> for more "
5369 "<!-- Plus this comment, to make the body response more than 512 bytes, so "
5370 " IE will be willing to display it. Comment comment comment comment "
5371 " comment comment comment comment comment comment comment comment.-->\n"
5376 /** Called when data has arrived on a v1 control connection: Try to fetch
5377 * commands from conn->inbuf, and execute them.
5380 connection_control_process_inbuf(control_connection_t
*conn
)
5383 uint32_t cmd_data_len
;
5388 tor_assert(conn
->base_
.state
== CONTROL_CONN_STATE_OPEN
||
5389 conn
->base_
.state
== CONTROL_CONN_STATE_NEEDAUTH
);
5391 if (!conn
->incoming_cmd
) {
5392 conn
->incoming_cmd
= tor_malloc(1024);
5393 conn
->incoming_cmd_len
= 1024;
5394 conn
->incoming_cmd_cur_len
= 0;
5397 if (conn
->base_
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
5398 peek_connection_has_control0_command(TO_CONN(conn
))) {
5399 /* Detect v0 commands and send a "no more v0" message. */
5402 set_uint16(buf
+2, htons(0x0000)); /* type == error */
5403 set_uint16(buf
+4, htons(0x0001)); /* code == internal error */
5404 strlcpy(buf
+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
5405 "and later; upgrade your controller.",
5407 body_len
= 2+strlen(buf
+6)+2; /* code, msg, nul. */
5408 set_uint16(buf
+0, htons(body_len
));
5409 connection_buf_add(buf
, 4+body_len
, TO_CONN(conn
));
5411 connection_mark_and_flush(TO_CONN(conn
));
5415 /* If the user has the HTTP proxy port and the control port confused. */
5416 if (conn
->base_
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
5417 peek_connection_has_http_command(TO_CONN(conn
))) {
5418 connection_write_str_to_buf(CONTROLPORT_IS_NOT_AN_HTTP_PROXY_MSG
, conn
);
5419 log_notice(LD_CONTROL
, "Received HTTP request on ControlPort");
5420 connection_mark_and_flush(TO_CONN(conn
));
5428 /* First, fetch a line. */
5430 data_len
= conn
->incoming_cmd_len
- conn
->incoming_cmd_cur_len
;
5431 r
= connection_buf_get_line(TO_CONN(conn
),
5432 conn
->incoming_cmd
+conn
->incoming_cmd_cur_len
,
5435 /* Line not all here yet. Wait. */
5438 if (data_len
+ conn
->incoming_cmd_cur_len
> MAX_COMMAND_LINE_LENGTH
) {
5439 connection_write_str_to_buf("500 Line too long.\r\n", conn
);
5440 connection_stop_reading(TO_CONN(conn
));
5441 connection_mark_and_flush(TO_CONN(conn
));
5443 while (conn
->incoming_cmd_len
< data_len
+conn
->incoming_cmd_cur_len
)
5444 conn
->incoming_cmd_len
*= 2;
5445 conn
->incoming_cmd
= tor_realloc(conn
->incoming_cmd
,
5446 conn
->incoming_cmd_len
);
5450 tor_assert(data_len
);
5452 last_idx
= conn
->incoming_cmd_cur_len
;
5453 conn
->incoming_cmd_cur_len
+= (int)data_len
;
5455 /* We have appended a line to incoming_cmd. Is the command done? */
5456 if (last_idx
== 0 && *conn
->incoming_cmd
!= '+')
5457 /* One line command, didn't start with '+'. */
5459 /* XXXX this code duplication is kind of dumb. */
5460 if (last_idx
+3 == conn
->incoming_cmd_cur_len
&&
5461 tor_memeq(conn
->incoming_cmd
+ last_idx
, ".\r\n", 3)) {
5462 /* Just appended ".\r\n"; we're done. Remove it. */
5463 conn
->incoming_cmd
[last_idx
] = '\0';
5464 conn
->incoming_cmd_cur_len
-= 3;
5466 } else if (last_idx
+2 == conn
->incoming_cmd_cur_len
&&
5467 tor_memeq(conn
->incoming_cmd
+ last_idx
, ".\n", 2)) {
5468 /* Just appended ".\n"; we're done. Remove it. */
5469 conn
->incoming_cmd
[last_idx
] = '\0';
5470 conn
->incoming_cmd_cur_len
-= 2;
5473 /* Otherwise, read another line. */
5475 data_len
= conn
->incoming_cmd_cur_len
;
5476 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
5480 while ((size_t)cmd_len
< data_len
5481 && !TOR_ISSPACE(conn
->incoming_cmd
[cmd_len
]))
5484 conn
->incoming_cmd
[cmd_len
]='\0';
5485 args
= conn
->incoming_cmd
+cmd_len
+1;
5486 tor_assert(data_len
>(size_t)cmd_len
);
5487 data_len
-= (cmd_len
+1); /* skip the command and NUL we added after it */
5488 while (TOR_ISSPACE(*args
)) {
5493 /* If the connection is already closing, ignore further commands */
5494 if (TO_CONN(conn
)->marked_for_close
) {
5498 /* Otherwise, Quit is always valid. */
5499 if (!strcasecmp(conn
->incoming_cmd
, "QUIT")) {
5500 connection_write_str_to_buf("250 closing connection\r\n", conn
);
5501 connection_mark_and_flush(TO_CONN(conn
));
5505 if (conn
->base_
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
5506 !is_valid_initial_command(conn
, conn
->incoming_cmd
)) {
5507 connection_write_str_to_buf("514 Authentication required.\r\n", conn
);
5508 connection_mark_for_close(TO_CONN(conn
));
5512 if (data_len
>= UINT32_MAX
) {
5513 connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn
);
5514 connection_mark_for_close(TO_CONN(conn
));
5518 /* XXXX Why is this not implemented as a table like the GETINFO
5519 * items are? Even handling the plus signs at the beginnings of
5520 * commands wouldn't be very hard with proper macros. */
5521 cmd_data_len
= (uint32_t)data_len
;
5522 if (!strcasecmp(conn
->incoming_cmd
, "SETCONF")) {
5523 if (handle_control_setconf(conn
, cmd_data_len
, args
))
5525 } else if (!strcasecmp(conn
->incoming_cmd
, "RESETCONF")) {
5526 if (handle_control_resetconf(conn
, cmd_data_len
, args
))
5528 } else if (!strcasecmp(conn
->incoming_cmd
, "GETCONF")) {
5529 if (handle_control_getconf(conn
, cmd_data_len
, args
))
5531 } else if (!strcasecmp(conn
->incoming_cmd
, "+LOADCONF")) {
5532 if (handle_control_loadconf(conn
, cmd_data_len
, args
))
5534 } else if (!strcasecmp(conn
->incoming_cmd
, "SETEVENTS")) {
5535 if (handle_control_setevents(conn
, cmd_data_len
, args
))
5537 } else if (!strcasecmp(conn
->incoming_cmd
, "AUTHENTICATE")) {
5538 if (handle_control_authenticate(conn
, cmd_data_len
, args
))
5540 } else if (!strcasecmp(conn
->incoming_cmd
, "SAVECONF")) {
5541 if (handle_control_saveconf(conn
, cmd_data_len
, args
))
5543 } else if (!strcasecmp(conn
->incoming_cmd
, "SIGNAL")) {
5544 if (handle_control_signal(conn
, cmd_data_len
, args
))
5546 } else if (!strcasecmp(conn
->incoming_cmd
, "TAKEOWNERSHIP")) {
5547 if (handle_control_takeownership(conn
, cmd_data_len
, args
))
5549 } else if (!strcasecmp(conn
->incoming_cmd
, "MAPADDRESS")) {
5550 if (handle_control_mapaddress(conn
, cmd_data_len
, args
))
5552 } else if (!strcasecmp(conn
->incoming_cmd
, "GETINFO")) {
5553 if (handle_control_getinfo(conn
, cmd_data_len
, args
))
5555 } else if (!strcasecmp(conn
->incoming_cmd
, "EXTENDCIRCUIT")) {
5556 if (handle_control_extendcircuit(conn
, cmd_data_len
, args
))
5558 } else if (!strcasecmp(conn
->incoming_cmd
, "SETCIRCUITPURPOSE")) {
5559 if (handle_control_setcircuitpurpose(conn
, cmd_data_len
, args
))
5561 } else if (!strcasecmp(conn
->incoming_cmd
, "SETROUTERPURPOSE")) {
5562 connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn
);
5563 } else if (!strcasecmp(conn
->incoming_cmd
, "ATTACHSTREAM")) {
5564 if (handle_control_attachstream(conn
, cmd_data_len
, args
))
5566 } else if (!strcasecmp(conn
->incoming_cmd
, "+POSTDESCRIPTOR")) {
5567 if (handle_control_postdescriptor(conn
, cmd_data_len
, args
))
5569 } else if (!strcasecmp(conn
->incoming_cmd
, "REDIRECTSTREAM")) {
5570 if (handle_control_redirectstream(conn
, cmd_data_len
, args
))
5572 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSESTREAM")) {
5573 if (handle_control_closestream(conn
, cmd_data_len
, args
))
5575 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSECIRCUIT")) {
5576 if (handle_control_closecircuit(conn
, cmd_data_len
, args
))
5578 } else if (!strcasecmp(conn
->incoming_cmd
, "USEFEATURE")) {
5579 if (handle_control_usefeature(conn
, cmd_data_len
, args
))
5581 } else if (!strcasecmp(conn
->incoming_cmd
, "RESOLVE")) {
5582 if (handle_control_resolve(conn
, cmd_data_len
, args
))
5584 } else if (!strcasecmp(conn
->incoming_cmd
, "PROTOCOLINFO")) {
5585 if (handle_control_protocolinfo(conn
, cmd_data_len
, args
))
5587 } else if (!strcasecmp(conn
->incoming_cmd
, "AUTHCHALLENGE")) {
5588 if (handle_control_authchallenge(conn
, cmd_data_len
, args
))
5590 } else if (!strcasecmp(conn
->incoming_cmd
, "DROPGUARDS")) {
5591 if (handle_control_dropguards(conn
, cmd_data_len
, args
))
5593 } else if (!strcasecmp(conn
->incoming_cmd
, "HSFETCH")) {
5594 if (handle_control_hsfetch(conn
, cmd_data_len
, args
))
5596 } else if (!strcasecmp(conn
->incoming_cmd
, "+HSPOST")) {
5597 if (handle_control_hspost(conn
, cmd_data_len
, args
))
5599 } else if (!strcasecmp(conn
->incoming_cmd
, "ADD_ONION")) {
5600 int ret
= handle_control_add_onion(conn
, cmd_data_len
, args
);
5601 memwipe(args
, 0, cmd_data_len
); /* Scrub the private key. */
5604 } else if (!strcasecmp(conn
->incoming_cmd
, "DEL_ONION")) {
5605 int ret
= handle_control_del_onion(conn
, cmd_data_len
, args
);
5606 memwipe(args
, 0, cmd_data_len
); /* Scrub the service id/pk. */
5610 connection_printf_to_buf(conn
, "510 Unrecognized command \"%s\"\r\n",
5611 conn
->incoming_cmd
);
5614 conn
->incoming_cmd_cur_len
= 0;
5618 /** Something major has happened to circuit <b>circ</b>: tell any
5619 * interested control connections. */
5621 control_event_circuit_status(origin_circuit_t
*circ
, circuit_status_event_t tp
,
5625 char reasons
[64] = "";
5626 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS
))
5632 case CIRC_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
5633 case CIRC_EVENT_BUILT
: status
= "BUILT"; break;
5634 case CIRC_EVENT_EXTENDED
: status
= "EXTENDED"; break;
5635 case CIRC_EVENT_FAILED
: status
= "FAILED"; break;
5636 case CIRC_EVENT_CLOSED
: status
= "CLOSED"; break;
5638 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
5639 tor_fragile_assert();
5643 if (tp
== CIRC_EVENT_FAILED
|| tp
== CIRC_EVENT_CLOSED
) {
5644 const char *reason_str
= circuit_end_reason_to_control_string(reason_code
);
5645 char unk_reason_buf
[16];
5647 tor_snprintf(unk_reason_buf
, 16, "UNKNOWN_%d", reason_code
);
5648 reason_str
= unk_reason_buf
;
5650 if (reason_code
> 0 && reason_code
& END_CIRC_REASON_FLAG_REMOTE
) {
5651 tor_snprintf(reasons
, sizeof(reasons
),
5652 " REASON=DESTROYED REMOTE_REASON=%s", reason_str
);
5654 tor_snprintf(reasons
, sizeof(reasons
),
5655 " REASON=%s", reason_str
);
5660 char *circdesc
= circuit_describe_status_for_controller(circ
);
5661 const char *sp
= strlen(circdesc
) ? " " : "";
5662 send_control_event(EVENT_CIRCUIT_STATUS
,
5663 "650 CIRC %lu %s%s%s%s\r\n",
5664 (unsigned long)circ
->global_identifier
,
5674 /** Something minor has happened to circuit <b>circ</b>: tell any
5675 * interested control connections. */
5677 control_event_circuit_status_minor(origin_circuit_t
*circ
,
5678 circuit_status_minor_event_t e
,
5679 int purpose
, const struct timeval
*tv
)
5681 const char *event_desc
;
5682 char event_tail
[160] = "";
5683 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR
))
5689 case CIRC_MINOR_EVENT_PURPOSE_CHANGED
:
5690 event_desc
= "PURPOSE_CHANGED";
5693 /* event_tail can currently be up to 68 chars long */
5694 const char *hs_state_str
=
5695 circuit_purpose_to_controller_hs_state_string(purpose
);
5696 tor_snprintf(event_tail
, sizeof(event_tail
),
5697 " OLD_PURPOSE=%s%s%s",
5698 circuit_purpose_to_controller_string(purpose
),
5699 (hs_state_str
!= NULL
) ? " OLD_HS_STATE=" : "",
5700 (hs_state_str
!= NULL
) ? hs_state_str
: "");
5704 case CIRC_MINOR_EVENT_CANNIBALIZED
:
5705 event_desc
= "CANNIBALIZED";
5708 /* event_tail can currently be up to 130 chars long */
5709 const char *hs_state_str
=
5710 circuit_purpose_to_controller_hs_state_string(purpose
);
5711 const struct timeval
*old_timestamp_began
= tv
;
5712 char tbuf
[ISO_TIME_USEC_LEN
+1];
5713 format_iso_time_nospace_usec(tbuf
, old_timestamp_began
);
5715 tor_snprintf(event_tail
, sizeof(event_tail
),
5716 " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
5717 circuit_purpose_to_controller_string(purpose
),
5718 (hs_state_str
!= NULL
) ? " OLD_HS_STATE=" : "",
5719 (hs_state_str
!= NULL
) ? hs_state_str
: "",
5725 log_warn(LD_BUG
, "Unrecognized status code %d", (int)e
);
5726 tor_fragile_assert();
5731 char *circdesc
= circuit_describe_status_for_controller(circ
);
5732 const char *sp
= strlen(circdesc
) ? " " : "";
5733 send_control_event(EVENT_CIRCUIT_STATUS_MINOR
,
5734 "650 CIRC_MINOR %lu %s%s%s%s\r\n",
5735 (unsigned long)circ
->global_identifier
,
5746 * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
5747 * interested controllers.
5750 control_event_circuit_purpose_changed(origin_circuit_t
*circ
,
5753 return control_event_circuit_status_minor(circ
,
5754 CIRC_MINOR_EVENT_PURPOSE_CHANGED
,
5760 * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
5761 * created-time from <b>old_tv_created</b>: tell any interested controllers.
5764 control_event_circuit_cannibalized(origin_circuit_t
*circ
,
5766 const struct timeval
*old_tv_created
)
5768 return control_event_circuit_status_minor(circ
,
5769 CIRC_MINOR_EVENT_CANNIBALIZED
,
5774 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
5775 * <b>buf</b>, determine the address:port combination requested on
5776 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
5779 write_stream_target_to_buf(entry_connection_t
*conn
, char *buf
, size_t len
)
5782 if (conn
->chosen_exit_name
)
5783 if (tor_snprintf(buf2
, sizeof(buf2
), ".%s.exit", conn
->chosen_exit_name
)<0)
5785 if (!conn
->socks_request
)
5787 if (tor_snprintf(buf
, len
, "%s%s%s:%d",
5788 conn
->socks_request
->address
,
5789 conn
->chosen_exit_name
? buf2
: "",
5790 !conn
->chosen_exit_name
&& connection_edge_is_rendezvous_stream(
5791 ENTRY_TO_EDGE_CONN(conn
)) ? ".onion" : "",
5792 conn
->socks_request
->port
)<0)
5797 /** Something has happened to the stream associated with AP connection
5798 * <b>conn</b>: tell any interested control connections. */
5800 control_event_stream_status(entry_connection_t
*conn
, stream_status_event_t tp
,
5803 char reason_buf
[64];
5804 char addrport_buf
[64];
5807 origin_circuit_t
*origin_circ
= NULL
;
5809 const char *purpose
= "";
5810 tor_assert(conn
->socks_request
);
5812 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS
))
5815 if (tp
== STREAM_EVENT_CLOSED
&&
5816 (reason_code
& END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
))
5819 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
5821 reason_buf
[0] = '\0';
5824 case STREAM_EVENT_SENT_CONNECT
: status
= "SENTCONNECT"; break;
5825 case STREAM_EVENT_SENT_RESOLVE
: status
= "SENTRESOLVE"; break;
5826 case STREAM_EVENT_SUCCEEDED
: status
= "SUCCEEDED"; break;
5827 case STREAM_EVENT_FAILED
: status
= "FAILED"; break;
5828 case STREAM_EVENT_CLOSED
: status
= "CLOSED"; break;
5829 case STREAM_EVENT_NEW
: status
= "NEW"; break;
5830 case STREAM_EVENT_NEW_RESOLVE
: status
= "NEWRESOLVE"; break;
5831 case STREAM_EVENT_FAILED_RETRIABLE
: status
= "DETACHED"; break;
5832 case STREAM_EVENT_REMAP
: status
= "REMAP"; break;
5834 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
5837 if (reason_code
&& (tp
== STREAM_EVENT_FAILED
||
5838 tp
== STREAM_EVENT_CLOSED
||
5839 tp
== STREAM_EVENT_FAILED_RETRIABLE
)) {
5840 const char *reason_str
= stream_end_reason_to_control_string(reason_code
);
5843 tor_asprintf(&r
, " UNKNOWN_%d", reason_code
);
5846 if (reason_code
& END_STREAM_REASON_FLAG_REMOTE
)
5847 tor_snprintf(reason_buf
, sizeof(reason_buf
),
5848 " REASON=END REMOTE_REASON=%s", reason_str
);
5850 tor_snprintf(reason_buf
, sizeof(reason_buf
),
5851 " REASON=%s", reason_str
);
5853 } else if (reason_code
&& tp
== STREAM_EVENT_REMAP
) {
5854 switch (reason_code
) {
5855 case REMAP_STREAM_SOURCE_CACHE
:
5856 strlcpy(reason_buf
, " SOURCE=CACHE", sizeof(reason_buf
));
5858 case REMAP_STREAM_SOURCE_EXIT
:
5859 strlcpy(reason_buf
, " SOURCE=EXIT", sizeof(reason_buf
));
5862 tor_snprintf(reason_buf
, sizeof(reason_buf
), " REASON=UNKNOWN_%d",
5864 /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
5869 if (tp
== STREAM_EVENT_NEW
|| tp
== STREAM_EVENT_NEW_RESOLVE
) {
5871 * When the control conn is an AF_UNIX socket and we have no address,
5872 * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
5875 if (strcmp(ENTRY_TO_CONN(conn
)->address
, "(Tor_internal)") != 0) {
5876 tor_snprintf(addrport_buf
,sizeof(addrport_buf
), " SOURCE_ADDR=%s:%d",
5877 ENTRY_TO_CONN(conn
)->address
, ENTRY_TO_CONN(conn
)->port
);
5880 * else leave it blank so control on AF_UNIX doesn't need to make
5883 addrport_buf
[0] = '\0';
5886 addrport_buf
[0] = '\0';
5889 if (tp
== STREAM_EVENT_NEW_RESOLVE
) {
5890 purpose
= " PURPOSE=DNS_REQUEST";
5891 } else if (tp
== STREAM_EVENT_NEW
) {
5892 if (conn
->use_begindir
) {
5893 connection_t
*linked
= ENTRY_TO_CONN(conn
)->linked_conn
;
5894 int linked_dir_purpose
= -1;
5895 if (linked
&& linked
->type
== CONN_TYPE_DIR
)
5896 linked_dir_purpose
= linked
->purpose
;
5897 if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose
))
5898 purpose
= " PURPOSE=DIR_UPLOAD";
5900 purpose
= " PURPOSE=DIR_FETCH";
5902 purpose
= " PURPOSE=USER";
5905 circ
= circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn
));
5906 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
5907 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
5908 send_control_event(EVENT_STREAM_STATUS
,
5909 "650 STREAM %"PRIu64
" %s %lu %s%s%s%s\r\n",
5910 (ENTRY_TO_CONN(conn
)->global_identifier
),
5913 (unsigned long)origin_circ
->global_identifier
: 0ul,
5914 buf
, reason_buf
, addrport_buf
, purpose
);
5916 /* XXX need to specify its intended exit, etc? */
5921 /** Figure out the best name for the target router of an OR connection
5922 * <b>conn</b>, and write it into the <b>len</b>-character buffer
5925 orconn_target_get_name(char *name
, size_t len
, or_connection_t
*conn
)
5927 const node_t
*node
= node_get_by_id(conn
->identity_digest
);
5929 tor_assert(len
> MAX_VERBOSE_NICKNAME_LEN
);
5930 node_get_verbose_nickname(node
, name
);
5931 } else if (! tor_digest_is_zero(conn
->identity_digest
)) {
5933 base16_encode(name
+1, len
-1, conn
->identity_digest
,
5936 tor_snprintf(name
, len
, "%s:%d",
5937 conn
->base_
.address
, conn
->base_
.port
);
5941 /** Called when the status of an OR connection <b>conn</b> changes: tell any
5942 * interested control connections. <b>tp</b> is the new status for the
5943 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
5944 * may be the reason why.
5947 control_event_or_conn_status(or_connection_t
*conn
, or_conn_status_event_t tp
,
5953 char ncircs_buf
[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
5955 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS
))
5960 case OR_CONN_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
5961 case OR_CONN_EVENT_CONNECTED
: status
= "CONNECTED"; break;
5962 case OR_CONN_EVENT_FAILED
: status
= "FAILED"; break;
5963 case OR_CONN_EVENT_CLOSED
: status
= "CLOSED"; break;
5964 case OR_CONN_EVENT_NEW
: status
= "NEW"; break;
5966 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
5970 ncircs
= circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn
->chan
));
5974 ncircs
+= connection_or_get_num_circuits(conn
);
5975 if (ncircs
&& (tp
== OR_CONN_EVENT_FAILED
|| tp
== OR_CONN_EVENT_CLOSED
)) {
5976 tor_snprintf(ncircs_buf
, sizeof(ncircs_buf
), " NCIRCS=%d", ncircs
);
5979 orconn_target_get_name(name
, sizeof(name
), conn
);
5980 send_control_event(EVENT_OR_CONN_STATUS
,
5981 "650 ORCONN %s %s%s%s%s ID=%"PRIu64
"\r\n",
5983 reason
? " REASON=" : "",
5984 orconn_end_reason_to_control_string(reason
),
5986 (conn
->base_
.global_identifier
));
5992 * Print out STREAM_BW event for a single conn
5995 control_event_stream_bandwidth(edge_connection_t
*edge_conn
)
5998 char tbuf
[ISO_TIME_USEC_LEN
+1];
5999 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED
)) {
6000 if (!edge_conn
->n_read
&& !edge_conn
->n_written
)
6003 tor_gettimeofday(&now
);
6004 format_iso_time_nospace_usec(tbuf
, &now
);
6005 send_control_event(EVENT_STREAM_BANDWIDTH_USED
,
6006 "650 STREAM_BW %"PRIu64
" %lu %lu %s\r\n",
6007 (edge_conn
->base_
.global_identifier
),
6008 (unsigned long)edge_conn
->n_read
,
6009 (unsigned long)edge_conn
->n_written
,
6012 edge_conn
->n_written
= edge_conn
->n_read
= 0;
6018 /** A second or more has elapsed: tell any interested control
6019 * connections how much bandwidth streams have used. */
6021 control_event_stream_bandwidth_used(void)
6023 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED
)) {
6024 smartlist_t
*conns
= get_connection_array();
6025 edge_connection_t
*edge_conn
;
6027 char tbuf
[ISO_TIME_USEC_LEN
+1];
6029 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
)
6031 if (conn
->type
!= CONN_TYPE_AP
)
6033 edge_conn
= TO_EDGE_CONN(conn
);
6034 if (!edge_conn
->n_read
&& !edge_conn
->n_written
)
6037 tor_gettimeofday(&now
);
6038 format_iso_time_nospace_usec(tbuf
, &now
);
6039 send_control_event(EVENT_STREAM_BANDWIDTH_USED
,
6040 "650 STREAM_BW %"PRIu64
" %lu %lu %s\r\n",
6041 (edge_conn
->base_
.global_identifier
),
6042 (unsigned long)edge_conn
->n_read
,
6043 (unsigned long)edge_conn
->n_written
,
6046 edge_conn
->n_written
= edge_conn
->n_read
= 0;
6048 SMARTLIST_FOREACH_END(conn
);
6054 /** A second or more has elapsed: tell any interested control connections
6055 * how much bandwidth origin circuits have used. */
6057 control_event_circ_bandwidth_used(void)
6059 if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED
))
6062 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t
*, circ
) {
6063 if (!CIRCUIT_IS_ORIGIN(circ
))
6066 control_event_circ_bandwidth_used_for_circ(TO_ORIGIN_CIRCUIT(circ
));
6068 SMARTLIST_FOREACH_END(circ
);
6074 * Emit a CIRC_BW event line for a specific circuit.
6076 * This function sets the values it emits to 0, and does not emit
6077 * an event if there is no new data to report since the last call.
6079 * Therefore, it may be called at any frequency.
6082 control_event_circ_bandwidth_used_for_circ(origin_circuit_t
*ocirc
)
6085 char tbuf
[ISO_TIME_USEC_LEN
+1];
6089 if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED
))
6092 /* n_read_circ_bw and n_written_circ_bw are always updated
6093 * when there is any new cell on a circuit, and set to 0 after
6096 * Therefore, checking them is sufficient to determine if there
6097 * is new data to report. */
6098 if (!ocirc
->n_read_circ_bw
&& !ocirc
->n_written_circ_bw
)
6101 tor_gettimeofday(&now
);
6102 format_iso_time_nospace_usec(tbuf
, &now
);
6103 send_control_event(EVENT_CIRC_BANDWIDTH_USED
,
6104 "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu TIME=%s "
6105 "DELIVERED_READ=%lu OVERHEAD_READ=%lu "
6106 "DELIVERED_WRITTEN=%lu OVERHEAD_WRITTEN=%lu\r\n",
6107 ocirc
->global_identifier
,
6108 (unsigned long)ocirc
->n_read_circ_bw
,
6109 (unsigned long)ocirc
->n_written_circ_bw
,
6111 (unsigned long)ocirc
->n_delivered_read_circ_bw
,
6112 (unsigned long)ocirc
->n_overhead_read_circ_bw
,
6113 (unsigned long)ocirc
->n_delivered_written_circ_bw
,
6114 (unsigned long)ocirc
->n_overhead_written_circ_bw
);
6115 ocirc
->n_written_circ_bw
= ocirc
->n_read_circ_bw
= 0;
6116 ocirc
->n_overhead_written_circ_bw
= ocirc
->n_overhead_read_circ_bw
= 0;
6117 ocirc
->n_delivered_written_circ_bw
= ocirc
->n_delivered_read_circ_bw
= 0;
6122 /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
6123 * bandwidth counters. */
6125 control_event_conn_bandwidth(connection_t
*conn
)
6127 const char *conn_type_str
;
6128 if (!get_options()->TestingEnableConnBwEvent
||
6129 !EVENT_IS_INTERESTING(EVENT_CONN_BW
))
6131 if (!conn
->n_read_conn_bw
&& !conn
->n_written_conn_bw
)
6133 switch (conn
->type
) {
6135 conn_type_str
= "OR";
6138 conn_type_str
= "DIR";
6140 case CONN_TYPE_EXIT
:
6141 conn_type_str
= "EXIT";
6146 send_control_event(EVENT_CONN_BW
,
6147 "650 CONN_BW ID=%"PRIu64
" TYPE=%s "
6148 "READ=%lu WRITTEN=%lu\r\n",
6149 (conn
->global_identifier
),
6151 (unsigned long)conn
->n_read_conn_bw
,
6152 (unsigned long)conn
->n_written_conn_bw
);
6153 conn
->n_written_conn_bw
= conn
->n_read_conn_bw
= 0;
6157 /** A second or more has elapsed: tell any interested control
6158 * connections how much bandwidth connections have used. */
6160 control_event_conn_bandwidth_used(void)
6162 if (get_options()->TestingEnableConnBwEvent
&&
6163 EVENT_IS_INTERESTING(EVENT_CONN_BW
)) {
6164 SMARTLIST_FOREACH(get_connection_array(), connection_t
*, conn
,
6165 control_event_conn_bandwidth(conn
));
6170 /** Helper: iterate over cell statistics of <b>circ</b> and sum up added
6171 * cells, removed cells, and waiting times by cell command and direction.
6172 * Store results in <b>cell_stats</b>. Free cell statistics of the
6173 * circuit afterwards. */
6175 sum_up_cell_stats_by_command(circuit_t
*circ
, cell_stats_t
*cell_stats
)
6177 memset(cell_stats
, 0, sizeof(cell_stats_t
));
6178 SMARTLIST_FOREACH_BEGIN(circ
->testing_cell_stats
,
6179 const testing_cell_stats_entry_t
*, ent
) {
6180 tor_assert(ent
->command
<= CELL_COMMAND_MAX_
);
6181 if (!ent
->removed
&& !ent
->exitward
) {
6182 cell_stats
->added_cells_appward
[ent
->command
] += 1;
6183 } else if (!ent
->removed
&& ent
->exitward
) {
6184 cell_stats
->added_cells_exitward
[ent
->command
] += 1;
6185 } else if (!ent
->exitward
) {
6186 cell_stats
->removed_cells_appward
[ent
->command
] += 1;
6187 cell_stats
->total_time_appward
[ent
->command
] += ent
->waiting_time
* 10;
6189 cell_stats
->removed_cells_exitward
[ent
->command
] += 1;
6190 cell_stats
->total_time_exitward
[ent
->command
] += ent
->waiting_time
* 10;
6192 } SMARTLIST_FOREACH_END(ent
);
6193 circuit_clear_testing_cell_stats(circ
);
6196 /** Helper: append a cell statistics string to <code>event_parts</code>,
6197 * prefixed with <code>key</code>=. Statistics consist of comma-separated
6198 * key:value pairs with lower-case command strings as keys and cell
6199 * numbers or total waiting times as values. A key:value pair is included
6200 * if the entry in <code>include_if_non_zero</code> is not zero, but with
6201 * the (possibly zero) entry from <code>number_to_include</code>. Both
6202 * arrays are expected to have a length of CELL_COMMAND_MAX_ + 1. If no
6203 * entry in <code>include_if_non_zero</code> is positive, no string will
6204 * be added to <code>event_parts</code>. */
6206 append_cell_stats_by_command(smartlist_t
*event_parts
, const char *key
,
6207 const uint64_t *include_if_non_zero
,
6208 const uint64_t *number_to_include
)
6210 smartlist_t
*key_value_strings
= smartlist_new();
6212 for (i
= 0; i
<= CELL_COMMAND_MAX_
; i
++) {
6213 if (include_if_non_zero
[i
] > 0) {
6214 smartlist_add_asprintf(key_value_strings
, "%s:%"PRIu64
,
6215 cell_command_to_string(i
),
6216 (number_to_include
[i
]));
6219 if (smartlist_len(key_value_strings
) > 0) {
6220 char *joined
= smartlist_join_strings(key_value_strings
, ",", 0, NULL
);
6221 smartlist_add_asprintf(event_parts
, "%s=%s", key
, joined
);
6222 SMARTLIST_FOREACH(key_value_strings
, char *, cp
, tor_free(cp
));
6225 smartlist_free(key_value_strings
);
6228 /** Helper: format <b>cell_stats</b> for <b>circ</b> for inclusion in a
6229 * CELL_STATS event and write result string to <b>event_string</b>. */
6231 format_cell_stats(char **event_string
, circuit_t
*circ
,
6232 cell_stats_t
*cell_stats
)
6234 smartlist_t
*event_parts
= smartlist_new();
6235 if (CIRCUIT_IS_ORIGIN(circ
)) {
6236 origin_circuit_t
*ocirc
= TO_ORIGIN_CIRCUIT(circ
);
6237 smartlist_add_asprintf(event_parts
, "ID=%lu",
6238 (unsigned long)ocirc
->global_identifier
);
6239 } else if (TO_OR_CIRCUIT(circ
)->p_chan
) {
6240 or_circuit_t
*or_circ
= TO_OR_CIRCUIT(circ
);
6241 smartlist_add_asprintf(event_parts
, "InboundQueue=%lu",
6242 (unsigned long)or_circ
->p_circ_id
);
6243 smartlist_add_asprintf(event_parts
, "InboundConn=%"PRIu64
,
6244 (or_circ
->p_chan
->global_identifier
));
6245 append_cell_stats_by_command(event_parts
, "InboundAdded",
6246 cell_stats
->added_cells_appward
,
6247 cell_stats
->added_cells_appward
);
6248 append_cell_stats_by_command(event_parts
, "InboundRemoved",
6249 cell_stats
->removed_cells_appward
,
6250 cell_stats
->removed_cells_appward
);
6251 append_cell_stats_by_command(event_parts
, "InboundTime",
6252 cell_stats
->removed_cells_appward
,
6253 cell_stats
->total_time_appward
);
6256 smartlist_add_asprintf(event_parts
, "OutboundQueue=%lu",
6257 (unsigned long)circ
->n_circ_id
);
6258 smartlist_add_asprintf(event_parts
, "OutboundConn=%"PRIu64
,
6259 (circ
->n_chan
->global_identifier
));
6260 append_cell_stats_by_command(event_parts
, "OutboundAdded",
6261 cell_stats
->added_cells_exitward
,
6262 cell_stats
->added_cells_exitward
);
6263 append_cell_stats_by_command(event_parts
, "OutboundRemoved",
6264 cell_stats
->removed_cells_exitward
,
6265 cell_stats
->removed_cells_exitward
);
6266 append_cell_stats_by_command(event_parts
, "OutboundTime",
6267 cell_stats
->removed_cells_exitward
,
6268 cell_stats
->total_time_exitward
);
6270 *event_string
= smartlist_join_strings(event_parts
, " ", 0, NULL
);
6271 SMARTLIST_FOREACH(event_parts
, char *, cp
, tor_free(cp
));
6272 smartlist_free(event_parts
);
6275 /** A second or more has elapsed: tell any interested control connection
6276 * how many cells have been processed for a given circuit. */
6278 control_event_circuit_cell_stats(void)
6280 cell_stats_t
*cell_stats
;
6282 if (!get_options()->TestingEnableCellStatsEvent
||
6283 !EVENT_IS_INTERESTING(EVENT_CELL_STATS
))
6285 cell_stats
= tor_malloc(sizeof(cell_stats_t
));
6286 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t
*, circ
) {
6287 if (!circ
->testing_cell_stats
)
6289 sum_up_cell_stats_by_command(circ
, cell_stats
);
6290 format_cell_stats(&event_string
, circ
, cell_stats
);
6291 send_control_event(EVENT_CELL_STATS
,
6292 "650 CELL_STATS %s\r\n", event_string
);
6293 tor_free(event_string
);
6295 SMARTLIST_FOREACH_END(circ
);
6296 tor_free(cell_stats
);
6300 /* about 5 minutes worth. */
6301 #define N_BW_EVENTS_TO_CACHE 300
6302 /* Index into cached_bw_events to next write. */
6303 static int next_measurement_idx
= 0;
6304 /* number of entries set in n_measurements */
6305 static int n_measurements
= 0;
6306 static struct cached_bw_event_s
{
6309 } cached_bw_events
[N_BW_EVENTS_TO_CACHE
];
6311 /** A second or more has elapsed: tell any interested control
6312 * connections how much bandwidth we used. */
6314 control_event_bandwidth_used(uint32_t n_read
, uint32_t n_written
)
6316 cached_bw_events
[next_measurement_idx
].n_read
= n_read
;
6317 cached_bw_events
[next_measurement_idx
].n_written
= n_written
;
6318 if (++next_measurement_idx
== N_BW_EVENTS_TO_CACHE
)
6319 next_measurement_idx
= 0;
6320 if (n_measurements
< N_BW_EVENTS_TO_CACHE
)
6323 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED
)) {
6324 send_control_event(EVENT_BANDWIDTH_USED
,
6325 "650 BW %lu %lu\r\n",
6326 (unsigned long)n_read
,
6327 (unsigned long)n_written
);
6334 get_bw_samples(void)
6337 int idx
= (next_measurement_idx
+ N_BW_EVENTS_TO_CACHE
- n_measurements
)
6338 % N_BW_EVENTS_TO_CACHE
;
6339 tor_assert(0 <= idx
&& idx
< N_BW_EVENTS_TO_CACHE
);
6341 smartlist_t
*elements
= smartlist_new();
6343 for (i
= 0; i
< n_measurements
; ++i
) {
6344 tor_assert(0 <= idx
&& idx
< N_BW_EVENTS_TO_CACHE
);
6345 const struct cached_bw_event_s
*bwe
= &cached_bw_events
[idx
];
6347 smartlist_add_asprintf(elements
, "%u,%u",
6348 (unsigned)bwe
->n_read
,
6349 (unsigned)bwe
->n_written
);
6351 idx
= (idx
+ 1) % N_BW_EVENTS_TO_CACHE
;
6354 char *result
= smartlist_join_strings(elements
, " ", 0, NULL
);
6356 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
6357 smartlist_free(elements
);
6362 /** Called when we are sending a log message to the controllers: suspend
6363 * sending further log messages to the controllers until we're done. Used by
6364 * CONN_LOG_PROTECT. */
6366 disable_control_logging(void)
6368 ++disable_log_messages
;
6371 /** We're done sending a log message to the controllers: re-enable controller
6372 * logging. Used by CONN_LOG_PROTECT. */
6374 enable_control_logging(void)
6376 if (--disable_log_messages
< 0)
6380 /** We got a log message: tell any interested control connections. */
6382 control_event_logmsg(int severity
, uint32_t domain
, const char *msg
)
6386 /* Don't even think of trying to add stuff to a buffer from a cpuworker
6387 * thread. (See #25987 for plan to fix.) */
6388 if (! in_main_thread())
6391 if (disable_log_messages
)
6394 if (domain
== LD_BUG
&& EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
) &&
6395 severity
<= LOG_NOTICE
) {
6396 char *esc
= esc_for_log(msg
);
6397 ++disable_log_messages
;
6398 control_event_general_status(severity
, "BUG REASON=%s", esc
);
6399 --disable_log_messages
;
6403 event
= log_severity_to_event(severity
);
6404 if (event
>= 0 && EVENT_IS_INTERESTING(event
)) {
6407 if (strchr(msg
, '\n')) {
6409 b
= tor_strdup(msg
);
6410 for (cp
= b
; *cp
; ++cp
)
6411 if (*cp
== '\r' || *cp
== '\n')
6415 case LOG_DEBUG
: s
= "DEBUG"; break;
6416 case LOG_INFO
: s
= "INFO"; break;
6417 case LOG_NOTICE
: s
= "NOTICE"; break;
6418 case LOG_WARN
: s
= "WARN"; break;
6419 case LOG_ERR
: s
= "ERR"; break;
6420 default: s
= "UnknownLogSeverity"; break;
6422 ++disable_log_messages
;
6423 send_control_event(event
, "650 %s %s\r\n", s
, b
?b
:msg
);
6424 if (severity
== LOG_ERR
) {
6425 /* Force a flush, since we may be about to die horribly */
6426 queued_events_flush_all(1);
6428 --disable_log_messages
;
6434 * Logging callback: called when there is a queued pending log callback.
6437 control_event_logmsg_pending(void)
6439 if (! in_main_thread()) {
6440 /* We can't handle this case yet, since we're using a
6441 * mainloop_event_t to invoke queued_events_flush_all. We ought to
6442 * use a different mechanism instead: see #25987.
6446 tor_assert(flush_queued_events_event
);
6447 mainloop_event_activate(flush_queued_events_event
);
6450 /** Called whenever we receive new router descriptors: tell any
6451 * interested control connections. <b>routers</b> is a list of
6455 control_event_descriptors_changed(smartlist_t
*routers
)
6459 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC
))
6463 smartlist_t
*names
= smartlist_new();
6465 SMARTLIST_FOREACH(routers
, routerinfo_t
*, ri
, {
6466 char *b
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
6467 router_get_verbose_nickname(b
, ri
);
6468 smartlist_add(names
, b
);
6470 ids
= smartlist_join_strings(names
, " ", 0, NULL
);
6471 tor_asprintf(&msg
, "650 NEWDESC %s\r\n", ids
);
6472 send_control_event_string(EVENT_NEW_DESC
, msg
);
6475 SMARTLIST_FOREACH(names
, char *, cp
, tor_free(cp
));
6476 smartlist_free(names
);
6481 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
6482 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
6483 * <b>error</b> is non-NULL, it is an error code describing the failure
6484 * mode of the mapping.
6487 control_event_address_mapped(const char *from
, const char *to
, time_t expires
,
6488 const char *error
, const int cached
)
6490 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP
))
6493 if (expires
< 3 || expires
== TIME_MAX
)
6494 send_control_event(EVENT_ADDRMAP
,
6495 "650 ADDRMAP %s %s NEVER %s%s"
6496 "CACHED=\"%s\"\r\n",
6497 from
, to
, error
?error
:"", error
?" ":"",
6500 char buf
[ISO_TIME_LEN
+1];
6501 char buf2
[ISO_TIME_LEN
+1];
6502 format_local_iso_time(buf
,expires
);
6503 format_iso_time(buf2
,expires
);
6504 send_control_event(EVENT_ADDRMAP
,
6505 "650 ADDRMAP %s %s \"%s\""
6506 " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
6508 error
?error
:"", error
?" ":"",
6509 buf2
, cached
?"YES":"NO");
6515 /** Cached liveness for network liveness events and GETINFO
6518 static int network_is_live
= 0;
6521 get_cached_network_liveness(void)
6523 return network_is_live
;
6527 set_cached_network_liveness(int liveness
)
6529 network_is_live
= liveness
;
6532 /** The network liveness has changed; this is called from circuitstats.c
6533 * whenever we receive a cell, or when timeout expires and we assume the
6534 * network is down. */
6536 control_event_network_liveness_update(int liveness
)
6539 if (get_cached_network_liveness() <= 0) {
6540 /* Update cached liveness */
6541 set_cached_network_liveness(1);
6542 log_debug(LD_CONTROL
, "Sending NETWORK_LIVENESS UP");
6543 send_control_event_string(EVENT_NETWORK_LIVENESS
,
6544 "650 NETWORK_LIVENESS UP\r\n");
6546 /* else was already live, no-op */
6548 if (get_cached_network_liveness() > 0) {
6549 /* Update cached liveness */
6550 set_cached_network_liveness(0);
6551 log_debug(LD_CONTROL
, "Sending NETWORK_LIVENESS DOWN");
6552 send_control_event_string(EVENT_NETWORK_LIVENESS
,
6553 "650 NETWORK_LIVENESS DOWN\r\n");
6555 /* else was already dead, no-op */
6561 /** Helper function for NS-style events. Constructs and sends an event
6562 * of type <b>event</b> with string <b>event_string</b> out of the set of
6563 * networkstatuses <b>statuses</b>. Currently it is used for NS events
6564 * and NEWCONSENSUS events. */
6566 control_event_networkstatus_changed_helper(smartlist_t
*statuses
,
6568 const char *event_string
)
6571 char *s
, *esc
= NULL
;
6572 if (!EVENT_IS_INTERESTING(event
) || !smartlist_len(statuses
))
6575 strs
= smartlist_new();
6576 smartlist_add_strdup(strs
, "650+");
6577 smartlist_add_strdup(strs
, event_string
);
6578 smartlist_add_strdup(strs
, "\r\n");
6579 SMARTLIST_FOREACH(statuses
, const routerstatus_t
*, rs
,
6581 s
= networkstatus_getinfo_helper_single(rs
);
6583 smartlist_add(strs
, s
);
6586 s
= smartlist_join_strings(strs
, "", 0, NULL
);
6587 write_escaped_data(s
, strlen(s
), &esc
);
6588 SMARTLIST_FOREACH(strs
, char *, cp
, tor_free(cp
));
6589 smartlist_free(strs
);
6591 send_control_event_string(event
, esc
);
6592 send_control_event_string(event
,
6599 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
6600 * an NS event to any controller that cares. */
6602 control_event_networkstatus_changed(smartlist_t
*statuses
)
6604 return control_event_networkstatus_changed_helper(statuses
, EVENT_NS
, "NS");
6607 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
6608 * event consisting of an NS-style line for each relay in the consensus. */
6610 control_event_newconsensus(const networkstatus_t
*consensus
)
6612 if (!control_event_is_interesting(EVENT_NEWCONSENSUS
))
6614 return control_event_networkstatus_changed_helper(
6615 consensus
->routerstatus_list
, EVENT_NEWCONSENSUS
, "NEWCONSENSUS");
6618 /** Called when we compute a new circuitbuildtimeout */
6620 control_event_buildtimeout_set(buildtimeout_set_event_t type
,
6623 const char *type_string
= NULL
;
6625 if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET
))
6629 case BUILDTIMEOUT_SET_EVENT_COMPUTED
:
6630 type_string
= "COMPUTED";
6632 case BUILDTIMEOUT_SET_EVENT_RESET
:
6633 type_string
= "RESET";
6635 case BUILDTIMEOUT_SET_EVENT_SUSPENDED
:
6636 type_string
= "SUSPENDED";
6638 case BUILDTIMEOUT_SET_EVENT_DISCARD
:
6639 type_string
= "DISCARD";
6641 case BUILDTIMEOUT_SET_EVENT_RESUME
:
6642 type_string
= "RESUME";
6645 type_string
= "UNKNOWN";
6649 send_control_event(EVENT_BUILDTIMEOUT_SET
,
6650 "650 BUILDTIMEOUT_SET %s %s\r\n",
6656 /** Called when a signal has been processed from signal_callback */
6658 control_event_signal(uintptr_t signal_num
)
6660 const char *signal_string
= NULL
;
6662 if (!control_event_is_interesting(EVENT_GOT_SIGNAL
))
6665 switch (signal_num
) {
6667 signal_string
= "RELOAD";
6670 signal_string
= "DUMP";
6673 signal_string
= "DEBUG";
6676 signal_string
= "NEWNYM";
6678 case SIGCLEARDNSCACHE
:
6679 signal_string
= "CLEARDNSCACHE";
6682 signal_string
= "HEARTBEAT";
6685 log_warn(LD_BUG
, "Unrecognized signal %lu in control_event_signal",
6686 (unsigned long)signal_num
);
6690 send_control_event(EVENT_GOT_SIGNAL
, "650 SIGNAL %s\r\n",
6695 /** Called when a single local_routerstatus_t has changed: Sends an NS event
6696 * to any controller that cares. */
6698 control_event_networkstatus_changed_single(const routerstatus_t
*rs
)
6700 smartlist_t
*statuses
;
6703 if (!EVENT_IS_INTERESTING(EVENT_NS
))
6706 statuses
= smartlist_new();
6707 smartlist_add(statuses
, (void*)rs
);
6708 r
= control_event_networkstatus_changed(statuses
);
6709 smartlist_free(statuses
);
6713 /** Our own router descriptor has changed; tell any controllers that care.
6716 control_event_my_descriptor_changed(void)
6718 send_control_event(EVENT_DESCCHANGED
, "650 DESCCHANGED\r\n");
6722 /** Helper: sends a status event where <b>type</b> is one of
6723 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
6724 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
6725 * string corresponding to <b>args</b>. */
6727 control_event_status(int type
, int severity
, const char *format
, va_list args
)
6729 char *user_buf
= NULL
;
6730 char format_buf
[160];
6731 const char *status
, *sev
;
6734 case EVENT_STATUS_GENERAL
:
6735 status
= "STATUS_GENERAL";
6737 case EVENT_STATUS_CLIENT
:
6738 status
= "STATUS_CLIENT";
6740 case EVENT_STATUS_SERVER
:
6741 status
= "STATUS_SERVER";
6744 log_warn(LD_BUG
, "Unrecognized status type %d", type
);
6758 log_warn(LD_BUG
, "Unrecognized status severity %d", severity
);
6761 if (tor_snprintf(format_buf
, sizeof(format_buf
), "650 %s %s",
6763 log_warn(LD_BUG
, "Format string too long.");
6766 tor_vasprintf(&user_buf
, format
, args
);
6768 send_control_event(type
, "%s %s\r\n", format_buf
, user_buf
);
6773 #define CONTROL_EVENT_STATUS_BODY(event, sev) \
6777 if (!EVENT_IS_INTERESTING(event)) \
6780 va_start(ap, format); \
6781 r = control_event_status((event), (sev), format, ap); \
6785 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
6786 * by formatting the arguments using the printf-style <b>format</b>. */
6788 control_event_general_status(int severity
, const char *format
, ...)
6790 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL
, severity
);
6794 /** Format and send an EVENT_STATUS_GENERAL LOG_ERR event, and flush it to the
6795 * controller(s) immediately. */
6797 control_event_general_error(const char *format
, ...)
6799 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL
, LOG_ERR
);
6800 /* Force a flush, since we may be about to die horribly */
6801 queued_events_flush_all(1);
6805 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
6806 * by formatting the arguments using the printf-style <b>format</b>. */
6808 control_event_client_status(int severity
, const char *format
, ...)
6810 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT
, severity
);
6814 /** Format and send an EVENT_STATUS_CLIENT LOG_ERR event, and flush it to the
6815 * controller(s) immediately. */
6817 control_event_client_error(const char *format
, ...)
6819 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT
, LOG_ERR
);
6820 /* Force a flush, since we may be about to die horribly */
6821 queued_events_flush_all(1);
6825 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
6826 * by formatting the arguments using the printf-style <b>format</b>. */
6828 control_event_server_status(int severity
, const char *format
, ...)
6830 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER
, severity
);
6834 /** Format and send an EVENT_STATUS_SERVER LOG_ERR event, and flush it to the
6835 * controller(s) immediately. */
6837 control_event_server_error(const char *format
, ...)
6839 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER
, LOG_ERR
);
6840 /* Force a flush, since we may be about to die horribly */
6841 queued_events_flush_all(1);
6845 /** Called when the status of an entry guard with the given <b>nickname</b>
6846 * and identity <b>digest</b> has changed to <b>status</b>: tells any
6847 * controllers that care. */
6849 control_event_guard(const char *nickname
, const char *digest
,
6852 char hbuf
[HEX_DIGEST_LEN
+1];
6853 base16_encode(hbuf
, sizeof(hbuf
), digest
, DIGEST_LEN
);
6854 if (!EVENT_IS_INTERESTING(EVENT_GUARD
))
6858 char buf
[MAX_VERBOSE_NICKNAME_LEN
+1];
6859 const node_t
*node
= node_get_by_id(digest
);
6861 node_get_verbose_nickname(node
, buf
);
6863 tor_snprintf(buf
, sizeof(buf
), "$%s~%s", hbuf
, nickname
);
6865 send_control_event(EVENT_GUARD
,
6866 "650 GUARD ENTRY %s %s\r\n", buf
, status
);
6871 /** Called when a configuration option changes. This is generally triggered
6872 * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
6873 * a smartlist_t containing (key, value, ...) pairs in sequence.
6874 * <b>value</b> can be NULL. */
6876 control_event_conf_changed(const smartlist_t
*elements
)
6881 if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED
) ||
6882 smartlist_len(elements
) == 0) {
6885 lines
= smartlist_new();
6886 for (i
= 0; i
< smartlist_len(elements
); i
+= 2) {
6887 char *k
= smartlist_get(elements
, i
);
6888 char *v
= smartlist_get(elements
, i
+1);
6890 smartlist_add_asprintf(lines
, "650-%s", k
);
6892 smartlist_add_asprintf(lines
, "650-%s=%s", k
, v
);
6895 result
= smartlist_join_strings(lines
, "\r\n", 0, NULL
);
6896 send_control_event(EVENT_CONF_CHANGED
,
6897 "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result
);
6899 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
6900 smartlist_free(lines
);
6904 /** Helper: Return a newly allocated string containing a path to the
6905 * file where we store our authentication cookie. */
6907 get_controller_cookie_file_name(void)
6909 const or_options_t
*options
= get_options();
6910 if (options
->CookieAuthFile
&& strlen(options
->CookieAuthFile
)) {
6911 return tor_strdup(options
->CookieAuthFile
);
6913 return get_datadir_fname("control_auth_cookie");
6917 /* Initialize the cookie-based authentication system of the
6918 * ControlPort. If <b>enabled</b> is 0, then disable the cookie
6919 * authentication system. */
6921 init_control_cookie_authentication(int enabled
)
6927 authentication_cookie_is_set
= 0;
6931 fname
= get_controller_cookie_file_name();
6932 retval
= init_cookie_authentication(fname
, "", /* no header */
6933 AUTHENTICATION_COOKIE_LEN
,
6934 get_options()->CookieAuthFileGroupReadable
,
6935 &authentication_cookie
,
6936 &authentication_cookie_is_set
);
6941 /** A copy of the process specifier of Tor's owning controller, or
6942 * NULL if this Tor instance is not currently owned by a process. */
6943 static char *owning_controller_process_spec
= NULL
;
6945 /** A process-termination monitor for Tor's owning controller, or NULL
6946 * if this Tor instance is not currently owned by a process. */
6947 static tor_process_monitor_t
*owning_controller_process_monitor
= NULL
;
6949 /** Process-termination monitor callback for Tor's owning controller
6952 owning_controller_procmon_cb(void *unused
)
6956 lost_owning_controller("process", "vanished");
6959 /** Set <b>process_spec</b> as Tor's owning controller process.
6960 * Exit on failure. */
6962 monitor_owning_controller_process(const char *process_spec
)
6966 tor_assert((owning_controller_process_spec
== NULL
) ==
6967 (owning_controller_process_monitor
== NULL
));
6969 if (owning_controller_process_spec
!= NULL
) {
6970 if ((process_spec
!= NULL
) && !strcmp(process_spec
,
6971 owning_controller_process_spec
)) {
6972 /* Same process -- return now, instead of disposing of and
6973 * recreating the process-termination monitor. */
6977 /* We are currently owned by a process, and we should no longer be
6978 * owned by it. Free the process-termination monitor. */
6979 tor_process_monitor_free(owning_controller_process_monitor
);
6980 owning_controller_process_monitor
= NULL
;
6982 tor_free(owning_controller_process_spec
);
6983 owning_controller_process_spec
= NULL
;
6986 tor_assert((owning_controller_process_spec
== NULL
) &&
6987 (owning_controller_process_monitor
== NULL
));
6989 if (process_spec
== NULL
)
6992 owning_controller_process_spec
= tor_strdup(process_spec
);
6993 owning_controller_process_monitor
=
6994 tor_process_monitor_new(tor_libevent_get_base(),
6995 owning_controller_process_spec
,
6997 owning_controller_procmon_cb
, NULL
,
7000 if (owning_controller_process_monitor
== NULL
) {
7001 log_err(LD_BUG
, "Couldn't create process-termination monitor for "
7002 "owning controller: %s. Exiting.",
7004 owning_controller_process_spec
= NULL
;
7005 tor_shutdown_event_loop_and_exit(1);
7009 /** Convert the name of a bootstrapping phase <b>s</b> into strings
7010 * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
7012 bootstrap_status_to_string(bootstrap_status_t s
, const char **tag
,
7013 const char **summary
)
7016 case BOOTSTRAP_STATUS_UNDEF
:
7018 *summary
= "Undefined";
7020 case BOOTSTRAP_STATUS_STARTING
:
7022 *summary
= "Starting";
7024 case BOOTSTRAP_STATUS_CONN_DIR
:
7026 *summary
= "Connecting to directory server";
7028 case BOOTSTRAP_STATUS_HANDSHAKE
:
7029 *tag
= "status_handshake";
7030 *summary
= "Finishing handshake";
7032 case BOOTSTRAP_STATUS_HANDSHAKE_DIR
:
7033 *tag
= "handshake_dir";
7034 *summary
= "Finishing handshake with directory server";
7036 case BOOTSTRAP_STATUS_ONEHOP_CREATE
:
7037 *tag
= "onehop_create";
7038 *summary
= "Establishing an encrypted directory connection";
7040 case BOOTSTRAP_STATUS_REQUESTING_STATUS
:
7041 *tag
= "requesting_status";
7042 *summary
= "Asking for networkstatus consensus";
7044 case BOOTSTRAP_STATUS_LOADING_STATUS
:
7045 *tag
= "loading_status";
7046 *summary
= "Loading networkstatus consensus";
7048 case BOOTSTRAP_STATUS_LOADING_KEYS
:
7049 *tag
= "loading_keys";
7050 *summary
= "Loading authority key certs";
7052 case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS
:
7053 *tag
= "requesting_descriptors";
7054 /* XXXX this appears to incorrectly report internal on most loads */
7055 *summary
= router_have_consensus_path() == CONSENSUS_PATH_INTERNAL
?
7056 "Asking for relay descriptors for internal paths" :
7057 "Asking for relay descriptors";
7059 /* If we're sure there are no exits in the consensus,
7060 * inform the controller by adding "internal"
7061 * to the status summaries.
7062 * (We only check this while loading descriptors,
7063 * so we may not know in the earlier stages.)
7064 * But if there are exits, we can't be sure whether
7065 * we're creating internal or exit paths/circuits.
7066 * XXXX Or should be use different tags or statuses
7067 * for internal and exit/all? */
7068 case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS
:
7069 *tag
= "loading_descriptors";
7070 *summary
= router_have_consensus_path() == CONSENSUS_PATH_INTERNAL
?
7071 "Loading relay descriptors for internal paths" :
7072 "Loading relay descriptors";
7074 case BOOTSTRAP_STATUS_CONN_OR
:
7076 *summary
= router_have_consensus_path() == CONSENSUS_PATH_INTERNAL
?
7077 "Connecting to the Tor network internally" :
7078 "Connecting to the Tor network";
7080 case BOOTSTRAP_STATUS_HANDSHAKE_OR
:
7081 *tag
= "handshake_or";
7082 *summary
= router_have_consensus_path() == CONSENSUS_PATH_INTERNAL
?
7083 "Finishing handshake with first hop of internal circuit" :
7084 "Finishing handshake with first hop";
7086 case BOOTSTRAP_STATUS_CIRCUIT_CREATE
:
7087 *tag
= "circuit_create";
7088 *summary
= router_have_consensus_path() == CONSENSUS_PATH_INTERNAL
?
7089 "Establishing an internal Tor circuit" :
7090 "Establishing a Tor circuit";
7092 case BOOTSTRAP_STATUS_DONE
:
7097 // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
7098 *tag
= *summary
= "unknown";
7104 /** What percentage through the bootstrap process are we? We remember
7105 * this so we can avoid sending redundant bootstrap status events, and
7106 * so we can guess context for the bootstrap messages which are
7107 * ambiguous. It starts at 'undef', but gets set to 'starting' while
7108 * Tor initializes. */
7109 static int bootstrap_percent
= BOOTSTRAP_STATUS_UNDEF
;
7111 /** Like bootstrap_percent, but only takes on the enumerated values in
7112 * bootstrap_status_t.
7114 static int bootstrap_phase
= BOOTSTRAP_STATUS_UNDEF
;
7116 /** As bootstrap_percent, but holds the bootstrapping level at which we last
7117 * logged a NOTICE-level message. We use this, plus BOOTSTRAP_PCT_INCREMENT,
7118 * to avoid flooding the log with a new message every time we get a few more
7119 * microdescriptors */
7120 static int notice_bootstrap_percent
= 0;
7122 /** How many problems have we had getting to the next bootstrapping phase?
7123 * These include failure to establish a connection to a Tor relay,
7124 * failures to finish the TLS handshake, failures to validate the
7125 * consensus document, etc. */
7126 static int bootstrap_problems
= 0;
7128 /** We only tell the controller once we've hit a threshold of problems
7129 * for the current phase. */
7130 #define BOOTSTRAP_PROBLEM_THRESHOLD 10
7132 /** When our bootstrapping progress level changes, but our bootstrapping
7133 * status has not advanced, we only log at NOTICE when we have made at least
7134 * this much progress.
7136 #define BOOTSTRAP_PCT_INCREMENT 5
7138 /** Do the actual logging and notifications for
7139 * control_event_bootstrap(). Doesn't change any state beyond that.
7142 control_event_bootstrap_core(int loglevel
, bootstrap_status_t status
,
7145 char buf
[BOOTSTRAP_MSG_LEN
];
7146 const char *tag
, *summary
;
7148 bootstrap_status_to_string(status
, &tag
, &summary
);
7149 /* Locally reset status if there's incremental progress */
7153 tor_log(loglevel
, LD_CONTROL
,
7154 "Bootstrapped %d%%: %s", status
, summary
);
7155 tor_snprintf(buf
, sizeof(buf
),
7156 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
7157 status
, tag
, summary
);
7158 tor_snprintf(last_sent_bootstrap_message
,
7159 sizeof(last_sent_bootstrap_message
),
7161 control_event_client_status(LOG_NOTICE
, "%s", buf
);
7164 /** Called when Tor has made progress at bootstrapping its directory
7165 * information and initial circuits.
7167 * <b>status</b> is the new status, that is, what task we will be doing
7168 * next. <b>progress</b> is zero if we just started this task, else it
7169 * represents progress on the task.
7172 control_event_bootstrap(bootstrap_status_t status
, int progress
)
7174 int loglevel
= LOG_NOTICE
;
7176 if (bootstrap_percent
== BOOTSTRAP_STATUS_DONE
)
7177 return; /* already bootstrapped; nothing to be done here. */
7179 /* special case for handshaking status, since our TLS handshaking code
7180 * can't distinguish what the connection is going to be for. */
7181 if (status
== BOOTSTRAP_STATUS_HANDSHAKE
) {
7182 if (bootstrap_percent
< BOOTSTRAP_STATUS_CONN_OR
) {
7183 status
= BOOTSTRAP_STATUS_HANDSHAKE_DIR
;
7185 status
= BOOTSTRAP_STATUS_HANDSHAKE_OR
;
7189 if (status
<= bootstrap_percent
) {
7190 /* If there's no new progress, return early. */
7191 if (!progress
|| progress
<= bootstrap_percent
)
7193 /* Log at INFO if not enough progress happened. */
7194 if (progress
< notice_bootstrap_percent
+ BOOTSTRAP_PCT_INCREMENT
)
7195 loglevel
= LOG_INFO
;
7198 control_event_bootstrap_core(loglevel
, status
, progress
);
7200 if (status
> bootstrap_percent
) {
7201 bootstrap_phase
= status
; /* new milestone reached */
7202 bootstrap_percent
= status
;
7204 if (progress
> bootstrap_percent
) {
7205 /* incremental progress within a milestone */
7206 bootstrap_percent
= progress
;
7207 bootstrap_problems
= 0; /* Progress! Reset our problem counter. */
7209 if (loglevel
== LOG_NOTICE
&&
7210 bootstrap_percent
> notice_bootstrap_percent
) {
7211 /* Remember that we gave a notice at this level. */
7212 notice_bootstrap_percent
= bootstrap_percent
;
7216 /** Flag whether we've opened an OR_CONN yet */
7217 static int bootstrap_first_orconn
= 0;
7219 /** Like bootstrap_phase, but for (possibly deferred) directory progress */
7220 static int bootstrap_dir_phase
= BOOTSTRAP_STATUS_UNDEF
;
7222 /** Like bootstrap_problems, but for (possibly deferred) directory progress */
7223 static int bootstrap_dir_progress
= BOOTSTRAP_STATUS_UNDEF
;
7225 /** Defer directory info bootstrap events until we have successfully
7226 * completed our first connection to a router. */
7228 control_event_boot_dir(bootstrap_status_t status
, int progress
)
7230 if (status
> bootstrap_dir_progress
) {
7231 bootstrap_dir_progress
= status
;
7232 bootstrap_dir_phase
= status
;
7234 if (progress
&& progress
>= bootstrap_dir_progress
) {
7235 bootstrap_dir_progress
= progress
;
7238 /* Don't report unless we have successfully opened at least one OR_CONN */
7239 if (!bootstrap_first_orconn
)
7242 control_event_bootstrap(status
, progress
);
7245 /** Set a flag to allow reporting of directory bootstrap progress.
7246 * (Code that reports completion of an OR_CONN calls this.) Also,
7247 * report directory progress so far. */
7249 control_event_boot_first_orconn(void)
7251 bootstrap_first_orconn
= 1;
7252 control_event_bootstrap(bootstrap_dir_phase
, bootstrap_dir_progress
);
7255 /** Called when Tor has failed to make bootstrapping progress in a way
7256 * that indicates a problem. <b>warn</b> gives a human-readable hint
7257 * as to why, and <b>reason</b> provides a controller-facing short
7258 * tag. <b>conn</b> is the connection that caused this problem and
7259 * can be NULL if a connection cannot be easily identified.
7262 control_event_bootstrap_problem(const char *warn
, const char *reason
,
7263 const connection_t
*conn
, int dowarn
)
7265 int status
= bootstrap_percent
;
7266 const char *tag
= "", *summary
= "";
7267 char buf
[BOOTSTRAP_MSG_LEN
];
7268 const char *recommendation
= "ignore";
7270 char *or_id
= NULL
, *hostaddr
= NULL
;
7271 or_connection_t
*or_conn
= NULL
;
7273 /* bootstrap_percent must not be in "undefined" state here. */
7274 tor_assert(status
>= 0);
7276 if (bootstrap_percent
== 100)
7277 return; /* already bootstrapped; nothing to be done here. */
7279 bootstrap_problems
++;
7281 if (bootstrap_problems
>= BOOTSTRAP_PROBLEM_THRESHOLD
)
7284 /* Don't warn about our bootstrapping status if we are hibernating or
7286 if (we_are_hibernating())
7289 tor_assert(bootstrap_status_to_string(bootstrap_phase
, &tag
, &summary
) == 0);
7291 severity
= dowarn
? LOG_WARN
: LOG_INFO
;
7294 recommendation
= "warn";
7296 if (conn
&& conn
->type
== CONN_TYPE_OR
) {
7297 /* XXX TO_OR_CONN can't deal with const */
7298 or_conn
= TO_OR_CONN((connection_t
*)conn
);
7299 or_id
= tor_strdup(hex_str(or_conn
->identity_digest
, DIGEST_LEN
));
7301 or_id
= tor_strdup("?");
7305 tor_asprintf(&hostaddr
, "%s:%d", conn
->address
, (int)conn
->port
);
7307 hostaddr
= tor_strdup("?");
7310 LD_CONTROL
, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
7311 "count %d; recommendation %s; host %s at %s)",
7312 status
, summary
, warn
, reason
,
7313 bootstrap_problems
, recommendation
,
7316 connection_or_report_broken_states(severity
, LD_HANDSHAKE
);
7318 tor_snprintf(buf
, sizeof(buf
),
7319 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
7320 "COUNT=%d RECOMMENDATION=%s HOSTID=\"%s\" HOSTADDR=\"%s\"",
7321 bootstrap_percent
, tag
, summary
, warn
, reason
, bootstrap_problems
,
7325 tor_snprintf(last_sent_bootstrap_message
,
7326 sizeof(last_sent_bootstrap_message
),
7328 control_event_client_status(LOG_WARN
, "%s", buf
);
7334 /** Called when Tor has failed to make bootstrapping progress in a way
7335 * that indicates a problem. <b>warn</b> gives a hint as to why, and
7336 * <b>reason</b> provides an "or_conn_end_reason" tag. <b>or_conn</b>
7337 * is the connection that caused this problem.
7340 control_event_bootstrap_prob_or
, (const char *warn
, int reason
,
7341 or_connection_t
*or_conn
))
7345 if (or_conn
->have_noted_bootstrap_problem
)
7348 or_conn
->have_noted_bootstrap_problem
= 1;
7350 if (reason
== END_OR_CONN_REASON_NO_ROUTE
)
7353 /* If we are using bridges and all our OR connections are now
7354 closed, it means that we totally failed to connect to our
7355 bridges. Throw a warning. */
7356 if (get_options()->UseBridges
&& !any_other_active_or_conns(or_conn
))
7359 control_event_bootstrap_problem(warn
,
7360 orconn_end_reason_to_control_string(reason
),
7361 TO_CONN(or_conn
), dowarn
);
7364 /** We just generated a new summary of which countries we've seen clients
7365 * from recently. Send a copy to the controller in case it wants to
7366 * display it for the user. */
7368 control_event_clients_seen(const char *controller_str
)
7370 send_control_event(EVENT_CLIENTS_SEEN
,
7371 "650 CLIENTS_SEEN %s\r\n", controller_str
);
7374 /** A new pluggable transport called <b>transport_name</b> was
7375 * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
7376 * "server" or "client" depending on the mode of the pluggable
7378 * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
7381 control_event_transport_launched(const char *mode
, const char *transport_name
,
7382 tor_addr_t
*addr
, uint16_t port
)
7384 send_control_event(EVENT_TRANSPORT_LAUNCHED
,
7385 "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
7386 mode
, transport_name
, fmt_addr(addr
), port
);
7389 /** Convert rendezvous auth type to string for HS_DESC control events
7392 rend_auth_type_to_string(rend_auth_type_t auth_type
)
7396 switch (auth_type
) {
7400 case REND_BASIC_AUTH
:
7403 case REND_STEALTH_AUTH
:
7404 str
= "STEALTH_AUTH";
7413 /** Return a longname the node whose identity is <b>id_digest</b>. If
7414 * node_get_by_id() returns NULL, base 16 encoding of <b>id_digest</b> is
7417 * This function is not thread-safe. Each call to this function invalidates
7418 * previous values returned by this function.
7420 MOCK_IMPL(const char *,
7421 node_describe_longname_by_id
,(const char *id_digest
))
7423 static char longname
[MAX_VERBOSE_NICKNAME_LEN
+1];
7424 node_get_verbose_nickname_by_id(id_digest
, longname
);
7428 /** Return either the onion address if the given pointer is a non empty
7429 * string else the unknown string. */
7431 rend_hsaddress_str_or_unknown(const char *onion_address
)
7433 static const char *str_unknown
= "UNKNOWN";
7434 const char *str_ret
= str_unknown
;
7436 /* No valid pointer, unknown it is. */
7437 if (!onion_address
) {
7440 /* Empty onion address thus we don't know, unknown it is. */
7441 if (onion_address
[0] == '\0') {
7444 /* All checks are good so return the given onion address. */
7445 str_ret
= onion_address
;
7451 /** send HS_DESC requested event.
7453 * <b>rend_query</b> is used to fetch requested onion address and auth type.
7454 * <b>hs_dir</b> is the description of contacting hs directory.
7455 * <b>desc_id_base32</b> is the ID of requested hs descriptor.
7456 * <b>hsdir_index</b> is the HSDir fetch index value for v3, an hex string.
7459 control_event_hs_descriptor_requested(const char *onion_address
,
7460 rend_auth_type_t auth_type
,
7461 const char *id_digest
,
7462 const char *desc_id
,
7463 const char *hsdir_index
)
7465 char *hsdir_index_field
= NULL
;
7467 if (BUG(!id_digest
|| !desc_id
)) {
7472 tor_asprintf(&hsdir_index_field
, " HSDIR_INDEX=%s", hsdir_index
);
7475 send_control_event(EVENT_HS_DESC
,
7476 "650 HS_DESC REQUESTED %s %s %s %s%s\r\n",
7477 rend_hsaddress_str_or_unknown(onion_address
),
7478 rend_auth_type_to_string(auth_type
),
7479 node_describe_longname_by_id(id_digest
),
7481 hsdir_index_field
? hsdir_index_field
: "");
7482 tor_free(hsdir_index_field
);
7485 /** For an HS descriptor query <b>rend_data</b>, using the
7486 * <b>onion_address</b> and HSDir fingerprint <b>hsdir_fp</b>, find out
7487 * which descriptor ID in the query is the right one.
7489 * Return a pointer of the binary descriptor ID found in the query's object
7490 * or NULL if not found. */
7492 get_desc_id_from_query(const rend_data_t
*rend_data
, const char *hsdir_fp
)
7495 const char *desc_id
= NULL
;
7496 const rend_data_v2_t
*rend_data_v2
= TO_REND_DATA_V2(rend_data
);
7498 /* Possible if the fetch was done using a descriptor ID. This means that
7499 * the HSFETCH command was used. */
7500 if (!tor_digest_is_zero(rend_data_v2
->desc_id_fetch
)) {
7501 desc_id
= rend_data_v2
->desc_id_fetch
;
7505 /* Without a directory fingerprint at this stage, we can't do much. */
7506 if (hsdir_fp
== NULL
) {
7510 /* OK, we have an onion address so now let's find which descriptor ID
7511 * is the one associated with the HSDir fingerprint. */
7512 for (replica
= 0; replica
< REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS
;
7514 const char *digest
= rend_data_get_desc_id(rend_data
, replica
, NULL
);
7516 SMARTLIST_FOREACH_BEGIN(rend_data
->hsdirs_fp
, char *, fingerprint
) {
7517 if (tor_memcmp(fingerprint
, hsdir_fp
, DIGEST_LEN
) == 0) {
7518 /* Found it! This descriptor ID is the right one. */
7522 } SMARTLIST_FOREACH_END(fingerprint
);
7529 /** send HS_DESC CREATED event when a local service generates a descriptor.
7531 * <b>onion_address</b> is service address.
7532 * <b>desc_id</b> is the descriptor ID.
7533 * <b>replica</b> is the the descriptor replica number. If it is negative, it
7537 control_event_hs_descriptor_created(const char *onion_address
,
7538 const char *desc_id
,
7541 char *replica_field
= NULL
;
7543 if (BUG(!onion_address
|| !desc_id
)) {
7548 tor_asprintf(&replica_field
, " REPLICA=%d", replica
);
7551 send_control_event(EVENT_HS_DESC
,
7552 "650 HS_DESC CREATED %s UNKNOWN UNKNOWN %s%s\r\n",
7553 onion_address
, desc_id
,
7554 replica_field
? replica_field
: "");
7555 tor_free(replica_field
);
7558 /** send HS_DESC upload event.
7560 * <b>onion_address</b> is service address.
7561 * <b>hs_dir</b> is the description of contacting hs directory.
7562 * <b>desc_id</b> is the ID of requested hs descriptor.
7565 control_event_hs_descriptor_upload(const char *onion_address
,
7566 const char *id_digest
,
7567 const char *desc_id
,
7568 const char *hsdir_index
)
7570 char *hsdir_index_field
= NULL
;
7572 if (BUG(!onion_address
|| !id_digest
|| !desc_id
)) {
7577 tor_asprintf(&hsdir_index_field
, " HSDIR_INDEX=%s", hsdir_index
);
7580 send_control_event(EVENT_HS_DESC
,
7581 "650 HS_DESC UPLOAD %s UNKNOWN %s %s%s\r\n",
7583 node_describe_longname_by_id(id_digest
),
7585 hsdir_index_field
? hsdir_index_field
: "");
7586 tor_free(hsdir_index_field
);
7589 /** send HS_DESC event after got response from hs directory.
7591 * NOTE: this is an internal function used by following functions:
7592 * control_event_hsv2_descriptor_received
7593 * control_event_hsv2_descriptor_failed
7594 * control_event_hsv3_descriptor_failed
7596 * So do not call this function directly.
7599 event_hs_descriptor_receive_end(const char *action
,
7600 const char *onion_address
,
7601 const char *desc_id
,
7602 rend_auth_type_t auth_type
,
7603 const char *hsdir_id_digest
,
7606 char *reason_field
= NULL
;
7608 if (BUG(!action
|| !onion_address
)) {
7613 tor_asprintf(&reason_field
, " REASON=%s", reason
);
7616 send_control_event(EVENT_HS_DESC
,
7617 "650 HS_DESC %s %s %s %s%s%s\r\n",
7619 rend_hsaddress_str_or_unknown(onion_address
),
7620 rend_auth_type_to_string(auth_type
),
7622 node_describe_longname_by_id(hsdir_id_digest
) :
7624 desc_id
? desc_id
: "",
7625 reason_field
? reason_field
: "");
7627 tor_free(reason_field
);
7630 /** send HS_DESC event after got response from hs directory.
7632 * NOTE: this is an internal function used by following functions:
7633 * control_event_hs_descriptor_uploaded
7634 * control_event_hs_descriptor_upload_failed
7636 * So do not call this function directly.
7639 control_event_hs_descriptor_upload_end(const char *action
,
7640 const char *onion_address
,
7641 const char *id_digest
,
7644 char *reason_field
= NULL
;
7646 if (BUG(!action
|| !id_digest
)) {
7651 tor_asprintf(&reason_field
, " REASON=%s", reason
);
7654 send_control_event(EVENT_HS_DESC
,
7655 "650 HS_DESC %s %s UNKNOWN %s%s\r\n",
7657 rend_hsaddress_str_or_unknown(onion_address
),
7658 node_describe_longname_by_id(id_digest
),
7659 reason_field
? reason_field
: "");
7661 tor_free(reason_field
);
7664 /** send HS_DESC RECEIVED event
7666 * called when we successfully received a hidden service descriptor.
7669 control_event_hsv2_descriptor_received(const char *onion_address
,
7670 const rend_data_t
*rend_data
,
7671 const char *hsdir_id_digest
)
7673 char *desc_id_field
= NULL
;
7674 const char *desc_id
;
7676 if (BUG(!rend_data
|| !hsdir_id_digest
|| !onion_address
)) {
7680 desc_id
= get_desc_id_from_query(rend_data
, hsdir_id_digest
);
7681 if (desc_id
!= NULL
) {
7682 char desc_id_base32
[REND_DESC_ID_V2_LEN_BASE32
+ 1];
7683 /* Set the descriptor ID digest to base32 so we can send it. */
7684 base32_encode(desc_id_base32
, sizeof(desc_id_base32
), desc_id
,
7686 /* Extra whitespace is needed before the value. */
7687 tor_asprintf(&desc_id_field
, " %s", desc_id_base32
);
7690 event_hs_descriptor_receive_end("RECEIVED", onion_address
, desc_id_field
,
7691 TO_REND_DATA_V2(rend_data
)->auth_type
,
7692 hsdir_id_digest
, NULL
);
7693 tor_free(desc_id_field
);
7696 /* Send HS_DESC RECEIVED event
7698 * Called when we successfully received a hidden service descriptor. */
7700 control_event_hsv3_descriptor_received(const char *onion_address
,
7701 const char *desc_id
,
7702 const char *hsdir_id_digest
)
7704 char *desc_id_field
= NULL
;
7706 if (BUG(!onion_address
|| !desc_id
|| !hsdir_id_digest
)) {
7710 /* Because DescriptorID is an optional positional value, we need to add a
7711 * whitespace before in order to not be next to the HsDir value. */
7712 tor_asprintf(&desc_id_field
, " %s", desc_id
);
7714 event_hs_descriptor_receive_end("RECEIVED", onion_address
, desc_id_field
,
7715 REND_NO_AUTH
, hsdir_id_digest
, NULL
);
7716 tor_free(desc_id_field
);
7719 /** send HS_DESC UPLOADED event
7721 * called when we successfully uploaded a hidden service descriptor.
7724 control_event_hs_descriptor_uploaded(const char *id_digest
,
7725 const char *onion_address
)
7727 if (BUG(!id_digest
)) {
7731 control_event_hs_descriptor_upload_end("UPLOADED", onion_address
,
7735 /** Send HS_DESC event to inform controller that query <b>rend_data</b>
7736 * failed to retrieve hidden service descriptor from directory identified by
7737 * <b>id_digest</b>. If NULL, "UNKNOWN" is used. If <b>reason</b> is not NULL,
7738 * add it to REASON= field.
7741 control_event_hsv2_descriptor_failed(const rend_data_t
*rend_data
,
7742 const char *hsdir_id_digest
,
7745 char *desc_id_field
= NULL
;
7746 const char *desc_id
;
7748 if (BUG(!rend_data
)) {
7752 desc_id
= get_desc_id_from_query(rend_data
, hsdir_id_digest
);
7753 if (desc_id
!= NULL
) {
7754 char desc_id_base32
[REND_DESC_ID_V2_LEN_BASE32
+ 1];
7755 /* Set the descriptor ID digest to base32 so we can send it. */
7756 base32_encode(desc_id_base32
, sizeof(desc_id_base32
), desc_id
,
7758 /* Extra whitespace is needed before the value. */
7759 tor_asprintf(&desc_id_field
, " %s", desc_id_base32
);
7762 event_hs_descriptor_receive_end("FAILED", rend_data_get_address(rend_data
),
7764 TO_REND_DATA_V2(rend_data
)->auth_type
,
7765 hsdir_id_digest
, reason
);
7766 tor_free(desc_id_field
);
7769 /** Send HS_DESC event to inform controller that the query to
7770 * <b>onion_address</b> failed to retrieve hidden service descriptor
7771 * <b>desc_id</b> from directory identified by <b>hsdir_id_digest</b>. If
7772 * NULL, "UNKNOWN" is used. If <b>reason</b> is not NULL, add it to REASON=
7775 control_event_hsv3_descriptor_failed(const char *onion_address
,
7776 const char *desc_id
,
7777 const char *hsdir_id_digest
,
7780 char *desc_id_field
= NULL
;
7782 if (BUG(!onion_address
|| !desc_id
|| !reason
)) {
7786 /* Because DescriptorID is an optional positional value, we need to add a
7787 * whitespace before in order to not be next to the HsDir value. */
7788 tor_asprintf(&desc_id_field
, " %s", desc_id
);
7790 event_hs_descriptor_receive_end("FAILED", onion_address
, desc_id_field
,
7791 REND_NO_AUTH
, hsdir_id_digest
, reason
);
7792 tor_free(desc_id_field
);
7795 /** Send HS_DESC_CONTENT event after completion of a successful fetch
7796 * from hs directory. If <b>hsdir_id_digest</b> is NULL, it is replaced
7797 * by "UNKNOWN". If <b>content</b> is NULL, it is replaced by an empty
7798 * string. The <b>onion_address</b> or <b>desc_id</b> set to NULL will
7799 * not trigger the control event. */
7801 control_event_hs_descriptor_content(const char *onion_address
,
7802 const char *desc_id
,
7803 const char *hsdir_id_digest
,
7804 const char *content
)
7806 static const char *event_name
= "HS_DESC_CONTENT";
7807 char *esc_content
= NULL
;
7809 if (!onion_address
|| !desc_id
) {
7810 log_warn(LD_BUG
, "Called with onion_address==%p, desc_id==%p, ",
7811 onion_address
, desc_id
);
7815 if (content
== NULL
) {
7816 /* Point it to empty content so it can still be escaped. */
7819 write_escaped_data(content
, strlen(content
), &esc_content
);
7821 send_control_event(EVENT_HS_DESC_CONTENT
,
7822 "650+%s %s %s %s\r\n%s650 OK\r\n",
7824 rend_hsaddress_str_or_unknown(onion_address
),
7827 node_describe_longname_by_id(hsdir_id_digest
) :
7830 tor_free(esc_content
);
7833 /** Send HS_DESC event to inform controller upload of hidden service
7834 * descriptor identified by <b>id_digest</b> failed. If <b>reason</b>
7835 * is not NULL, add it to REASON= field.
7838 control_event_hs_descriptor_upload_failed(const char *id_digest
,
7839 const char *onion_address
,
7842 if (BUG(!id_digest
)) {
7845 control_event_hs_descriptor_upload_end("FAILED", onion_address
,
7849 /** Free any leftover allocated memory of the control.c subsystem. */
7851 control_free_all(void)
7853 smartlist_t
*queued_events
= NULL
;
7855 stats_prev_n_read
= stats_prev_n_written
= 0;
7857 if (authentication_cookie
) /* Free the auth cookie */
7858 tor_free(authentication_cookie
);
7859 if (detached_onion_services
) { /* Free the detached onion services */
7860 SMARTLIST_FOREACH(detached_onion_services
, char *, cp
, tor_free(cp
));
7861 smartlist_free(detached_onion_services
);
7864 if (queued_control_events_lock
) {
7865 tor_mutex_acquire(queued_control_events_lock
);
7866 flush_queued_event_pending
= 0;
7867 queued_events
= queued_control_events
;
7868 queued_control_events
= NULL
;
7869 tor_mutex_release(queued_control_events_lock
);
7871 if (queued_events
) {
7872 SMARTLIST_FOREACH(queued_events
, queued_event_t
*, ev
,
7873 queued_event_free(ev
));
7874 smartlist_free(queued_events
);
7876 if (flush_queued_events_event
) {
7877 mainloop_event_free(flush_queued_events_event
);
7878 flush_queued_events_event
= NULL
;
7880 bootstrap_percent
= BOOTSTRAP_STATUS_UNDEF
;
7881 notice_bootstrap_percent
= 0;
7882 bootstrap_problems
= 0;
7883 authentication_cookie_is_set
= 0;
7884 global_event_mask
= 0;
7885 disable_log_messages
= 0;
7886 memset(last_sent_bootstrap_message
, 0, sizeof(last_sent_bootstrap_message
));
7889 #ifdef TOR_UNIT_TESTS
7890 /* For testing: change the value of global_event_mask */
7892 control_testing_set_global_event_mask(uint64_t mask
)
7894 global_event_mask
= mask
;
7896 #endif /* defined(TOR_UNIT_TESTS) */