2 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2019, 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/or/versions.h"
56 #include "core/proto/proto_control0.h"
57 #include "core/proto/proto_http.h"
58 #include "feature/client/addressmap.h"
59 #include "feature/client/bridges.h"
60 #include "feature/client/dnsserv.h"
61 #include "feature/client/entrynodes.h"
62 #include "feature/control/control.h"
63 #include "feature/control/fmt_serverstatus.h"
64 #include "feature/control/getinfo_geoip.h"
65 #include "feature/dircache/dirserv.h"
66 #include "feature/dirclient/dirclient.h"
67 #include "feature/dirclient/dlstatus.h"
68 #include "feature/dircommon/directory.h"
69 #include "feature/hibernate/hibernate.h"
70 #include "feature/hs/hs_cache.h"
71 #include "feature/hs/hs_common.h"
72 #include "feature/hs/hs_control.h"
73 #include "feature/hs_common/shared_random_client.h"
74 #include "feature/nodelist/authcert.h"
75 #include "feature/nodelist/dirlist.h"
76 #include "feature/nodelist/microdesc.h"
77 #include "feature/nodelist/networkstatus.h"
78 #include "feature/nodelist/nodelist.h"
79 #include "feature/nodelist/routerinfo.h"
80 #include "feature/nodelist/routerlist.h"
81 #include "feature/relay/router.h"
82 #include "feature/relay/routermode.h"
83 #include "feature/relay/selftest.h"
84 #include "feature/rend/rendclient.h"
85 #include "feature/rend/rendcommon.h"
86 #include "feature/rend/rendparse.h"
87 #include "feature/rend/rendservice.h"
88 #include "feature/stats/geoip_stats.h"
89 #include "feature/stats/predict_ports.h"
90 #include "lib/container/buffers.h"
91 #include "lib/crypt_ops/crypto_rand.h"
92 #include "lib/crypt_ops/crypto_util.h"
93 #include "lib/encoding/confline.h"
94 #include "lib/evloop/compat_libevent.h"
96 #include "feature/dircache/cached_dir_st.h"
97 #include "feature/control/control_connection_st.h"
98 #include "core/or/cpath_build_state_st.h"
99 #include "core/or/entry_connection_st.h"
100 #include "feature/nodelist/extrainfo_st.h"
101 #include "feature/nodelist/networkstatus_st.h"
102 #include "feature/nodelist/node_st.h"
103 #include "core/or/or_connection_st.h"
104 #include "core/or/or_circuit_st.h"
105 #include "core/or/origin_circuit_st.h"
106 #include "feature/nodelist/microdesc_st.h"
107 #include "feature/rend/rend_authorized_client_st.h"
108 #include "feature/rend/rend_encoded_v2_service_descriptor_st.h"
109 #include "feature/rend/rend_service_descriptor_st.h"
110 #include "feature/nodelist/routerinfo_st.h"
111 #include "feature/nodelist/routerlist_st.h"
112 #include "core/or/socks_request_st.h"
117 #ifdef HAVE_SYS_STAT_H
118 #include <sys/stat.h>
123 #include <sys/resource.h>
126 #include "lib/crypt_ops/crypto_s2k.h"
127 #include "lib/evloop/procmon.h"
128 #include "lib/evloop/compat_libevent.h"
130 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
131 * finished authentication and is accepting commands. */
132 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
134 /** Bitfield: The bit 1<<e is set if <b>any</b> open control
135 * connection is interested in events of type <b>e</b>. We use this
136 * so that we can decide to skip generating event messages that nobody
137 * has interest in without having to walk over the global connection
140 typedef uint64_t event_mask_t
;
142 /** An event mask of all the events that any controller is interested in
144 static event_mask_t global_event_mask
= 0;
146 /** True iff we have disabled log messages from being sent to the controller */
147 static int disable_log_messages
= 0;
149 /** Macro: true if any control connection is interested in events of type
151 #define EVENT_IS_INTERESTING(e) \
152 (!! (global_event_mask & EVENT_MASK_(e)))
154 /** Macro: true if any event from the bitfield 'e' is interesting. */
155 #define ANY_EVENT_IS_INTERESTING(e) \
156 (!! (global_event_mask & (e)))
158 /** If we're using cookie-type authentication, how long should our cookies be?
160 #define AUTHENTICATION_COOKIE_LEN 32
162 /** If true, we've set authentication_cookie to a secret code and
163 * stored it to disk. */
164 static int authentication_cookie_is_set
= 0;
165 /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
166 * and which we're using to authenticate controllers. (If the controller can
167 * read it off disk, it has permission to connect.) */
168 static uint8_t *authentication_cookie
= NULL
;
170 #define SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT \
171 "Tor safe cookie authentication server-to-controller hash"
172 #define SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT \
173 "Tor safe cookie authentication controller-to-server hash"
174 #define SAFECOOKIE_SERVER_NONCE_LEN DIGEST256_LEN
176 /** The list of onion services that have been added via ADD_ONION that do not
177 * belong to any particular control connection.
179 static smartlist_t
*detached_onion_services
= NULL
;
181 /** A sufficiently large size to record the last bootstrap phase string. */
182 #define BOOTSTRAP_MSG_LEN 1024
184 /** What was the last bootstrap phase message we sent? We keep track
185 * of this so we can respond to getinfo status/bootstrap-phase queries. */
186 static char last_sent_bootstrap_message
[BOOTSTRAP_MSG_LEN
];
188 static void connection_printf_to_buf(control_connection_t
*conn
,
189 const char *format
, ...)
191 static void send_control_event_impl(uint16_t event
,
192 const char *format
, va_list ap
)
194 static int control_event_status(int type
, int severity
, const char *format
,
198 static void send_control_done(control_connection_t
*conn
);
199 static void send_control_event(uint16_t event
,
200 const char *format
, ...)
202 static int handle_control_setconf(control_connection_t
*conn
, uint32_t len
,
204 static int handle_control_resetconf(control_connection_t
*conn
, uint32_t len
,
206 static int handle_control_getconf(control_connection_t
*conn
, uint32_t len
,
208 static int handle_control_loadconf(control_connection_t
*conn
, uint32_t len
,
210 static int handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
212 static int handle_control_authenticate(control_connection_t
*conn
,
215 static int handle_control_signal(control_connection_t
*conn
, uint32_t len
,
217 static int handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
219 static char *list_getinfo_options(void);
220 static int handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
222 static int handle_control_extendcircuit(control_connection_t
*conn
,
225 static int handle_control_setcircuitpurpose(control_connection_t
*conn
,
226 uint32_t len
, const char *body
);
227 static int handle_control_attachstream(control_connection_t
*conn
,
230 static int handle_control_postdescriptor(control_connection_t
*conn
,
233 static int handle_control_redirectstream(control_connection_t
*conn
,
236 static int handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
238 static int handle_control_closecircuit(control_connection_t
*conn
,
241 static int handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
243 static int handle_control_usefeature(control_connection_t
*conn
,
246 static int handle_control_hsfetch(control_connection_t
*conn
, uint32_t len
,
248 static int handle_control_hspost(control_connection_t
*conn
, uint32_t len
,
250 static int handle_control_add_onion(control_connection_t
*conn
, uint32_t len
,
252 static int handle_control_del_onion(control_connection_t
*conn
, uint32_t len
,
254 static int write_stream_target_to_buf(entry_connection_t
*conn
, char *buf
,
256 static void orconn_target_get_name(char *buf
, size_t len
,
257 or_connection_t
*conn
);
259 static int get_cached_network_liveness(void);
260 static void set_cached_network_liveness(int liveness
);
262 static void flush_queued_events_cb(mainloop_event_t
*event
, void *arg
);
264 static char * download_status_to_string(const download_status_t
*dl
);
265 static void control_get_bytes_rw_last_sec(uint64_t *r
, uint64_t *w
);
267 /** Convert a connection_t* to an control_connection_t*; assert if the cast is
269 control_connection_t
*
270 TO_CONTROL_CONN(connection_t
*c
)
272 tor_assert(c
->magic
== CONTROL_CONNECTION_MAGIC
);
273 return DOWNCAST(control_connection_t
, c
);
276 /** Given a control event code for a message event, return the corresponding
279 event_to_log_severity(int event
)
282 case EVENT_DEBUG_MSG
: return LOG_DEBUG
;
283 case EVENT_INFO_MSG
: return LOG_INFO
;
284 case EVENT_NOTICE_MSG
: return LOG_NOTICE
;
285 case EVENT_WARN_MSG
: return LOG_WARN
;
286 case EVENT_ERR_MSG
: return LOG_ERR
;
291 /** Given a log severity, return the corresponding control event code. */
293 log_severity_to_event(int severity
)
296 case LOG_DEBUG
: return EVENT_DEBUG_MSG
;
297 case LOG_INFO
: return EVENT_INFO_MSG
;
298 case LOG_NOTICE
: return EVENT_NOTICE_MSG
;
299 case LOG_WARN
: return EVENT_WARN_MSG
;
300 case LOG_ERR
: return EVENT_ERR_MSG
;
305 /** Helper: clear bandwidth counters of all origin circuits. */
307 clear_circ_bw_fields(void)
309 origin_circuit_t
*ocirc
;
310 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t
*, circ
) {
311 if (!CIRCUIT_IS_ORIGIN(circ
))
313 ocirc
= TO_ORIGIN_CIRCUIT(circ
);
314 ocirc
->n_written_circ_bw
= ocirc
->n_read_circ_bw
= 0;
315 ocirc
->n_overhead_written_circ_bw
= ocirc
->n_overhead_read_circ_bw
= 0;
316 ocirc
->n_delivered_written_circ_bw
= ocirc
->n_delivered_read_circ_bw
= 0;
318 SMARTLIST_FOREACH_END(circ
);
321 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
322 * connection's event_mask field. */
324 control_update_global_event_mask(void)
326 smartlist_t
*conns
= get_connection_array();
327 event_mask_t old_mask
, new_mask
;
328 old_mask
= global_event_mask
;
329 int any_old_per_sec_events
= control_any_per_second_event_enabled();
331 global_event_mask
= 0;
332 SMARTLIST_FOREACH(conns
, connection_t
*, _conn
,
334 if (_conn
->type
== CONN_TYPE_CONTROL
&&
335 STATE_IS_OPEN(_conn
->state
)) {
336 control_connection_t
*conn
= TO_CONTROL_CONN(_conn
);
337 global_event_mask
|= conn
->event_mask
;
341 new_mask
= global_event_mask
;
343 /* Handle the aftermath. Set up the log callback to tell us only what
344 * we want to hear...*/
345 control_adjust_event_log_severity();
347 /* Macro: true if ev was false before and is true now. */
348 #define NEWLY_ENABLED(ev) \
349 (! (old_mask & (ev)) && (new_mask & (ev)))
351 /* ...then, if we've started logging stream or circ bw, clear the
352 * appropriate fields. */
353 if (NEWLY_ENABLED(EVENT_STREAM_BANDWIDTH_USED
)) {
354 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
356 if (conn
->type
== CONN_TYPE_AP
) {
357 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
358 edge_conn
->n_written
= edge_conn
->n_read
= 0;
362 if (NEWLY_ENABLED(EVENT_CIRC_BANDWIDTH_USED
)) {
363 clear_circ_bw_fields();
365 if (NEWLY_ENABLED(EVENT_BANDWIDTH_USED
)) {
367 control_get_bytes_rw_last_sec(&r
, &w
);
369 if (any_old_per_sec_events
!= control_any_per_second_event_enabled()) {
370 reschedule_per_second_timer();
376 /** Adjust the log severities that result in control_event_logmsg being called
377 * to match the severity of log messages that any controllers are interested
380 control_adjust_event_log_severity(void)
383 int min_log_event
=EVENT_ERR_MSG
, max_log_event
=EVENT_DEBUG_MSG
;
385 for (i
= EVENT_DEBUG_MSG
; i
<= EVENT_ERR_MSG
; ++i
) {
386 if (EVENT_IS_INTERESTING(i
)) {
391 for (i
= EVENT_ERR_MSG
; i
>= EVENT_DEBUG_MSG
; --i
) {
392 if (EVENT_IS_INTERESTING(i
)) {
397 if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
)) {
398 if (min_log_event
> EVENT_NOTICE_MSG
)
399 min_log_event
= EVENT_NOTICE_MSG
;
400 if (max_log_event
< EVENT_ERR_MSG
)
401 max_log_event
= EVENT_ERR_MSG
;
403 if (min_log_event
<= max_log_event
)
404 change_callback_log_severity(event_to_log_severity(min_log_event
),
405 event_to_log_severity(max_log_event
),
406 control_event_logmsg
);
408 change_callback_log_severity(LOG_ERR
, LOG_ERR
,
409 control_event_logmsg
);
412 /** Return true iff the event with code <b>c</b> is being sent to any current
413 * control connection. This is useful if the amount of work needed to prepare
414 * to call the appropriate control_event_...() function is high.
417 control_event_is_interesting(int event
)
419 return EVENT_IS_INTERESTING(event
);
422 /** Return true if any event that needs to fire once a second is enabled. */
424 control_any_per_second_event_enabled(void)
426 return ANY_EVENT_IS_INTERESTING(
427 EVENT_MASK_(EVENT_BANDWIDTH_USED
) |
428 EVENT_MASK_(EVENT_CELL_STATS
) |
429 EVENT_MASK_(EVENT_CIRC_BANDWIDTH_USED
) |
430 EVENT_MASK_(EVENT_CONN_BW
) |
431 EVENT_MASK_(EVENT_STREAM_BANDWIDTH_USED
)
435 /* The value of 'get_bytes_read()' the previous time that
436 * control_get_bytes_rw_last_sec() as called. */
437 static uint64_t stats_prev_n_read
= 0;
438 /* The value of 'get_bytes_written()' the previous time that
439 * control_get_bytes_rw_last_sec() as called. */
440 static uint64_t stats_prev_n_written
= 0;
443 * Set <b>n_read</b> and <b>n_written</b> to the total number of bytes read
444 * and written by Tor since the last call to this function.
446 * Call this only from the main thread.
449 control_get_bytes_rw_last_sec(uint64_t *n_read
,
452 const uint64_t stats_n_bytes_read
= get_bytes_read();
453 const uint64_t stats_n_bytes_written
= get_bytes_written();
455 *n_read
= stats_n_bytes_read
- stats_prev_n_read
;
456 *n_written
= stats_n_bytes_written
- stats_prev_n_written
;
457 stats_prev_n_read
= stats_n_bytes_read
;
458 stats_prev_n_written
= stats_n_bytes_written
;
462 * Run all the controller events (if any) that are scheduled to trigger once
466 control_per_second_events(void)
468 if (!control_any_per_second_event_enabled())
471 uint64_t bytes_read
, bytes_written
;
472 control_get_bytes_rw_last_sec(&bytes_read
, &bytes_written
);
473 control_event_bandwidth_used((uint32_t)bytes_read
,(uint32_t)bytes_written
);
475 control_event_stream_bandwidth_used();
476 control_event_conn_bandwidth_used();
477 control_event_circ_bandwidth_used();
478 control_event_circuit_cell_stats();
481 /** Append a NUL-terminated string <b>s</b> to the end of
482 * <b>conn</b>-\>outbuf.
485 connection_write_str_to_buf(const char *s
, control_connection_t
*conn
)
487 size_t len
= strlen(s
);
488 connection_buf_add(s
, len
, TO_CONN(conn
));
491 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
492 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
493 * contents of <b>data</b> into *<b>out</b>, adding a period before any period
494 * that appears at the start of a line, and adding a period-CRLF line at
495 * the end. Replace all LF characters sequences with CRLF. Return the number
496 * of bytes in *<b>out</b>.
499 write_escaped_data(const char *data
, size_t len
, char **out
)
501 tor_assert(len
< SIZE_MAX
- 9);
502 size_t sz_out
= len
+8+1;
504 const char *start
= data
, *end
;
507 for (i
=0; i
< len
; ++i
) {
508 if (data
[i
] == '\n') {
509 sz_out
+= 2; /* Maybe add a CR; maybe add a dot. */
510 if (sz_out
>= SIZE_T_CEILING
) {
511 log_warn(LD_BUG
, "Input to write_escaped_data was too long");
512 *out
= tor_strdup(".\r\n");
517 *out
= outp
= tor_malloc(sz_out
);
522 if (data
> start
&& data
[-1] != '\r')
525 } else if (*data
== '.') {
535 if (outp
< *out
+2 || fast_memcmp(outp
-2, "\r\n", 2)) {
542 *outp
= '\0'; /* NUL-terminate just in case. */
543 tor_assert(outp
>= *out
);
544 tor_assert((size_t)(outp
- *out
) <= sz_out
);
548 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
549 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
550 * the contents of <b>data</b> into *<b>out</b>, removing any period
551 * that appears at the start of a line, and replacing all CRLF sequences
552 * with LF. Return the number of
553 * bytes in *<b>out</b>. */
555 read_escaped_data(const char *data
, size_t len
, char **out
)
561 *out
= outp
= tor_malloc(len
+1);
566 /* we're at the start of a line. */
569 next
= memchr(data
, '\n', end
-data
);
571 size_t n_to_copy
= next
-data
;
572 /* Don't copy a CR that precedes this LF. */
573 if (n_to_copy
&& *(next
-1) == '\r')
575 memcpy(outp
, data
, n_to_copy
);
577 data
= next
+1; /* This will point at the start of the next line,
578 * or the end of the string, or a period. */
580 memcpy(outp
, data
, end
-data
);
592 /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
593 * double-quoted string with escaped characters, return the length of that
594 * string (as encoded, including quotes). Otherwise return -1. */
596 get_escaped_string_length(const char *start
, size_t in_len_max
,
599 const char *cp
, *end
;
606 end
= start
+in_len_max
;
608 /* Calculate length. */
611 return -1; /* Too long. */
612 } else if (*cp
== '\\') {
614 return -1; /* Can't escape EOS. */
617 } else if (*cp
== '\"') {
626 return (int)(cp
- start
+1);
629 /** As decode_escaped_string, but does not decode the string: copies the
630 * entire thing, including quotation marks. */
632 extract_escaped_string(const char *start
, size_t in_len_max
,
633 char **out
, size_t *out_len
)
635 int length
= get_escaped_string_length(start
, in_len_max
, NULL
);
639 *out
= tor_strndup(start
, *out_len
);
643 /** Given a pointer to a string starting at <b>start</b> containing
644 * <b>in_len_max</b> characters, decode a string beginning with one double
645 * quote, containing any number of non-quote characters or characters escaped
646 * with a backslash, and ending with a final double quote. Place the resulting
647 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
648 * store its length in <b>out_len</b>. On success, return a pointer to the
649 * character immediately following the escaped string. On failure, return
652 decode_escaped_string(const char *start
, size_t in_len_max
,
653 char **out
, size_t *out_len
)
655 const char *cp
, *end
;
657 int len
, n_chars
= 0;
659 len
= get_escaped_string_length(start
, in_len_max
, &n_chars
);
663 end
= start
+len
-1; /* Index of last quote. */
664 tor_assert(*end
== '\"');
665 outp
= *out
= tor_malloc(len
+1);
675 tor_assert((outp
- *out
) == (int)*out_len
);
680 /** Create and add a new controller connection on <b>sock</b>. If
681 * <b>CC_LOCAL_FD_IS_OWNER</b> is set in <b>flags</b>, this Tor process should
682 * exit when the connection closes. If <b>CC_LOCAL_FD_IS_AUTHENTICATED</b>
683 * is set, then the connection does not need to authenticate.
686 control_connection_add_local_fd(tor_socket_t sock
, unsigned flags
)
688 if (BUG(! SOCKET_OK(sock
)))
690 const int is_owner
= !!(flags
& CC_LOCAL_FD_IS_OWNER
);
691 const int is_authenticated
= !!(flags
& CC_LOCAL_FD_IS_AUTHENTICATED
);
692 control_connection_t
*control_conn
= control_connection_new(AF_UNSPEC
);
693 connection_t
*conn
= TO_CONN(control_conn
);
695 tor_addr_make_unspec(&conn
->addr
);
697 conn
->address
= tor_strdup("<local socket>");
699 /* We take ownership of this socket so that later, when we close it,
700 * we don't freak out. */
701 tor_take_socket_ownership(sock
);
703 if (set_socket_nonblocking(sock
) < 0 ||
704 connection_add(conn
) < 0) {
705 connection_free(conn
);
709 control_conn
->is_owning_control_connection
= is_owner
;
711 if (connection_init_accepted_conn(conn
, NULL
) < 0) {
712 connection_mark_for_close(conn
);
716 if (is_authenticated
) {
717 conn
->state
= CONTROL_CONN_STATE_OPEN
;
723 /** Acts like sprintf, but writes its formatted string to the end of
724 * <b>conn</b>-\>outbuf. */
726 connection_printf_to_buf(control_connection_t
*conn
, const char *format
, ...)
733 len
= tor_vasprintf(&buf
, format
, ap
);
737 log_err(LD_BUG
, "Unable to format string for controller.");
741 connection_buf_add(buf
, (size_t)len
, TO_CONN(conn
));
746 /** Write all of the open control ports to ControlPortWriteToFile */
748 control_ports_write_to_file(void)
752 const or_options_t
*options
= get_options();
754 if (!options
->ControlPortWriteToFile
)
757 lines
= smartlist_new();
759 SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t
*, conn
) {
760 if (conn
->type
!= CONN_TYPE_CONTROL_LISTENER
|| conn
->marked_for_close
)
763 if (conn
->socket_family
== AF_UNIX
) {
764 smartlist_add_asprintf(lines
, "UNIX_PORT=%s\n", conn
->address
);
767 #endif /* defined(AF_UNIX) */
768 smartlist_add_asprintf(lines
, "PORT=%s:%d\n", conn
->address
, conn
->port
);
769 } SMARTLIST_FOREACH_END(conn
);
771 joined
= smartlist_join_strings(lines
, "", 0, NULL
);
773 if (write_str_to_file(options
->ControlPortWriteToFile
, joined
, 0) < 0) {
774 log_warn(LD_CONTROL
, "Writing %s failed: %s",
775 options
->ControlPortWriteToFile
, strerror(errno
));
778 if (options
->ControlPortFileGroupReadable
) {
779 if (chmod(options
->ControlPortWriteToFile
, 0640)) {
780 log_warn(LD_FS
,"Unable to make %s group-readable.",
781 options
->ControlPortWriteToFile
);
784 #endif /* !defined(_WIN32) */
786 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
787 smartlist_free(lines
);
790 /** Send a "DONE" message down the control connection <b>conn</b>. */
792 send_control_done(control_connection_t
*conn
)
794 connection_write_str_to_buf("250 OK\r\n", conn
);
797 /** Represents an event that's queued to be sent to one or more
799 typedef struct queued_event_s
{
804 /** Pointer to int. If this is greater than 0, we don't allow new events to be
806 static tor_threadlocal_t block_event_queue_flag
;
808 /** Holds a smartlist of queued_event_t objects that may need to be sent
809 * to one or more controllers */
810 static smartlist_t
*queued_control_events
= NULL
;
812 /** True if the flush_queued_events_event is pending. */
813 static int flush_queued_event_pending
= 0;
815 /** Lock to protect the above fields. */
816 static tor_mutex_t
*queued_control_events_lock
= NULL
;
818 /** An event that should fire in order to flush the contents of
819 * queued_control_events. */
820 static mainloop_event_t
*flush_queued_events_event
= NULL
;
823 control_initialize_event_queue(void)
825 if (queued_control_events
== NULL
) {
826 queued_control_events
= smartlist_new();
829 if (flush_queued_events_event
== NULL
) {
830 struct event_base
*b
= tor_libevent_get_base();
832 flush_queued_events_event
=
833 mainloop_event_new(flush_queued_events_cb
, NULL
);
834 tor_assert(flush_queued_events_event
);
838 if (queued_control_events_lock
== NULL
) {
839 queued_control_events_lock
= tor_mutex_new();
840 tor_threadlocal_init(&block_event_queue_flag
);
845 get_block_event_queue(void)
847 int *val
= tor_threadlocal_get(&block_event_queue_flag
);
848 if (PREDICT_UNLIKELY(val
== NULL
)) {
849 val
= tor_malloc_zero(sizeof(int));
850 tor_threadlocal_set(&block_event_queue_flag
, val
);
855 /** Helper: inserts an event on the list of events queued to be sent to
856 * one or more controllers, and schedules the events to be flushed if needed.
858 * This function takes ownership of <b>msg</b>, and may free it.
860 * We queue these events rather than send them immediately in order to break
861 * the dependency in our callgraph from code that generates events for the
862 * controller, and the network layer at large. Otherwise, nearly every
863 * interesting part of Tor would potentially call every other interesting part
866 MOCK_IMPL(STATIC
void,
867 queue_control_event_string
,(uint16_t event
, char *msg
))
869 /* This is redundant with checks done elsewhere, but it's a last-ditch
870 * attempt to avoid queueing something we shouldn't have to queue. */
871 if (PREDICT_UNLIKELY( ! EVENT_IS_INTERESTING(event
) )) {
876 int *block_event_queue
= get_block_event_queue();
877 if (*block_event_queue
) {
882 queued_event_t
*ev
= tor_malloc(sizeof(*ev
));
886 /* No queueing an event while queueing an event */
887 ++*block_event_queue
;
889 tor_mutex_acquire(queued_control_events_lock
);
890 tor_assert(queued_control_events
);
891 smartlist_add(queued_control_events
, ev
);
893 int activate_event
= 0;
894 if (! flush_queued_event_pending
&& in_main_thread()) {
896 flush_queued_event_pending
= 1;
899 tor_mutex_release(queued_control_events_lock
);
901 --*block_event_queue
;
903 /* We just put an event on the queue; mark the queue to be
904 * flushed. We only do this from the main thread for now; otherwise,
905 * we'd need to incur locking overhead in Libevent or use a socket.
907 if (activate_event
) {
908 tor_assert(flush_queued_events_event
);
909 mainloop_event_activate(flush_queued_events_event
);
913 #define queued_event_free(ev) \
914 FREE_AND_NULL(queued_event_t, queued_event_free_, (ev))
916 /** Release all storage held by <b>ev</b>. */
918 queued_event_free_(queued_event_t
*ev
)
927 /** Send every queued event to every controller that's interested in it,
928 * and remove the events from the queue. If <b>force</b> is true,
929 * then make all controllers send their data out immediately, since we
930 * may be about to shut down. */
932 queued_events_flush_all(int force
)
934 /* Make sure that we get all the pending log events, if there are any. */
935 flush_pending_log_callbacks();
937 if (PREDICT_UNLIKELY(queued_control_events
== NULL
)) {
940 smartlist_t
*all_conns
= get_connection_array();
941 smartlist_t
*controllers
= smartlist_new();
942 smartlist_t
*queued_events
;
944 int *block_event_queue
= get_block_event_queue();
945 ++*block_event_queue
;
947 tor_mutex_acquire(queued_control_events_lock
);
948 /* No queueing an event while flushing events. */
949 flush_queued_event_pending
= 0;
950 queued_events
= queued_control_events
;
951 queued_control_events
= smartlist_new();
952 tor_mutex_release(queued_control_events_lock
);
954 /* Gather all the controllers that will care... */
955 SMARTLIST_FOREACH_BEGIN(all_conns
, connection_t
*, conn
) {
956 if (conn
->type
== CONN_TYPE_CONTROL
&&
957 !conn
->marked_for_close
&&
958 conn
->state
== CONTROL_CONN_STATE_OPEN
) {
959 control_connection_t
*control_conn
= TO_CONTROL_CONN(conn
);
961 smartlist_add(controllers
, control_conn
);
963 } SMARTLIST_FOREACH_END(conn
);
965 SMARTLIST_FOREACH_BEGIN(queued_events
, queued_event_t
*, ev
) {
966 const event_mask_t bit
= ((event_mask_t
)1) << ev
->event
;
967 const size_t msg_len
= strlen(ev
->msg
);
968 SMARTLIST_FOREACH_BEGIN(controllers
, control_connection_t
*,
970 if (control_conn
->event_mask
& bit
) {
971 connection_buf_add(ev
->msg
, msg_len
, TO_CONN(control_conn
));
973 } SMARTLIST_FOREACH_END(control_conn
);
975 queued_event_free(ev
);
976 } SMARTLIST_FOREACH_END(ev
);
979 SMARTLIST_FOREACH_BEGIN(controllers
, control_connection_t
*,
981 connection_flush(TO_CONN(control_conn
));
982 } SMARTLIST_FOREACH_END(control_conn
);
985 smartlist_free(queued_events
);
986 smartlist_free(controllers
);
988 --*block_event_queue
;
991 /** Libevent callback: Flushes pending events to controllers that are
992 * interested in them. */
994 flush_queued_events_cb(mainloop_event_t
*event
, void *arg
)
998 queued_events_flush_all(0);
1001 /** Send an event to all v1 controllers that are listening for code
1002 * <b>event</b>. The event's body is given by <b>msg</b>.
1004 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
1005 * respect to the EXTENDED_EVENTS feature. */
1006 MOCK_IMPL(STATIC
void,
1007 send_control_event_string
,(uint16_t event
,
1010 tor_assert(event
>= EVENT_MIN_
&& event
<= EVENT_MAX_
);
1011 queue_control_event_string(event
, tor_strdup(msg
));
1014 /** Helper for send_control_event and control_event_status:
1015 * Send an event to all v1 controllers that are listening for code
1016 * <b>event</b>. The event's body is created by the printf-style format in
1017 * <b>format</b>, and other arguments as provided. */
1019 send_control_event_impl(uint16_t event
,
1020 const char *format
, va_list ap
)
1025 len
= tor_vasprintf(&buf
, format
, ap
);
1027 log_warn(LD_BUG
, "Unable to format event for controller.");
1031 queue_control_event_string(event
, buf
);
1034 /** Send an event to all v1 controllers that are listening for code
1035 * <b>event</b>. The event's body is created by the printf-style format in
1036 * <b>format</b>, and other arguments as provided. */
1038 send_control_event(uint16_t event
,
1039 const char *format
, ...)
1042 va_start(ap
, format
);
1043 send_control_event_impl(event
, format
, ap
);
1047 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
1048 static origin_circuit_t
*
1049 get_circ(const char *id
)
1053 n_id
= (uint32_t) tor_parse_ulong(id
, 10, 0, UINT32_MAX
, &ok
, NULL
);
1056 return circuit_get_by_global_id(n_id
);
1059 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
1060 static entry_connection_t
*
1061 get_stream(const char *id
)
1066 n_id
= tor_parse_uint64(id
, 10, 0, UINT64_MAX
, &ok
, NULL
);
1069 conn
= connection_get_by_global_id(n_id
);
1070 if (!conn
|| conn
->type
!= CONN_TYPE_AP
|| conn
->marked_for_close
)
1072 return TO_ENTRY_CONN(conn
);
1075 /** Helper for setconf and resetconf. Acts like setconf, except
1076 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
1080 control_setconf_helper(control_connection_t
*conn
, uint32_t len
, char *body
,
1083 setopt_err_t opt_err
;
1084 config_line_t
*lines
=NULL
;
1086 char *errstring
= NULL
;
1087 const unsigned flags
=
1088 CAL_CLEAR_FIRST
| (use_defaults
? CAL_USE_DEFAULTS
: 0);
1091 smartlist_t
*entries
= smartlist_new();
1093 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
1094 * separated by space. break it into a list of configuration entries. */
1099 while (!TOR_ISSPACE(*eq
) && *eq
!= '=')
1101 key
= tor_strndup(body
, eq
-body
);
1106 if (*body
!= '\"') {
1107 char *val_start
= body
;
1108 while (!TOR_ISSPACE(*body
))
1110 val
= tor_strndup(val_start
, body
-val_start
);
1111 val_len
= strlen(val
);
1113 body
= (char*)extract_escaped_string(body
, (len
- (body
-start
)),
1116 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn
);
1117 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
1118 smartlist_free(entries
);
1123 tor_asprintf(&entry
, "%s %s", key
, val
);
1129 smartlist_add(entries
, entry
);
1130 while (TOR_ISSPACE(*body
))
1134 smartlist_add_strdup(entries
, "");
1135 config
= smartlist_join_strings(entries
, "\n", 0, NULL
);
1136 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
1137 smartlist_free(entries
);
1139 if (config_get_lines(config
, &lines
, 0) < 0) {
1140 log_warn(LD_CONTROL
,"Controller gave us config lines we can't parse.");
1141 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
1148 opt_err
= options_trial_assign(lines
, flags
, &errstring
);
1152 case SETOPT_ERR_MISC
:
1153 msg
= "552 Unrecognized option";
1155 case SETOPT_ERR_PARSE
:
1156 msg
= "513 Unacceptable option value";
1158 case SETOPT_ERR_TRANSITION
:
1159 msg
= "553 Transition not allowed";
1161 case SETOPT_ERR_SETTING
:
1163 msg
= "553 Unable to set option";
1166 config_free_lines(lines
);
1167 send_control_done(conn
);
1170 log_warn(LD_CONTROL
,
1171 "Controller gave us config lines that didn't validate: %s",
1173 connection_printf_to_buf(conn
, "%s: %s\r\n", msg
, errstring
);
1174 config_free_lines(lines
);
1175 tor_free(errstring
);
1180 /** Called when we receive a SETCONF message: parse the body and try
1181 * to update our configuration. Reply with a DONE or ERROR message.
1182 * Modifies the contents of body.*/
1184 handle_control_setconf(control_connection_t
*conn
, uint32_t len
, char *body
)
1186 return control_setconf_helper(conn
, len
, body
, 0);
1189 /** Called when we receive a RESETCONF message: parse the body and try
1190 * to update our configuration. Reply with a DONE or ERROR message.
1191 * Modifies the contents of body. */
1193 handle_control_resetconf(control_connection_t
*conn
, uint32_t len
, char *body
)
1195 return control_setconf_helper(conn
, len
, body
, 1);
1198 /** Called when we receive a GETCONF message. Parse the request, and
1199 * reply with a CONFVALUE or an ERROR message */
1201 handle_control_getconf(control_connection_t
*conn
, uint32_t body_len
,
1204 smartlist_t
*questions
= smartlist_new();
1205 smartlist_t
*answers
= smartlist_new();
1206 smartlist_t
*unrecognized
= smartlist_new();
1209 const or_options_t
*options
= get_options();
1212 (void) body_len
; /* body is NUL-terminated; so we can ignore len. */
1213 smartlist_split_string(questions
, body
, " ",
1214 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1215 SMARTLIST_FOREACH_BEGIN(questions
, const char *, q
) {
1216 if (!option_is_recognized(q
)) {
1217 smartlist_add(unrecognized
, (char*) q
);
1219 config_line_t
*answer
= option_get_assignment(options
,q
);
1221 const char *name
= option_get_canonical_name(q
);
1222 smartlist_add_asprintf(answers
, "250-%s\r\n", name
);
1226 config_line_t
*next
;
1227 smartlist_add_asprintf(answers
, "250-%s=%s\r\n",
1228 answer
->key
, answer
->value
);
1230 next
= answer
->next
;
1231 tor_free(answer
->key
);
1232 tor_free(answer
->value
);
1237 } SMARTLIST_FOREACH_END(q
);
1239 if ((len
= smartlist_len(unrecognized
))) {
1240 for (i
=0; i
< len
-1; ++i
)
1241 connection_printf_to_buf(conn
,
1242 "552-Unrecognized configuration key \"%s\"\r\n",
1243 (char*)smartlist_get(unrecognized
, i
));
1244 connection_printf_to_buf(conn
,
1245 "552 Unrecognized configuration key \"%s\"\r\n",
1246 (char*)smartlist_get(unrecognized
, len
-1));
1247 } else if ((len
= smartlist_len(answers
))) {
1248 char *tmp
= smartlist_get(answers
, len
-1);
1249 tor_assert(strlen(tmp
)>4);
1251 msg
= smartlist_join_strings(answers
, "", 0, &msg_len
);
1252 connection_buf_add(msg
, msg_len
, TO_CONN(conn
));
1254 connection_write_str_to_buf("250 OK\r\n", conn
);
1257 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
1258 smartlist_free(answers
);
1259 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
1260 smartlist_free(questions
);
1261 smartlist_free(unrecognized
);
1268 /** Called when we get a +LOADCONF message. */
1270 handle_control_loadconf(control_connection_t
*conn
, uint32_t len
,
1273 setopt_err_t retval
;
1274 char *errstring
= NULL
;
1275 const char *msg
= NULL
;
1278 retval
= options_init_from_string(NULL
, body
, CMD_RUN_TOR
, NULL
, &errstring
);
1280 if (retval
!= SETOPT_OK
)
1281 log_warn(LD_CONTROL
,
1282 "Controller gave us config file that didn't validate: %s",
1286 case SETOPT_ERR_PARSE
:
1287 msg
= "552 Invalid config file";
1289 case SETOPT_ERR_TRANSITION
:
1290 msg
= "553 Transition not allowed";
1292 case SETOPT_ERR_SETTING
:
1293 msg
= "553 Unable to set option";
1295 case SETOPT_ERR_MISC
:
1297 msg
= "550 Unable to load config";
1304 connection_printf_to_buf(conn
, "%s: %s\r\n", msg
, errstring
);
1306 connection_printf_to_buf(conn
, "%s\r\n", msg
);
1308 send_control_done(conn
);
1310 tor_free(errstring
);
1314 /** Helper structure: maps event values to their names. */
1315 struct control_event_t
{
1316 uint16_t event_code
;
1317 const char *event_name
;
1319 /** Table mapping event values to their names. Used to implement SETEVENTS
1320 * and GETINFO events/names, and to keep they in sync. */
1321 static const struct control_event_t control_event_table
[] = {
1322 { EVENT_CIRCUIT_STATUS
, "CIRC" },
1323 { EVENT_CIRCUIT_STATUS_MINOR
, "CIRC_MINOR" },
1324 { EVENT_STREAM_STATUS
, "STREAM" },
1325 { EVENT_OR_CONN_STATUS
, "ORCONN" },
1326 { EVENT_BANDWIDTH_USED
, "BW" },
1327 { EVENT_DEBUG_MSG
, "DEBUG" },
1328 { EVENT_INFO_MSG
, "INFO" },
1329 { EVENT_NOTICE_MSG
, "NOTICE" },
1330 { EVENT_WARN_MSG
, "WARN" },
1331 { EVENT_ERR_MSG
, "ERR" },
1332 { EVENT_NEW_DESC
, "NEWDESC" },
1333 { EVENT_ADDRMAP
, "ADDRMAP" },
1334 { EVENT_DESCCHANGED
, "DESCCHANGED" },
1336 { EVENT_STATUS_GENERAL
, "STATUS_GENERAL" },
1337 { EVENT_STATUS_CLIENT
, "STATUS_CLIENT" },
1338 { EVENT_STATUS_SERVER
, "STATUS_SERVER" },
1339 { EVENT_GUARD
, "GUARD" },
1340 { EVENT_STREAM_BANDWIDTH_USED
, "STREAM_BW" },
1341 { EVENT_CLIENTS_SEEN
, "CLIENTS_SEEN" },
1342 { EVENT_NEWCONSENSUS
, "NEWCONSENSUS" },
1343 { EVENT_BUILDTIMEOUT_SET
, "BUILDTIMEOUT_SET" },
1344 { EVENT_GOT_SIGNAL
, "SIGNAL" },
1345 { EVENT_CONF_CHANGED
, "CONF_CHANGED"},
1346 { EVENT_CONN_BW
, "CONN_BW" },
1347 { EVENT_CELL_STATS
, "CELL_STATS" },
1348 { EVENT_CIRC_BANDWIDTH_USED
, "CIRC_BW" },
1349 { EVENT_TRANSPORT_LAUNCHED
, "TRANSPORT_LAUNCHED" },
1350 { EVENT_HS_DESC
, "HS_DESC" },
1351 { EVENT_HS_DESC_CONTENT
, "HS_DESC_CONTENT" },
1352 { EVENT_NETWORK_LIVENESS
, "NETWORK_LIVENESS" },
1356 /** Called when we get a SETEVENTS message: update conn->event_mask,
1357 * and reply with DONE or ERROR. */
1359 handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
1363 event_mask_t event_mask
= 0;
1364 smartlist_t
*events
= smartlist_new();
1368 smartlist_split_string(events
, body
, " ",
1369 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1370 SMARTLIST_FOREACH_BEGIN(events
, const char *, ev
)
1372 if (!strcasecmp(ev
, "EXTENDED") ||
1373 !strcasecmp(ev
, "AUTHDIR_NEWDESCS")) {
1374 log_warn(LD_CONTROL
, "The \"%s\" SETEVENTS argument is no longer "
1381 for (i
= 0; control_event_table
[i
].event_name
!= NULL
; ++i
) {
1382 if (!strcasecmp(ev
, control_event_table
[i
].event_name
)) {
1383 event_code
= control_event_table
[i
].event_code
;
1388 if (event_code
== -1) {
1389 connection_printf_to_buf(conn
, "552 Unrecognized event \"%s\"\r\n",
1391 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
1392 smartlist_free(events
);
1396 event_mask
|= (((event_mask_t
)1) << event_code
);
1398 SMARTLIST_FOREACH_END(ev
);
1399 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
1400 smartlist_free(events
);
1402 conn
->event_mask
= event_mask
;
1404 control_update_global_event_mask();
1405 send_control_done(conn
);
1409 /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
1410 * Return a smartlist of acceptable passwords (unterminated strings of
1411 * length S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on
1415 decode_hashed_passwords(config_line_t
*passwords
)
1419 smartlist_t
*sl
= smartlist_new();
1421 tor_assert(passwords
);
1423 for (cl
= passwords
; cl
; cl
= cl
->next
) {
1424 const char *hashed
= cl
->value
;
1426 if (!strcmpstart(hashed
, "16:")) {
1427 if (base16_decode(decoded
, sizeof(decoded
), hashed
+3, strlen(hashed
+3))
1428 != S2K_RFC2440_SPECIFIER_LEN
+ DIGEST_LEN
1429 || strlen(hashed
+3) != (S2K_RFC2440_SPECIFIER_LEN
+DIGEST_LEN
)*2) {
1433 if (base64_decode(decoded
, sizeof(decoded
), hashed
, strlen(hashed
))
1434 != S2K_RFC2440_SPECIFIER_LEN
+DIGEST_LEN
) {
1439 tor_memdup(decoded
, S2K_RFC2440_SPECIFIER_LEN
+DIGEST_LEN
));
1445 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
1450 /** Called when we get an AUTHENTICATE message. Check whether the
1451 * authentication is valid, and if so, update the connection's state to
1452 * OPEN. Reply with DONE or ERROR.
1455 handle_control_authenticate(control_connection_t
*conn
, uint32_t len
,
1458 int used_quoted_string
= 0;
1459 const or_options_t
*options
= get_options();
1460 const char *errstr
= "Unknown error";
1462 size_t password_len
;
1465 int bad_cookie
=0, bad_password
=0;
1466 smartlist_t
*sl
= NULL
;
1469 password
= tor_strdup("");
1471 } else if (TOR_ISXDIGIT(body
[0])) {
1473 while (TOR_ISXDIGIT(*cp
))
1475 i
= (int)(cp
- body
);
1478 password
= tor_malloc(password_len
+ 1);
1479 if (base16_decode(password
, password_len
+1, body
, i
)
1480 != (int) password_len
) {
1481 connection_write_str_to_buf(
1482 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1483 "password? If so, the standard requires that you put it in "
1484 "double quotes.\r\n", conn
);
1485 connection_mark_for_close(TO_CONN(conn
));
1490 if (!decode_escaped_string(body
, len
, &password
, &password_len
)) {
1491 connection_write_str_to_buf("551 Invalid quoted string. You need "
1492 "to put the password in double quotes.\r\n", conn
);
1493 connection_mark_for_close(TO_CONN(conn
));
1496 used_quoted_string
= 1;
1499 if (conn
->safecookie_client_hash
!= NULL
) {
1500 /* The controller has chosen safe cookie authentication; the only
1501 * acceptable authentication value is the controller-to-server
1504 tor_assert(authentication_cookie_is_set
);
1506 if (password_len
!= DIGEST256_LEN
) {
1507 log_warn(LD_CONTROL
,
1508 "Got safe cookie authentication response with wrong length "
1509 "(%d)", (int)password_len
);
1510 errstr
= "Wrong length for safe cookie response.";
1514 if (tor_memneq(conn
->safecookie_client_hash
, password
, DIGEST256_LEN
)) {
1515 log_warn(LD_CONTROL
,
1516 "Got incorrect safe cookie authentication response");
1517 errstr
= "Safe cookie response did not match expected value.";
1521 tor_free(conn
->safecookie_client_hash
);
1525 if (!options
->CookieAuthentication
&& !options
->HashedControlPassword
&&
1526 !options
->HashedControlSessionPassword
) {
1527 /* if Tor doesn't demand any stronger authentication, then
1528 * the controller can get in with anything. */
1532 if (options
->CookieAuthentication
) {
1533 int also_password
= options
->HashedControlPassword
!= NULL
||
1534 options
->HashedControlSessionPassword
!= NULL
;
1535 if (password_len
!= AUTHENTICATION_COOKIE_LEN
) {
1536 if (!also_password
) {
1537 log_warn(LD_CONTROL
, "Got authentication cookie with wrong length "
1538 "(%d)", (int)password_len
);
1539 errstr
= "Wrong length on authentication cookie.";
1543 } else if (tor_memneq(authentication_cookie
, password
, password_len
)) {
1544 if (!also_password
) {
1545 log_warn(LD_CONTROL
, "Got mismatched authentication cookie");
1546 errstr
= "Authentication cookie did not match expected value.";
1555 if (options
->HashedControlPassword
||
1556 options
->HashedControlSessionPassword
) {
1558 smartlist_t
*sl_tmp
;
1559 char received
[DIGEST_LEN
];
1560 int also_cookie
= options
->CookieAuthentication
;
1561 sl
= smartlist_new();
1562 if (options
->HashedControlPassword
) {
1563 sl_tmp
= decode_hashed_passwords(options
->HashedControlPassword
);
1567 smartlist_add_all(sl
, sl_tmp
);
1568 smartlist_free(sl_tmp
);
1571 if (options
->HashedControlSessionPassword
) {
1572 sl_tmp
= decode_hashed_passwords(options
->HashedControlSessionPassword
);
1576 smartlist_add_all(sl
, sl_tmp
);
1577 smartlist_free(sl_tmp
);
1583 "Couldn't decode HashedControlPassword: invalid base16");
1584 errstr
="Couldn't decode HashedControlPassword value in configuration.";
1588 SMARTLIST_FOREACH(sl
, char *, str
, tor_free(str
));
1592 SMARTLIST_FOREACH(sl
, char *, expected
,
1594 secret_to_key_rfc2440(received
,DIGEST_LEN
,
1595 password
,password_len
,expected
);
1596 if (tor_memeq(expected
+ S2K_RFC2440_SPECIFIER_LEN
,
1597 received
, DIGEST_LEN
))
1600 SMARTLIST_FOREACH(sl
, char *, str
, tor_free(str
));
1604 if (used_quoted_string
)
1605 errstr
= "Password did not match HashedControlPassword value from "
1608 errstr
= "Password did not match HashedControlPassword value from "
1609 "configuration. Maybe you tried a plain text password? "
1610 "If so, the standard requires that you put it in double quotes.";
1617 /** We only get here if both kinds of authentication failed. */
1618 tor_assert(bad_password
&& bad_cookie
);
1619 log_warn(LD_CONTROL
, "Bad password or authentication cookie on controller.");
1620 errstr
= "Password did not match HashedControlPassword *or* authentication "
1625 connection_printf_to_buf(conn
, "515 Authentication failed: %s\r\n", errstr
);
1626 connection_mark_for_close(TO_CONN(conn
));
1627 if (sl
) { /* clean up */
1628 SMARTLIST_FOREACH(sl
, char *, str
, tor_free(str
));
1633 log_info(LD_CONTROL
, "Authenticated control connection ("TOR_SOCKET_T_FORMAT
1634 ")", conn
->base_
.s
);
1635 send_control_done(conn
);
1636 conn
->base_
.state
= CONTROL_CONN_STATE_OPEN
;
1638 if (sl
) { /* clean up */
1639 SMARTLIST_FOREACH(sl
, char *, str
, tor_free(str
));
1645 /** Called when we get a SAVECONF command. Try to flush the current options to
1646 * disk, and report success or failure. */
1648 handle_control_saveconf(control_connection_t
*conn
, uint32_t len
,
1653 int force
= !strcmpstart(body
, "FORCE");
1654 const or_options_t
*options
= get_options();
1655 if ((!force
&& options
->IncludeUsed
) || options_save_current() < 0) {
1656 connection_write_str_to_buf(
1657 "551 Unable to write configuration to disk.\r\n", conn
);
1659 send_control_done(conn
);
1666 const char *signal_name
;
1669 static const struct signal_t signal_table
[] = {
1670 { SIGHUP
, "RELOAD" },
1672 { SIGINT
, "SHUTDOWN" },
1673 { SIGUSR1
, "DUMP" },
1674 { SIGUSR1
, "USR1" },
1675 { SIGUSR2
, "DEBUG" },
1676 { SIGUSR2
, "USR2" },
1677 { SIGTERM
, "HALT" },
1678 { SIGTERM
, "TERM" },
1680 { SIGNEWNYM
, "NEWNYM" },
1681 { SIGCLEARDNSCACHE
, "CLEARDNSCACHE"},
1682 { SIGHEARTBEAT
, "HEARTBEAT"},
1686 /** Called when we get a SIGNAL command. React to the provided signal, and
1687 * report success or failure. (If the signal results in a shutdown, success
1688 * may not be reported.) */
1690 handle_control_signal(control_connection_t
*conn
, uint32_t len
,
1700 while (body
[n
] && ! TOR_ISSPACE(body
[n
]))
1702 s
= tor_strndup(body
, n
);
1704 for (i
= 0; signal_table
[i
].signal_name
!= NULL
; ++i
) {
1705 if (!strcasecmp(s
, signal_table
[i
].signal_name
)) {
1706 sig
= signal_table
[i
].sig
;
1712 connection_printf_to_buf(conn
, "552 Unrecognized signal code \"%s\"\r\n",
1718 send_control_done(conn
);
1719 /* Flush the "done" first if the signal might make us shut down. */
1720 if (sig
== SIGTERM
|| sig
== SIGINT
)
1721 connection_flush(TO_CONN(conn
));
1723 activate_signal(sig
);
1728 /** Called when we get a TAKEOWNERSHIP command. Mark this connection
1729 * as an owning connection, so that we will exit if the connection
1732 handle_control_takeownership(control_connection_t
*conn
, uint32_t len
,
1738 conn
->is_owning_control_connection
= 1;
1740 log_info(LD_CONTROL
, "Control connection %d has taken ownership of this "
1742 (int)(conn
->base_
.s
));
1744 send_control_done(conn
);
1748 /** Return true iff <b>addr</b> is unusable as a mapaddress target because of
1749 * containing funny characters. */
1751 address_is_invalid_mapaddress_target(const char *addr
)
1753 if (!strcmpstart(addr
, "*."))
1754 return address_is_invalid_destination(addr
+2, 1);
1756 return address_is_invalid_destination(addr
, 1);
1759 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1760 * and report success or failure. */
1762 handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
1770 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
1772 lines
= smartlist_new();
1773 elts
= smartlist_new();
1774 reply
= smartlist_new();
1775 smartlist_split_string(lines
, body
, " ",
1776 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1777 SMARTLIST_FOREACH_BEGIN(lines
, char *, line
) {
1779 smartlist_split_string(elts
, line
, "=", 0, 2);
1780 if (smartlist_len(elts
) == 2) {
1781 const char *from
= smartlist_get(elts
,0);
1782 const char *to
= smartlist_get(elts
,1);
1783 if (address_is_invalid_mapaddress_target(to
)) {
1784 smartlist_add_asprintf(reply
,
1785 "512-syntax error: invalid address '%s'", to
);
1786 log_warn(LD_CONTROL
,
1787 "Skipping invalid argument '%s' in MapAddress msg", to
);
1788 } else if (!strcmp(from
, ".") || !strcmp(from
, "0.0.0.0") ||
1789 !strcmp(from
, "::")) {
1791 !strcmp(from
,".") ? RESOLVED_TYPE_HOSTNAME
:
1792 (!strcmp(from
, "0.0.0.0") ? RESOLVED_TYPE_IPV4
: RESOLVED_TYPE_IPV6
);
1793 const char *address
= addressmap_register_virtual_address(
1794 type
, tor_strdup(to
));
1796 smartlist_add_asprintf(reply
,
1797 "451-resource exhausted: skipping '%s'", line
);
1798 log_warn(LD_CONTROL
,
1799 "Unable to allocate address for '%s' in MapAddress msg",
1800 safe_str_client(line
));
1802 smartlist_add_asprintf(reply
, "250-%s=%s", address
, to
);
1806 if (addressmap_register_auto(from
, to
, 1,
1807 ADDRMAPSRC_CONTROLLER
, &msg
) < 0) {
1808 smartlist_add_asprintf(reply
,
1809 "512-syntax error: invalid address mapping "
1810 " '%s': %s", line
, msg
);
1811 log_warn(LD_CONTROL
,
1812 "Skipping invalid argument '%s' in MapAddress msg: %s",
1815 smartlist_add_asprintf(reply
, "250-%s", line
);
1819 smartlist_add_asprintf(reply
, "512-syntax error: mapping '%s' is "
1820 "not of expected form 'foo=bar'.", line
);
1821 log_info(LD_CONTROL
, "Skipping MapAddress '%s': wrong "
1823 safe_str_client(line
));
1825 SMARTLIST_FOREACH(elts
, char *, cp
, tor_free(cp
));
1826 smartlist_clear(elts
);
1827 } SMARTLIST_FOREACH_END(line
);
1828 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
1829 smartlist_free(lines
);
1830 smartlist_free(elts
);
1832 if (smartlist_len(reply
)) {
1833 ((char*)smartlist_get(reply
,smartlist_len(reply
)-1))[3] = ' ';
1834 r
= smartlist_join_strings(reply
, "\r\n", 1, &sz
);
1835 connection_buf_add(r
, sz
, TO_CONN(conn
));
1838 const char *response
=
1839 "512 syntax error: not enough arguments to mapaddress.\r\n";
1840 connection_buf_add(response
, strlen(response
), TO_CONN(conn
));
1843 SMARTLIST_FOREACH(reply
, char *, cp
, tor_free(cp
));
1844 smartlist_free(reply
);
1848 /** Implementation helper for GETINFO: knows the answers for various
1849 * trivial-to-implement questions. */
1851 getinfo_helper_misc(control_connection_t
*conn
, const char *question
,
1852 char **answer
, const char **errmsg
)
1855 if (!strcmp(question
, "version")) {
1856 *answer
= tor_strdup(get_version());
1857 } else if (!strcmp(question
, "bw-event-cache")) {
1858 *answer
= get_bw_samples();
1859 } else if (!strcmp(question
, "config-file")) {
1860 const char *a
= get_torrc_fname(0);
1862 *answer
= tor_strdup(a
);
1863 } else if (!strcmp(question
, "config-defaults-file")) {
1864 const char *a
= get_torrc_fname(1);
1866 *answer
= tor_strdup(a
);
1867 } else if (!strcmp(question
, "config-text")) {
1868 *answer
= options_dump(get_options(), OPTIONS_DUMP_MINIMAL
);
1869 } else if (!strcmp(question
, "config-can-saveconf")) {
1870 *answer
= tor_strdup(get_options()->IncludeUsed
? "0" : "1");
1871 } else if (!strcmp(question
, "info/names")) {
1872 *answer
= list_getinfo_options();
1873 } else if (!strcmp(question
, "dormant")) {
1874 int dormant
= rep_hist_circbuilding_dormant(time(NULL
));
1875 *answer
= tor_strdup(dormant
? "1" : "0");
1876 } else if (!strcmp(question
, "events/names")) {
1878 smartlist_t
*event_names
= smartlist_new();
1880 for (i
= 0; control_event_table
[i
].event_name
!= NULL
; ++i
) {
1881 smartlist_add(event_names
, (char *)control_event_table
[i
].event_name
);
1884 *answer
= smartlist_join_strings(event_names
, " ", 0, NULL
);
1886 smartlist_free(event_names
);
1887 } else if (!strcmp(question
, "signal/names")) {
1888 smartlist_t
*signal_names
= smartlist_new();
1890 for (j
= 0; signal_table
[j
].signal_name
!= NULL
; ++j
) {
1891 smartlist_add(signal_names
, (char*)signal_table
[j
].signal_name
);
1894 *answer
= smartlist_join_strings(signal_names
, " ", 0, NULL
);
1896 smartlist_free(signal_names
);
1897 } else if (!strcmp(question
, "features/names")) {
1898 *answer
= tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1899 } else if (!strcmp(question
, "address")) {
1901 if (router_pick_published_address(get_options(), &addr
, 0) < 0) {
1902 *errmsg
= "Address unknown";
1905 *answer
= tor_dup_ip(addr
);
1906 } else if (!strcmp(question
, "traffic/read")) {
1907 tor_asprintf(answer
, "%"PRIu64
, (get_bytes_read()));
1908 } else if (!strcmp(question
, "traffic/written")) {
1909 tor_asprintf(answer
, "%"PRIu64
, (get_bytes_written()));
1910 } else if (!strcmp(question
, "uptime")) {
1911 long uptime_secs
= get_uptime();
1912 tor_asprintf(answer
, "%ld", uptime_secs
);
1913 } else if (!strcmp(question
, "process/pid")) {
1922 tor_asprintf(answer
, "%d", myPid
);
1923 } else if (!strcmp(question
, "process/uid")) {
1925 *answer
= tor_strdup("-1");
1927 int myUid
= geteuid();
1928 tor_asprintf(answer
, "%d", myUid
);
1929 #endif /* defined(_WIN32) */
1930 } else if (!strcmp(question
, "process/user")) {
1932 *answer
= tor_strdup("");
1934 int myUid
= geteuid();
1935 const struct passwd
*myPwEntry
= tor_getpwuid(myUid
);
1938 *answer
= tor_strdup(myPwEntry
->pw_name
);
1940 *answer
= tor_strdup("");
1942 #endif /* defined(_WIN32) */
1943 } else if (!strcmp(question
, "process/descriptor-limit")) {
1944 int max_fds
= get_max_sockets();
1945 tor_asprintf(answer
, "%d", max_fds
);
1946 } else if (!strcmp(question
, "limits/max-mem-in-queues")) {
1947 tor_asprintf(answer
, "%"PRIu64
,
1948 (get_options()->MaxMemInQueues
));
1949 } else if (!strcmp(question
, "fingerprint")) {
1950 crypto_pk_t
*server_key
;
1951 if (!server_mode(get_options())) {
1952 *errmsg
= "Not running in server mode";
1955 server_key
= get_server_identity_key();
1956 *answer
= tor_malloc(HEX_DIGEST_LEN
+1);
1957 crypto_pk_get_fingerprint(server_key
, *answer
, 0);
1962 /** Awful hack: return a newly allocated string based on a routerinfo and
1963 * (possibly) an extrainfo, sticking the read-history and write-history from
1964 * <b>ei</b> into the resulting string. The thing you get back won't
1965 * necessarily have a valid signature.
1967 * New code should never use this; it's for backward compatibility.
1969 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1970 * not be NUL-terminated. */
1972 munge_extrainfo_into_routerinfo(const char *ri_body
,
1973 const signed_descriptor_t
*ri
,
1974 const signed_descriptor_t
*ei
)
1976 char *out
= NULL
, *outp
;
1978 const char *router_sig
;
1979 const char *ei_body
= signed_descriptor_get_body(ei
);
1980 size_t ri_len
= ri
->signed_descriptor_len
;
1981 size_t ei_len
= ei
->signed_descriptor_len
;
1985 outp
= out
= tor_malloc(ri_len
+ei_len
+1);
1986 if (!(router_sig
= tor_memstr(ri_body
, ri_len
, "\nrouter-signature")))
1989 memcpy(out
, ri_body
, router_sig
-ri_body
);
1990 outp
+= router_sig
-ri_body
;
1992 for (i
=0; i
< 2; ++i
) {
1993 const char *kwd
= i
? "\nwrite-history " : "\nread-history ";
1994 const char *cp
, *eol
;
1995 if (!(cp
= tor_memstr(ei_body
, ei_len
, kwd
)))
1998 if (!(eol
= memchr(cp
, '\n', ei_len
- (cp
-ei_body
))))
2000 memcpy(outp
, cp
, eol
-cp
+1);
2003 memcpy(outp
, router_sig
, ri_len
- (router_sig
-ri_body
));
2005 tor_assert(outp
-out
< (int)(ri_len
+ei_len
+1));
2010 return tor_strndup(ri_body
, ri
->signed_descriptor_len
);
2013 /** Implementation helper for GETINFO: answers requests for information about
2014 * which ports are bound. */
2016 getinfo_helper_listeners(control_connection_t
*control_conn
,
2017 const char *question
,
2018 char **answer
, const char **errmsg
)
2026 if (!strcmp(question
, "net/listeners/or"))
2027 type
= CONN_TYPE_OR_LISTENER
;
2028 else if (!strcmp(question
, "net/listeners/extor"))
2029 type
= CONN_TYPE_EXT_OR_LISTENER
;
2030 else if (!strcmp(question
, "net/listeners/dir"))
2031 type
= CONN_TYPE_DIR_LISTENER
;
2032 else if (!strcmp(question
, "net/listeners/socks"))
2033 type
= CONN_TYPE_AP_LISTENER
;
2034 else if (!strcmp(question
, "net/listeners/trans"))
2035 type
= CONN_TYPE_AP_TRANS_LISTENER
;
2036 else if (!strcmp(question
, "net/listeners/natd"))
2037 type
= CONN_TYPE_AP_NATD_LISTENER
;
2038 else if (!strcmp(question
, "net/listeners/httptunnel"))
2039 type
= CONN_TYPE_AP_HTTP_CONNECT_LISTENER
;
2040 else if (!strcmp(question
, "net/listeners/dns"))
2041 type
= CONN_TYPE_AP_DNS_LISTENER
;
2042 else if (!strcmp(question
, "net/listeners/control"))
2043 type
= CONN_TYPE_CONTROL_LISTENER
;
2045 return 0; /* unknown key */
2047 res
= smartlist_new();
2048 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t
*, conn
) {
2049 struct sockaddr_storage ss
;
2050 socklen_t ss_len
= sizeof(ss
);
2052 if (conn
->type
!= type
|| conn
->marked_for_close
|| !SOCKET_OK(conn
->s
))
2055 if (getsockname(conn
->s
, (struct sockaddr
*)&ss
, &ss_len
) < 0) {
2056 smartlist_add_asprintf(res
, "%s:%d", conn
->address
, (int)conn
->port
);
2058 char *tmp
= tor_sockaddr_to_str((struct sockaddr
*)&ss
);
2059 smartlist_add(res
, esc_for_log(tmp
));
2063 } SMARTLIST_FOREACH_END(conn
);
2065 *answer
= smartlist_join_strings(res
, " ", 0, NULL
);
2067 SMARTLIST_FOREACH(res
, char *, cp
, tor_free(cp
));
2068 smartlist_free(res
);
2072 /** Implementation helper for GETINFO: answers requests for information about
2073 * the current time in both local and UTC forms. */
2075 getinfo_helper_current_time(control_connection_t
*control_conn
,
2076 const char *question
,
2077 char **answer
, const char **errmsg
)
2083 tor_gettimeofday(&now
);
2084 char timebuf
[ISO_TIME_LEN
+1];
2086 if (!strcmp(question
, "current-time/local"))
2087 format_local_iso_time_nospace(timebuf
, (time_t)now
.tv_sec
);
2088 else if (!strcmp(question
, "current-time/utc"))
2089 format_iso_time_nospace(timebuf
, (time_t)now
.tv_sec
);
2093 *answer
= tor_strdup(timebuf
);
2097 /** Implementation helper for GETINFO: knows the answers for questions about
2098 * directory information. */
2100 getinfo_helper_dir(control_connection_t
*control_conn
,
2101 const char *question
, char **answer
,
2102 const char **errmsg
)
2104 (void) control_conn
;
2105 if (!strcmpstart(question
, "desc/id/")) {
2106 const routerinfo_t
*ri
= NULL
;
2107 const node_t
*node
= node_get_by_hex_id(question
+strlen("desc/id/"), 0);
2111 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
2113 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
2114 } else if (! we_fetch_router_descriptors(get_options())) {
2115 /* Descriptors won't be available, provide proper error */
2116 *errmsg
= "We fetch microdescriptors, not router "
2117 "descriptors. You'll need to use md/id/* "
2118 "instead of desc/id/*.";
2121 } else if (!strcmpstart(question
, "desc/name/")) {
2122 const routerinfo_t
*ri
= NULL
;
2123 /* XXX Setting 'warn_if_unnamed' here is a bit silly -- the
2124 * warning goes to the user, not to the controller. */
2125 const node_t
*node
=
2126 node_get_by_nickname(question
+strlen("desc/name/"), 0);
2130 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
2132 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
2133 } else if (! we_fetch_router_descriptors(get_options())) {
2134 /* Descriptors won't be available, provide proper error */
2135 *errmsg
= "We fetch microdescriptors, not router "
2136 "descriptors. You'll need to use md/name/* "
2137 "instead of desc/name/*.";
2140 } else if (!strcmp(question
, "desc/download-enabled")) {
2141 int r
= we_fetch_router_descriptors(get_options());
2142 tor_asprintf(answer
, "%d", !!r
);
2143 } else if (!strcmp(question
, "desc/all-recent")) {
2144 routerlist_t
*routerlist
= router_get_routerlist();
2145 smartlist_t
*sl
= smartlist_new();
2146 if (routerlist
&& routerlist
->routers
) {
2147 SMARTLIST_FOREACH(routerlist
->routers
, const routerinfo_t
*, ri
,
2149 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
2152 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
2155 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
2156 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
2158 } else if (!strcmp(question
, "desc/all-recent-extrainfo-hack")) {
2159 /* XXXX Remove this once Torstat asks for extrainfos. */
2160 routerlist_t
*routerlist
= router_get_routerlist();
2161 smartlist_t
*sl
= smartlist_new();
2162 if (routerlist
&& routerlist
->routers
) {
2163 SMARTLIST_FOREACH_BEGIN(routerlist
->routers
, const routerinfo_t
*, ri
) {
2164 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
2165 signed_descriptor_t
*ei
= extrainfo_get_by_descriptor_digest(
2166 ri
->cache_info
.extra_info_digest
);
2168 smartlist_add(sl
, munge_extrainfo_into_routerinfo(body
,
2169 &ri
->cache_info
, ei
));
2172 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
2174 } SMARTLIST_FOREACH_END(ri
);
2176 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
2177 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
2179 } else if (!strcmpstart(question
, "hs/client/desc/id/")) {
2180 hostname_type_t addr_type
;
2182 question
+= strlen("hs/client/desc/id/");
2183 if (rend_valid_v2_service_id(question
)) {
2184 addr_type
= ONION_V2_HOSTNAME
;
2185 } else if (hs_address_is_valid(question
)) {
2186 addr_type
= ONION_V3_HOSTNAME
;
2188 *errmsg
= "Invalid address";
2192 if (addr_type
== ONION_V2_HOSTNAME
) {
2193 rend_cache_entry_t
*e
= NULL
;
2194 if (!rend_cache_lookup_entry(question
, -1, &e
)) {
2195 /* Descriptor found in cache */
2196 *answer
= tor_strdup(e
->desc
);
2198 *errmsg
= "Not found in cache";
2202 ed25519_public_key_t service_pk
;
2205 /* The check before this if/else makes sure of this. */
2206 tor_assert(addr_type
== ONION_V3_HOSTNAME
);
2208 if (hs_parse_address(question
, &service_pk
, NULL
, NULL
) < 0) {
2209 *errmsg
= "Invalid v3 address";
2213 desc
= hs_cache_lookup_encoded_as_client(&service_pk
);
2215 *answer
= tor_strdup(desc
);
2217 *errmsg
= "Not found in cache";
2221 } else if (!strcmpstart(question
, "hs/service/desc/id/")) {
2222 hostname_type_t addr_type
;
2224 question
+= strlen("hs/service/desc/id/");
2225 if (rend_valid_v2_service_id(question
)) {
2226 addr_type
= ONION_V2_HOSTNAME
;
2227 } else if (hs_address_is_valid(question
)) {
2228 addr_type
= ONION_V3_HOSTNAME
;
2230 *errmsg
= "Invalid address";
2233 rend_cache_entry_t
*e
= NULL
;
2235 if (addr_type
== ONION_V2_HOSTNAME
) {
2236 if (!rend_cache_lookup_v2_desc_as_service(question
, &e
)) {
2237 /* Descriptor found in cache */
2238 *answer
= tor_strdup(e
->desc
);
2240 *errmsg
= "Not found in cache";
2244 ed25519_public_key_t service_pk
;
2247 /* The check before this if/else makes sure of this. */
2248 tor_assert(addr_type
== ONION_V3_HOSTNAME
);
2250 if (hs_parse_address(question
, &service_pk
, NULL
, NULL
) < 0) {
2251 *errmsg
= "Invalid v3 address";
2255 desc
= hs_service_lookup_current_desc(&service_pk
);
2257 /* Newly allocated string, we have ownership. */
2260 *errmsg
= "Not found in cache";
2264 } else if (!strcmp(question
, "md/all")) {
2265 const smartlist_t
*nodes
= nodelist_get_list();
2268 if (smartlist_len(nodes
) == 0) {
2269 *answer
= tor_strdup("");
2273 smartlist_t
*microdescs
= smartlist_new();
2275 SMARTLIST_FOREACH_BEGIN(nodes
, node_t
*, n
) {
2276 if (n
->md
&& n
->md
->body
) {
2277 char *copy
= tor_strndup(n
->md
->body
, n
->md
->bodylen
);
2278 smartlist_add(microdescs
, copy
);
2280 } SMARTLIST_FOREACH_END(n
);
2282 *answer
= smartlist_join_strings(microdescs
, "", 0, NULL
);
2283 SMARTLIST_FOREACH(microdescs
, char *, md
, tor_free(md
));
2284 smartlist_free(microdescs
);
2285 } else if (!strcmpstart(question
, "md/id/")) {
2286 const node_t
*node
= node_get_by_hex_id(question
+strlen("md/id/"), 0);
2287 const microdesc_t
*md
= NULL
;
2288 if (node
) md
= node
->md
;
2289 if (md
&& md
->body
) {
2290 *answer
= tor_strndup(md
->body
, md
->bodylen
);
2292 } else if (!strcmpstart(question
, "md/name/")) {
2293 /* XXX Setting 'warn_if_unnamed' here is a bit silly -- the
2294 * warning goes to the user, not to the controller. */
2295 const node_t
*node
= node_get_by_nickname(question
+strlen("md/name/"), 0);
2296 /* XXXX duplicated code */
2297 const microdesc_t
*md
= NULL
;
2298 if (node
) md
= node
->md
;
2299 if (md
&& md
->body
) {
2300 *answer
= tor_strndup(md
->body
, md
->bodylen
);
2302 } else if (!strcmp(question
, "md/download-enabled")) {
2303 int r
= we_fetch_microdescriptors(get_options());
2304 tor_asprintf(answer
, "%d", !!r
);
2305 } else if (!strcmpstart(question
, "desc-annotations/id/")) {
2306 const routerinfo_t
*ri
= NULL
;
2307 const node_t
*node
=
2308 node_get_by_hex_id(question
+strlen("desc-annotations/id/"), 0);
2312 const char *annotations
=
2313 signed_descriptor_get_annotations(&ri
->cache_info
);
2315 *answer
= tor_strndup(annotations
,
2316 ri
->cache_info
.annotations_len
);
2318 } else if (!strcmpstart(question
, "dir/server/")) {
2319 size_t answer_len
= 0;
2321 smartlist_t
*descs
= smartlist_new();
2325 tor_asprintf(&url
, "/tor/%s", question
+4);
2326 res
= dirserv_get_routerdescs(descs
, url
, &msg
);
2328 log_warn(LD_CONTROL
, "getinfo '%s': %s", question
, msg
);
2329 smartlist_free(descs
);
2334 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
2335 answer_len
+= sd
->signed_descriptor_len
);
2336 cp
= *answer
= tor_malloc(answer_len
+1);
2337 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
2339 memcpy(cp
, signed_descriptor_get_body(sd
),
2340 sd
->signed_descriptor_len
);
2341 cp
+= sd
->signed_descriptor_len
;
2345 smartlist_free(descs
);
2346 } else if (!strcmpstart(question
, "dir/status/")) {
2347 *answer
= tor_strdup("");
2348 } else if (!strcmp(question
, "dir/status-vote/current/consensus")) { /* v3 */
2349 if (we_want_to_fetch_flavor(get_options(), FLAV_NS
)) {
2350 const cached_dir_t
*consensus
= dirserv_get_consensus("ns");
2352 *answer
= tor_strdup(consensus
->dir
);
2354 if (!*answer
) { /* try loading it from disk */
2355 *answer
= networkstatus_read_cached_consensus("ns");
2356 if (!*answer
) { /* generate an error */
2357 *errmsg
= "Could not open cached consensus. "
2358 "Make sure FetchUselessDescriptors is set to 1.";
2362 } else if (!strcmp(question
, "network-status")) { /* v1 */
2363 static int network_status_warned
= 0;
2364 if (!network_status_warned
) {
2365 log_warn(LD_CONTROL
, "GETINFO network-status is deprecated; it will "
2366 "go away in a future version of Tor.");
2367 network_status_warned
= 1;
2369 routerlist_t
*routerlist
= router_get_routerlist();
2370 if (!routerlist
|| !routerlist
->routers
||
2371 list_server_status_v1(routerlist
->routers
, answer
, 1) < 0) {
2374 } else if (!strcmpstart(question
, "extra-info/digest/")) {
2375 question
+= strlen("extra-info/digest/");
2376 if (strlen(question
) == HEX_DIGEST_LEN
) {
2378 signed_descriptor_t
*sd
= NULL
;
2379 if (base16_decode(d
, sizeof(d
), question
, strlen(question
))
2381 /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
2382 * but I don't want to risk affecting other parts of the code,
2383 * especially since the rules for using our own extrainfo (including
2384 * when it might be freed) are different from those for using one
2385 * we have downloaded. */
2386 if (router_extrainfo_digest_is_me(d
))
2387 sd
= &(router_get_my_extrainfo()->cache_info
);
2389 sd
= extrainfo_get_by_descriptor_digest(d
);
2392 const char *body
= signed_descriptor_get_body(sd
);
2394 *answer
= tor_strndup(body
, sd
->signed_descriptor_len
);
2402 /** Given a smartlist of 20-byte digests, return a newly allocated string
2403 * containing each of those digests in order, formatted in HEX, and terminated
2404 * with a newline. */
2406 digest_list_to_string(const smartlist_t
*sl
)
2411 /* Allow for newlines, and a \0 at the end */
2412 len
= smartlist_len(sl
) * (HEX_DIGEST_LEN
+ 1) + 1;
2413 result
= tor_malloc_zero(len
);
2416 SMARTLIST_FOREACH_BEGIN(sl
, const char *, digest
) {
2417 base16_encode(s
, HEX_DIGEST_LEN
+ 1, digest
, DIGEST_LEN
);
2418 s
[HEX_DIGEST_LEN
] = '\n';
2419 s
+= HEX_DIGEST_LEN
+ 1;
2420 } SMARTLIST_FOREACH_END(digest
);
2426 /** Turn a download_status_t into a human-readable description in a newly
2427 * allocated string. The format is specified in control-spec.txt, under
2428 * the documentation for "GETINFO download/..." . */
2430 download_status_to_string(const download_status_t
*dl
)
2433 char tbuf
[ISO_TIME_LEN
+1];
2434 const char *schedule_str
, *want_authority_str
;
2435 const char *increment_on_str
, *backoff_str
;
2438 /* Get some substrings of the eventual output ready */
2439 format_iso_time(tbuf
, download_status_get_next_attempt_at(dl
));
2441 switch (dl
->schedule
) {
2442 case DL_SCHED_GENERIC
:
2443 schedule_str
= "DL_SCHED_GENERIC";
2445 case DL_SCHED_CONSENSUS
:
2446 schedule_str
= "DL_SCHED_CONSENSUS";
2448 case DL_SCHED_BRIDGE
:
2449 schedule_str
= "DL_SCHED_BRIDGE";
2452 schedule_str
= "unknown";
2456 switch (dl
->want_authority
) {
2457 case DL_WANT_ANY_DIRSERVER
:
2458 want_authority_str
= "DL_WANT_ANY_DIRSERVER";
2460 case DL_WANT_AUTHORITY
:
2461 want_authority_str
= "DL_WANT_AUTHORITY";
2464 want_authority_str
= "unknown";
2468 switch (dl
->increment_on
) {
2469 case DL_SCHED_INCREMENT_FAILURE
:
2470 increment_on_str
= "DL_SCHED_INCREMENT_FAILURE";
2472 case DL_SCHED_INCREMENT_ATTEMPT
:
2473 increment_on_str
= "DL_SCHED_INCREMENT_ATTEMPT";
2476 increment_on_str
= "unknown";
2480 backoff_str
= "DL_SCHED_RANDOM_EXPONENTIAL";
2482 /* Now assemble them */
2484 "next-attempt-at %s\n"
2485 "n-download-failures %u\n"
2486 "n-download-attempts %u\n"
2488 "want-authority %s\n"
2491 "last-backoff-position %u\n"
2492 "last-delay-used %d\n",
2494 dl
->n_download_failures
,
2495 dl
->n_download_attempts
,
2500 dl
->last_backoff_position
,
2501 dl
->last_delay_used
);
2507 /** Handle the consensus download cases for getinfo_helper_downloads() */
2509 getinfo_helper_downloads_networkstatus(const char *flavor
,
2510 download_status_t
**dl_to_emit
,
2511 const char **errmsg
)
2514 * We get the one for the current bootstrapped status by default, or
2515 * take an extra /bootstrap or /running suffix
2517 if (strcmp(flavor
, "ns") == 0) {
2518 *dl_to_emit
= networkstatus_get_dl_status_by_flavor(FLAV_NS
);
2519 } else if (strcmp(flavor
, "ns/bootstrap") == 0) {
2520 *dl_to_emit
= networkstatus_get_dl_status_by_flavor_bootstrap(FLAV_NS
);
2521 } else if (strcmp(flavor
, "ns/running") == 0 ) {
2522 *dl_to_emit
= networkstatus_get_dl_status_by_flavor_running(FLAV_NS
);
2523 } else if (strcmp(flavor
, "microdesc") == 0) {
2524 *dl_to_emit
= networkstatus_get_dl_status_by_flavor(FLAV_MICRODESC
);
2525 } else if (strcmp(flavor
, "microdesc/bootstrap") == 0) {
2527 networkstatus_get_dl_status_by_flavor_bootstrap(FLAV_MICRODESC
);
2528 } else if (strcmp(flavor
, "microdesc/running") == 0) {
2530 networkstatus_get_dl_status_by_flavor_running(FLAV_MICRODESC
);
2532 *errmsg
= "Unknown flavor";
2536 /** Handle the cert download cases for getinfo_helper_downloads() */
2538 getinfo_helper_downloads_cert(const char *fp_sk_req
,
2539 download_status_t
**dl_to_emit
,
2540 smartlist_t
**digest_list
,
2541 const char **errmsg
)
2544 char id_digest
[DIGEST_LEN
];
2545 char sk_digest
[DIGEST_LEN
];
2548 * We have to handle four cases; fp_sk_req is the request with
2549 * a prefix of "downloads/cert/" snipped off.
2551 * Case 1: fp_sk_req = "fps"
2552 * - We should emit a digest_list with a list of all the identity
2553 * fingerprints that can be queried for certificate download status;
2554 * get it by calling list_authority_ids_with_downloads().
2556 * Case 2: fp_sk_req = "fp/<fp>" for some fingerprint fp
2557 * - We want the default certificate for this identity fingerprint's
2558 * download status; this is the download we get from URLs starting
2559 * in /fp/ on the directory server. We can get it with
2560 * id_only_download_status_for_authority_id().
2562 * Case 3: fp_sk_req = "fp/<fp>/sks" for some fingerprint fp
2563 * - We want a list of all signing key digests for this identity
2564 * fingerprint which can be queried for certificate download status.
2565 * Get it with list_sk_digests_for_authority_id().
2567 * Case 4: fp_sk_req = "fp/<fp>/<sk>" for some fingerprint fp and
2568 * signing key digest sk
2569 * - We want the download status for the certificate for this specific
2570 * signing key and fingerprint. These correspond to the ones we get
2571 * from URLs starting in /fp-sk/ on the directory server. Get it with
2572 * list_sk_digests_for_authority_id().
2575 if (strcmp(fp_sk_req
, "fps") == 0) {
2576 *digest_list
= list_authority_ids_with_downloads();
2577 if (!(*digest_list
)) {
2578 *errmsg
= "Failed to get list of authority identity digests (!)";
2580 } else if (!strcmpstart(fp_sk_req
, "fp/")) {
2581 fp_sk_req
+= strlen("fp/");
2582 /* Okay, look for another / to tell the fp from fp-sk cases */
2583 sk_req
= strchr(fp_sk_req
, '/');
2585 /* okay, split it here and try to parse <fp> */
2586 if (base16_decode(id_digest
, DIGEST_LEN
,
2587 fp_sk_req
, sk_req
- fp_sk_req
) == DIGEST_LEN
) {
2588 /* Skip past the '/' */
2590 if (strcmp(sk_req
, "sks") == 0) {
2591 /* We're asking for the list of signing key fingerprints */
2592 *digest_list
= list_sk_digests_for_authority_id(id_digest
);
2593 if (!(*digest_list
)) {
2594 *errmsg
= "Failed to get list of signing key digests for this "
2595 "authority identity digest";
2598 /* We've got a signing key digest */
2599 if (base16_decode(sk_digest
, DIGEST_LEN
,
2600 sk_req
, strlen(sk_req
)) == DIGEST_LEN
) {
2602 download_status_for_authority_id_and_sk(id_digest
, sk_digest
);
2603 if (!(*dl_to_emit
)) {
2604 *errmsg
= "Failed to get download status for this identity/"
2605 "signing key digest pair";
2608 *errmsg
= "That didn't look like a signing key digest";
2612 *errmsg
= "That didn't look like an identity digest";
2615 /* We're either in downloads/certs/fp/<fp>, or we can't parse <fp> */
2616 if (strlen(fp_sk_req
) == HEX_DIGEST_LEN
) {
2617 if (base16_decode(id_digest
, DIGEST_LEN
,
2618 fp_sk_req
, strlen(fp_sk_req
)) == DIGEST_LEN
) {
2619 *dl_to_emit
= id_only_download_status_for_authority_id(id_digest
);
2620 if (!(*dl_to_emit
)) {
2621 *errmsg
= "Failed to get download status for this authority "
2625 *errmsg
= "That didn't look like a digest";
2628 *errmsg
= "That didn't look like a digest";
2632 *errmsg
= "Unknown certificate download status query";
2636 /** Handle the routerdesc download cases for getinfo_helper_downloads() */
2638 getinfo_helper_downloads_desc(const char *desc_req
,
2639 download_status_t
**dl_to_emit
,
2640 smartlist_t
**digest_list
,
2641 const char **errmsg
)
2643 char desc_digest
[DIGEST_LEN
];
2645 * Two cases to handle here:
2647 * Case 1: desc_req = "descs"
2648 * - Emit a list of all router descriptor digests, which we get by
2649 * calling router_get_descriptor_digests(); this can return NULL
2650 * if we have no current ns-flavor consensus.
2652 * Case 2: desc_req = <fp>
2653 * - Check on the specified fingerprint and emit its download_status_t
2654 * using router_get_dl_status_by_descriptor_digest().
2657 if (strcmp(desc_req
, "descs") == 0) {
2658 *digest_list
= router_get_descriptor_digests();
2659 if (!(*digest_list
)) {
2660 *errmsg
= "We don't seem to have a networkstatus-flavored consensus";
2663 * Microdescs don't use the download_status_t mechanism, so we don't
2664 * answer queries about their downloads here; see microdesc.c.
2666 } else if (strlen(desc_req
) == HEX_DIGEST_LEN
) {
2667 if (base16_decode(desc_digest
, DIGEST_LEN
,
2668 desc_req
, strlen(desc_req
)) == DIGEST_LEN
) {
2669 /* Okay we got a digest-shaped thing; try asking for it */
2670 *dl_to_emit
= router_get_dl_status_by_descriptor_digest(desc_digest
);
2671 if (!(*dl_to_emit
)) {
2672 *errmsg
= "No such descriptor digest found";
2675 *errmsg
= "That didn't look like a digest";
2678 *errmsg
= "Unknown router descriptor download status query";
2682 /** Handle the bridge download cases for getinfo_helper_downloads() */
2684 getinfo_helper_downloads_bridge(const char *bridge_req
,
2685 download_status_t
**dl_to_emit
,
2686 smartlist_t
**digest_list
,
2687 const char **errmsg
)
2689 char bridge_digest
[DIGEST_LEN
];
2691 * Two cases to handle here:
2693 * Case 1: bridge_req = "bridges"
2694 * - Emit a list of all bridge identity digests, which we get by
2695 * calling list_bridge_identities(); this can return NULL if we are
2696 * not using bridges.
2698 * Case 2: bridge_req = <fp>
2699 * - Check on the specified fingerprint and emit its download_status_t
2700 * using get_bridge_dl_status_by_id().
2703 if (strcmp(bridge_req
, "bridges") == 0) {
2704 *digest_list
= list_bridge_identities();
2705 if (!(*digest_list
)) {
2706 *errmsg
= "We don't seem to be using bridges";
2708 } else if (strlen(bridge_req
) == HEX_DIGEST_LEN
) {
2709 if (base16_decode(bridge_digest
, DIGEST_LEN
,
2710 bridge_req
, strlen(bridge_req
)) == DIGEST_LEN
) {
2711 /* Okay we got a digest-shaped thing; try asking for it */
2712 *dl_to_emit
= get_bridge_dl_status_by_id(bridge_digest
);
2713 if (!(*dl_to_emit
)) {
2714 *errmsg
= "No such bridge identity digest found";
2717 *errmsg
= "That didn't look like a digest";
2720 *errmsg
= "Unknown bridge descriptor download status query";
2724 /** Implementation helper for GETINFO: knows the answers for questions about
2725 * download status information. */
2727 getinfo_helper_downloads(control_connection_t
*control_conn
,
2728 const char *question
, char **answer
,
2729 const char **errmsg
)
2731 download_status_t
*dl_to_emit
= NULL
;
2732 smartlist_t
*digest_list
= NULL
;
2734 /* Assert args are sane */
2735 tor_assert(control_conn
!= NULL
);
2736 tor_assert(question
!= NULL
);
2737 tor_assert(answer
!= NULL
);
2738 tor_assert(errmsg
!= NULL
);
2740 /* We check for this later to see if we should supply a default */
2743 /* Are we after networkstatus downloads? */
2744 if (!strcmpstart(question
, "downloads/networkstatus/")) {
2745 getinfo_helper_downloads_networkstatus(
2746 question
+ strlen("downloads/networkstatus/"),
2747 &dl_to_emit
, errmsg
);
2749 } else if (!strcmpstart(question
, "downloads/cert/")) {
2750 getinfo_helper_downloads_cert(
2751 question
+ strlen("downloads/cert/"),
2752 &dl_to_emit
, &digest_list
, errmsg
);
2753 /* Router descriptors? */
2754 } else if (!strcmpstart(question
, "downloads/desc/")) {
2755 getinfo_helper_downloads_desc(
2756 question
+ strlen("downloads/desc/"),
2757 &dl_to_emit
, &digest_list
, errmsg
);
2758 /* Bridge descriptors? */
2759 } else if (!strcmpstart(question
, "downloads/bridge/")) {
2760 getinfo_helper_downloads_bridge(
2761 question
+ strlen("downloads/bridge/"),
2762 &dl_to_emit
, &digest_list
, errmsg
);
2764 *errmsg
= "Unknown download status query";
2768 *answer
= download_status_to_string(dl_to_emit
);
2771 } else if (digest_list
) {
2772 *answer
= digest_list_to_string(digest_list
);
2773 SMARTLIST_FOREACH(digest_list
, void *, s
, tor_free(s
));
2774 smartlist_free(digest_list
);
2779 *errmsg
= "Unknown error";
2786 /** Allocate and return a description of <b>circ</b>'s current status,
2787 * including its path (if any). */
2789 circuit_describe_status_for_controller(origin_circuit_t
*circ
)
2792 smartlist_t
*descparts
= smartlist_new();
2795 char *vpath
= circuit_list_path_for_controller(circ
);
2797 smartlist_add(descparts
, vpath
);
2799 tor_free(vpath
); /* empty path; don't put an extra space in the result */
2804 cpath_build_state_t
*build_state
= circ
->build_state
;
2805 smartlist_t
*flaglist
= smartlist_new();
2806 char *flaglist_joined
;
2808 if (build_state
->onehop_tunnel
)
2809 smartlist_add(flaglist
, (void *)"ONEHOP_TUNNEL");
2810 if (build_state
->is_internal
)
2811 smartlist_add(flaglist
, (void *)"IS_INTERNAL");
2812 if (build_state
->need_capacity
)
2813 smartlist_add(flaglist
, (void *)"NEED_CAPACITY");
2814 if (build_state
->need_uptime
)
2815 smartlist_add(flaglist
, (void *)"NEED_UPTIME");
2817 /* Only emit a BUILD_FLAGS argument if it will have a non-empty value. */
2818 if (smartlist_len(flaglist
)) {
2819 flaglist_joined
= smartlist_join_strings(flaglist
, ",", 0, NULL
);
2821 smartlist_add_asprintf(descparts
, "BUILD_FLAGS=%s", flaglist_joined
);
2823 tor_free(flaglist_joined
);
2826 smartlist_free(flaglist
);
2829 smartlist_add_asprintf(descparts
, "PURPOSE=%s",
2830 circuit_purpose_to_controller_string(circ
->base_
.purpose
));
2833 const char *hs_state
=
2834 circuit_purpose_to_controller_hs_state_string(circ
->base_
.purpose
);
2836 if (hs_state
!= NULL
) {
2837 smartlist_add_asprintf(descparts
, "HS_STATE=%s", hs_state
);
2841 if (circ
->rend_data
!= NULL
|| circ
->hs_ident
!= NULL
) {
2842 char addr
[HS_SERVICE_ADDR_LEN_BASE32
+ 1];
2843 const char *onion_address
;
2844 if (circ
->rend_data
) {
2845 onion_address
= rend_data_get_address(circ
->rend_data
);
2847 hs_build_address(&circ
->hs_ident
->identity_pk
, HS_VERSION_THREE
, addr
);
2848 onion_address
= addr
;
2850 smartlist_add_asprintf(descparts
, "REND_QUERY=%s", onion_address
);
2854 char tbuf
[ISO_TIME_USEC_LEN
+1];
2855 format_iso_time_nospace_usec(tbuf
, &circ
->base_
.timestamp_created
);
2857 smartlist_add_asprintf(descparts
, "TIME_CREATED=%s", tbuf
);
2860 // Show username and/or password if available.
2861 if (circ
->socks_username_len
> 0) {
2862 char* socks_username_escaped
= esc_for_log_len(circ
->socks_username
,
2863 (size_t) circ
->socks_username_len
);
2864 smartlist_add_asprintf(descparts
, "SOCKS_USERNAME=%s",
2865 socks_username_escaped
);
2866 tor_free(socks_username_escaped
);
2868 if (circ
->socks_password_len
> 0) {
2869 char* socks_password_escaped
= esc_for_log_len(circ
->socks_password
,
2870 (size_t) circ
->socks_password_len
);
2871 smartlist_add_asprintf(descparts
, "SOCKS_PASSWORD=%s",
2872 socks_password_escaped
);
2873 tor_free(socks_password_escaped
);
2876 rv
= smartlist_join_strings(descparts
, " ", 0, NULL
);
2878 SMARTLIST_FOREACH(descparts
, char *, cp
, tor_free(cp
));
2879 smartlist_free(descparts
);
2884 /** Implementation helper for GETINFO: knows how to generate summaries of the
2885 * current states of things we send events about. */
2887 getinfo_helper_events(control_connection_t
*control_conn
,
2888 const char *question
, char **answer
,
2889 const char **errmsg
)
2891 const or_options_t
*options
= get_options();
2892 (void) control_conn
;
2893 if (!strcmp(question
, "circuit-status")) {
2894 smartlist_t
*status
= smartlist_new();
2895 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t
*, circ_
) {
2896 origin_circuit_t
*circ
;
2899 if (! CIRCUIT_IS_ORIGIN(circ_
) || circ_
->marked_for_close
)
2901 circ
= TO_ORIGIN_CIRCUIT(circ_
);
2903 if (circ
->base_
.state
== CIRCUIT_STATE_OPEN
)
2905 else if (circ
->base_
.state
== CIRCUIT_STATE_GUARD_WAIT
)
2906 state
= "GUARD_WAIT";
2907 else if (circ
->cpath
)
2912 circdesc
= circuit_describe_status_for_controller(circ
);
2914 smartlist_add_asprintf(status
, "%lu %s%s%s",
2915 (unsigned long)circ
->global_identifier
,
2916 state
, *circdesc
? " " : "", circdesc
);
2919 SMARTLIST_FOREACH_END(circ_
);
2920 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
2921 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
2922 smartlist_free(status
);
2923 } else if (!strcmp(question
, "stream-status")) {
2924 smartlist_t
*conns
= get_connection_array();
2925 smartlist_t
*status
= smartlist_new();
2927 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
2929 entry_connection_t
*conn
;
2931 origin_circuit_t
*origin_circ
= NULL
;
2932 if (base_conn
->type
!= CONN_TYPE_AP
||
2933 base_conn
->marked_for_close
||
2934 base_conn
->state
== AP_CONN_STATE_SOCKS_WAIT
||
2935 base_conn
->state
== AP_CONN_STATE_NATD_WAIT
)
2937 conn
= TO_ENTRY_CONN(base_conn
);
2938 switch (base_conn
->state
)
2940 case AP_CONN_STATE_CONTROLLER_WAIT
:
2941 case AP_CONN_STATE_CIRCUIT_WAIT
:
2942 if (conn
->socks_request
&&
2943 SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
))
2944 state
= "NEWRESOLVE";
2948 case AP_CONN_STATE_RENDDESC_WAIT
:
2949 case AP_CONN_STATE_CONNECT_WAIT
:
2950 state
= "SENTCONNECT"; break;
2951 case AP_CONN_STATE_RESOLVE_WAIT
:
2952 state
= "SENTRESOLVE"; break;
2953 case AP_CONN_STATE_OPEN
:
2954 state
= "SUCCEEDED"; break;
2956 log_warn(LD_BUG
, "Asked for stream in unknown state %d",
2960 circ
= circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn
));
2961 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
2962 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
2963 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
2964 smartlist_add_asprintf(status
, "%lu %s %lu %s",
2965 (unsigned long) base_conn
->global_identifier
,state
,
2967 (unsigned long)origin_circ
->global_identifier
: 0ul,
2969 } SMARTLIST_FOREACH_END(base_conn
);
2970 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
2971 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
2972 smartlist_free(status
);
2973 } else if (!strcmp(question
, "orconn-status")) {
2974 smartlist_t
*conns
= get_connection_array();
2975 smartlist_t
*status
= smartlist_new();
2976 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
2979 or_connection_t
*conn
;
2980 if (base_conn
->type
!= CONN_TYPE_OR
|| base_conn
->marked_for_close
)
2982 conn
= TO_OR_CONN(base_conn
);
2983 if (conn
->base_
.state
== OR_CONN_STATE_OPEN
)
2984 state
= "CONNECTED";
2985 else if (conn
->nickname
)
2989 orconn_target_get_name(name
, sizeof(name
), conn
);
2990 smartlist_add_asprintf(status
, "%s %s", name
, state
);
2991 } SMARTLIST_FOREACH_END(base_conn
);
2992 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
2993 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
2994 smartlist_free(status
);
2995 } else if (!strcmpstart(question
, "address-mappings/")) {
2996 time_t min_e
, max_e
;
2997 smartlist_t
*mappings
;
2998 question
+= strlen("address-mappings/");
2999 if (!strcmp(question
, "all")) {
3000 min_e
= 0; max_e
= TIME_MAX
;
3001 } else if (!strcmp(question
, "cache")) {
3002 min_e
= 2; max_e
= TIME_MAX
;
3003 } else if (!strcmp(question
, "config")) {
3004 min_e
= 0; max_e
= 0;
3005 } else if (!strcmp(question
, "control")) {
3006 min_e
= 1; max_e
= 1;
3010 mappings
= smartlist_new();
3011 addressmap_get_mappings(mappings
, min_e
, max_e
, 1);
3012 *answer
= smartlist_join_strings(mappings
, "\r\n", 0, NULL
);
3013 SMARTLIST_FOREACH(mappings
, char *, cp
, tor_free(cp
));
3014 smartlist_free(mappings
);
3015 } else if (!strcmpstart(question
, "status/")) {
3016 /* Note that status/ is not a catch-all for events; there's only supposed
3017 * to be a status GETINFO if there's a corresponding STATUS event. */
3018 if (!strcmp(question
, "status/circuit-established")) {
3019 *answer
= tor_strdup(have_completed_a_circuit() ? "1" : "0");
3020 } else if (!strcmp(question
, "status/enough-dir-info")) {
3021 *answer
= tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
3022 } else if (!strcmp(question
, "status/good-server-descriptor") ||
3023 !strcmp(question
, "status/accepted-server-descriptor")) {
3024 /* They're equivalent for now, until we can figure out how to make
3025 * good-server-descriptor be what we want. See comment in
3026 * control-spec.txt. */
3027 *answer
= tor_strdup(directories_have_accepted_server_descriptor()
3029 } else if (!strcmp(question
, "status/reachability-succeeded/or")) {
3030 *answer
= tor_strdup(check_whether_orport_reachable(options
) ?
3032 } else if (!strcmp(question
, "status/reachability-succeeded/dir")) {
3033 *answer
= tor_strdup(check_whether_dirport_reachable(options
) ?
3035 } else if (!strcmp(question
, "status/reachability-succeeded")) {
3036 tor_asprintf(answer
, "OR=%d DIR=%d",
3037 check_whether_orport_reachable(options
) ? 1 : 0,
3038 check_whether_dirport_reachable(options
) ? 1 : 0);
3039 } else if (!strcmp(question
, "status/bootstrap-phase")) {
3040 *answer
= tor_strdup(last_sent_bootstrap_message
);
3041 } else if (!strcmpstart(question
, "status/version/")) {
3042 int is_server
= server_mode(options
);
3043 networkstatus_t
*c
= networkstatus_get_latest_consensus();
3044 version_status_t status
;
3045 const char *recommended
;
3047 recommended
= is_server
? c
->server_versions
: c
->client_versions
;
3048 status
= tor_version_is_obsolete(VERSION
, recommended
);
3051 status
= VS_UNKNOWN
;
3054 if (!strcmp(question
, "status/version/recommended")) {
3055 *answer
= tor_strdup(recommended
);
3058 if (!strcmp(question
, "status/version/current")) {
3061 case VS_RECOMMENDED
: *answer
= tor_strdup("recommended"); break;
3062 case VS_OLD
: *answer
= tor_strdup("obsolete"); break;
3063 case VS_NEW
: *answer
= tor_strdup("new"); break;
3064 case VS_NEW_IN_SERIES
: *answer
= tor_strdup("new in series"); break;
3065 case VS_UNRECOMMENDED
: *answer
= tor_strdup("unrecommended"); break;
3066 case VS_EMPTY
: *answer
= tor_strdup("none recommended"); break;
3067 case VS_UNKNOWN
: *answer
= tor_strdup("unknown"); break;
3068 default: tor_fragile_assert();
3070 } else if (!strcmp(question
, "status/version/num-versioning") ||
3071 !strcmp(question
, "status/version/num-concurring")) {
3072 tor_asprintf(answer
, "%d", get_n_authorities(V3_DIRINFO
));
3073 log_warn(LD_GENERAL
, "%s is deprecated; it no longer gives useful "
3074 "information", question
);
3076 } else if (!strcmp(question
, "status/clients-seen")) {
3077 char *bridge_stats
= geoip_get_bridge_stats_controller(time(NULL
));
3078 if (!bridge_stats
) {
3079 *errmsg
= "No bridge-client stats available";
3082 *answer
= bridge_stats
;
3083 } else if (!strcmp(question
, "status/fresh-relay-descs")) {
3084 if (!server_mode(options
)) {
3085 *errmsg
= "Only relays have descriptors";
3090 if (router_build_fresh_descriptor(&r
, &e
) < 0) {
3091 *errmsg
= "Error generating descriptor";
3094 size_t size
= r
->cache_info
.signed_descriptor_len
+ 1;
3096 size
+= e
->cache_info
.signed_descriptor_len
+ 1;
3098 tor_assert(r
->cache_info
.signed_descriptor_len
);
3099 char *descs
= tor_malloc(size
);
3101 memcpy(cp
, signed_descriptor_get_body(&r
->cache_info
),
3102 r
->cache_info
.signed_descriptor_len
);
3103 cp
+= r
->cache_info
.signed_descriptor_len
- 1;
3105 if (cp
[0] == '\0') {
3107 } else if (cp
[0] != '\n') {
3111 memcpy(cp
, signed_descriptor_get_body(&e
->cache_info
),
3112 e
->cache_info
.signed_descriptor_len
);
3113 cp
+= e
->cache_info
.signed_descriptor_len
- 1;
3115 if (cp
[0] == '\n') {
3117 } else if (cp
[0] != '\0') {
3130 /** Implementation helper for GETINFO: knows how to enumerate hidden services
3131 * created via the control port. */
3133 getinfo_helper_onions(control_connection_t
*control_conn
,
3134 const char *question
, char **answer
,
3135 const char **errmsg
)
3137 smartlist_t
*onion_list
= NULL
;
3138 (void) errmsg
; /* no errors from this method */
3140 if (control_conn
&& !strcmp(question
, "onions/current")) {
3141 onion_list
= control_conn
->ephemeral_onion_services
;
3142 } else if (!strcmp(question
, "onions/detached")) {
3143 onion_list
= detached_onion_services
;
3147 if (!onion_list
|| smartlist_len(onion_list
) == 0) {
3149 *answer
= tor_strdup("");
3153 *answer
= smartlist_join_strings(onion_list
, "\r\n", 0, NULL
);
3160 /** Implementation helper for GETINFO: answers queries about network
3163 getinfo_helper_liveness(control_connection_t
*control_conn
,
3164 const char *question
, char **answer
,
3165 const char **errmsg
)
3169 if (strcmp(question
, "network-liveness") == 0) {
3170 if (get_cached_network_liveness()) {
3171 *answer
= tor_strdup("up");
3173 *answer
= tor_strdup("down");
3180 /** Implementation helper for GETINFO: answers queries about shared random
3183 getinfo_helper_sr(control_connection_t
*control_conn
,
3184 const char *question
, char **answer
,
3185 const char **errmsg
)
3187 (void) control_conn
;
3190 if (!strcmp(question
, "sr/current")) {
3191 *answer
= sr_get_current_for_control();
3192 } else if (!strcmp(question
, "sr/previous")) {
3193 *answer
= sr_get_previous_for_control();
3195 /* Else statement here is unrecognized key so do nothing. */
3200 /** Callback function for GETINFO: on a given control connection, try to
3201 * answer the question <b>q</b> and store the newly-allocated answer in
3202 * *<b>a</b>. If an internal error occurs, return -1 and optionally set
3203 * *<b>error_out</b> to point to an error message to be delivered to the
3204 * controller. On success, _or if the key is not recognized_, return 0. Do not
3205 * set <b>a</b> if the key is not recognized but you may set <b>error_out</b>
3206 * to improve the error message.
3208 typedef int (*getinfo_helper_t
)(control_connection_t
*,
3209 const char *q
, char **a
,
3210 const char **error_out
);
3212 /** A single item for the GETINFO question-to-answer-function table. */
3213 typedef struct getinfo_item_t
{
3214 const char *varname
; /**< The value (or prefix) of the question. */
3215 getinfo_helper_t fn
; /**< The function that knows the answer: NULL if
3216 * this entry is documentation-only. */
3217 const char *desc
; /**< Description of the variable. */
3218 int is_prefix
; /** Must varname match exactly, or must it be a prefix? */
3221 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
3222 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
3223 #define DOC(name, desc) { name, NULL, desc, 0 }
3225 /** Table mapping questions accepted by GETINFO to the functions that know how
3226 * to answer them. */
3227 static const getinfo_item_t getinfo_items
[] = {
3228 ITEM("version", misc
, "The current version of Tor."),
3229 ITEM("bw-event-cache", misc
, "Cached BW events for a short interval."),
3230 ITEM("config-file", misc
, "Current location of the \"torrc\" file."),
3231 ITEM("config-defaults-file", misc
, "Current location of the defaults file."),
3232 ITEM("config-text", misc
,
3233 "Return the string that would be written by a saveconf command."),
3234 ITEM("config-can-saveconf", misc
,
3235 "Is it possible to save the configuration to the \"torrc\" file?"),
3236 ITEM("accounting/bytes", accounting
,
3237 "Number of bytes read/written so far in the accounting interval."),
3238 ITEM("accounting/bytes-left", accounting
,
3239 "Number of bytes left to write/read so far in the accounting interval."),
3240 ITEM("accounting/enabled", accounting
, "Is accounting currently enabled?"),
3241 ITEM("accounting/hibernating", accounting
, "Are we hibernating or awake?"),
3242 ITEM("accounting/interval-start", accounting
,
3243 "Time when the accounting period starts."),
3244 ITEM("accounting/interval-end", accounting
,
3245 "Time when the accounting period ends."),
3246 ITEM("accounting/interval-wake", accounting
,
3247 "Time to wake up in this accounting period."),
3248 ITEM("helper-nodes", entry_guards
, NULL
), /* deprecated */
3249 ITEM("entry-guards", entry_guards
,
3250 "Which nodes are we using as entry guards?"),
3251 ITEM("fingerprint", misc
, NULL
),
3252 PREFIX("config/", config
, "Current configuration values."),
3254 "List of configuration options, types, and documentation."),
3255 DOC("config/defaults",
3256 "List of default values for configuration options. "
3257 "See also config/names"),
3258 PREFIX("current-time/", current_time
, "Current time."),
3259 DOC("current-time/local", "Current time on the local system."),
3260 DOC("current-time/utc", "Current UTC time."),
3261 PREFIX("downloads/networkstatus/", downloads
,
3262 "Download statuses for networkstatus objects"),
3263 DOC("downloads/networkstatus/ns",
3264 "Download status for current-mode networkstatus download"),
3265 DOC("downloads/networkstatus/ns/bootstrap",
3266 "Download status for bootstrap-time networkstatus download"),
3267 DOC("downloads/networkstatus/ns/running",
3268 "Download status for run-time networkstatus download"),
3269 DOC("downloads/networkstatus/microdesc",
3270 "Download status for current-mode microdesc download"),
3271 DOC("downloads/networkstatus/microdesc/bootstrap",
3272 "Download status for bootstrap-time microdesc download"),
3273 DOC("downloads/networkstatus/microdesc/running",
3274 "Download status for run-time microdesc download"),
3275 PREFIX("downloads/cert/", downloads
,
3276 "Download statuses for certificates, by id fingerprint and "
3278 DOC("downloads/cert/fps",
3279 "List of authority fingerprints for which any download statuses "
3281 DOC("downloads/cert/fp/<fp>",
3282 "Download status for <fp> with the default signing key; corresponds "
3283 "to /fp/ URLs on directory server."),
3284 DOC("downloads/cert/fp/<fp>/sks",
3285 "List of signing keys for which specific download statuses are "
3286 "available for this id fingerprint"),
3287 DOC("downloads/cert/fp/<fp>/<sk>",
3288 "Download status for <fp> with signing key <sk>; corresponds "
3289 "to /fp-sk/ URLs on directory server."),
3290 PREFIX("downloads/desc/", downloads
,
3291 "Download statuses for router descriptors, by descriptor digest"),
3292 DOC("downloads/desc/descs",
3293 "Return a list of known router descriptor digests"),
3294 DOC("downloads/desc/<desc>",
3295 "Return a download status for a given descriptor digest"),
3296 PREFIX("downloads/bridge/", downloads
,
3297 "Download statuses for bridge descriptors, by bridge identity "
3299 DOC("downloads/bridge/bridges",
3300 "Return a list of configured bridge identity digests with download "
3302 DOC("downloads/bridge/<desc>",
3303 "Return a download status for a given bridge identity digest"),
3304 ITEM("info/names", misc
,
3305 "List of GETINFO options, types, and documentation."),
3306 ITEM("events/names", misc
,
3307 "Events that the controller can ask for with SETEVENTS."),
3308 ITEM("signal/names", misc
, "Signal names recognized by the SIGNAL command"),
3309 ITEM("features/names", misc
, "What arguments can USEFEATURE take?"),
3310 PREFIX("desc/id/", dir
, "Router descriptors by ID."),
3311 PREFIX("desc/name/", dir
, "Router descriptors by nickname."),
3312 ITEM("desc/all-recent", dir
,
3313 "All non-expired, non-superseded router descriptors."),
3314 ITEM("desc/download-enabled", dir
,
3315 "Do we try to download router descriptors?"),
3316 ITEM("desc/all-recent-extrainfo-hack", dir
, NULL
), /* Hack. */
3317 ITEM("md/all", dir
, "All known microdescriptors."),
3318 PREFIX("md/id/", dir
, "Microdescriptors by ID"),
3319 PREFIX("md/name/", dir
, "Microdescriptors by name"),
3320 ITEM("md/download-enabled", dir
,
3321 "Do we try to download microdescriptors?"),
3322 PREFIX("extra-info/digest/", dir
, "Extra-info documents by digest."),
3323 PREFIX("hs/client/desc/id", dir
,
3324 "Hidden Service descriptor in client's cache by onion."),
3325 PREFIX("hs/service/desc/id/", dir
,
3326 "Hidden Service descriptor in services's cache by onion."),
3327 PREFIX("net/listeners/", listeners
, "Bound addresses by type"),
3328 ITEM("ns/all", networkstatus
,
3329 "Brief summary of router status (v2 directory format)"),
3330 PREFIX("ns/id/", networkstatus
,
3331 "Brief summary of router status by ID (v2 directory format)."),
3332 PREFIX("ns/name/", networkstatus
,
3333 "Brief summary of router status by nickname (v2 directory format)."),
3334 PREFIX("ns/purpose/", networkstatus
,
3335 "Brief summary of router status by purpose (v2 directory format)."),
3336 PREFIX("consensus/", networkstatus
,
3337 "Information about and from the ns consensus."),
3338 ITEM("network-status", dir
,
3339 "Brief summary of router status (v1 directory format)"),
3340 ITEM("network-liveness", liveness
,
3341 "Current opinion on whether the network is live"),
3342 ITEM("circuit-status", events
, "List of current circuits originating here."),
3343 ITEM("stream-status", events
,"List of current streams."),
3344 ITEM("orconn-status", events
, "A list of current OR connections."),
3345 ITEM("dormant", misc
,
3346 "Is Tor dormant (not building circuits because it's idle)?"),
3347 PREFIX("address-mappings/", events
, NULL
),
3348 DOC("address-mappings/all", "Current address mappings."),
3349 DOC("address-mappings/cache", "Current cached DNS replies."),
3350 DOC("address-mappings/config",
3351 "Current address mappings from configuration."),
3352 DOC("address-mappings/control", "Current address mappings from controller."),
3353 PREFIX("status/", events
, NULL
),
3354 DOC("status/circuit-established",
3355 "Whether we think client functionality is working."),
3356 DOC("status/enough-dir-info",
3357 "Whether we have enough up-to-date directory information to build "
3359 DOC("status/bootstrap-phase",
3360 "The last bootstrap phase status event that Tor sent."),
3361 DOC("status/clients-seen",
3362 "Breakdown of client countries seen by a bridge."),
3363 DOC("status/fresh-relay-descs",
3364 "A fresh relay/ei descriptor pair for Tor's current state. Not stored."),
3365 DOC("status/version/recommended", "List of currently recommended versions."),
3366 DOC("status/version/current", "Status of the current version."),
3367 DOC("status/version/num-versioning", "Number of versioning authorities."),
3368 DOC("status/version/num-concurring",
3369 "Number of versioning authorities agreeing on the status of the "
3371 ITEM("address", misc
, "IP address of this Tor host, if we can guess it."),
3372 ITEM("traffic/read", misc
,"Bytes read since the process was started."),
3373 ITEM("traffic/written", misc
,
3374 "Bytes written since the process was started."),
3375 ITEM("uptime", misc
, "Uptime of the Tor daemon in seconds."),
3376 ITEM("process/pid", misc
, "Process id belonging to the main tor process."),
3377 ITEM("process/uid", misc
, "User id running the tor process."),
3378 ITEM("process/user", misc
,
3379 "Username under which the tor process is running."),
3380 ITEM("process/descriptor-limit", misc
, "File descriptor limit."),
3381 ITEM("limits/max-mem-in-queues", misc
, "Actual limit on memory in queues"),
3382 PREFIX("desc-annotations/id/", dir
, "Router annotations by hexdigest."),
3383 PREFIX("dir/server/", dir
,"Router descriptors as retrieved from a DirPort."),
3384 PREFIX("dir/status/", dir
,
3385 "v2 networkstatus docs as retrieved from a DirPort."),
3386 ITEM("dir/status-vote/current/consensus", dir
,
3387 "v3 Networkstatus consensus as retrieved from a DirPort."),
3388 ITEM("exit-policy/default", policies
,
3389 "The default value appended to the configured exit policy."),
3390 ITEM("exit-policy/reject-private/default", policies
,
3391 "The default rules appended to the configured exit policy by"
3392 " ExitPolicyRejectPrivate."),
3393 ITEM("exit-policy/reject-private/relay", policies
,
3394 "The relay-specific rules appended to the configured exit policy by"
3395 " ExitPolicyRejectPrivate and/or ExitPolicyRejectLocalInterfaces."),
3396 ITEM("exit-policy/full", policies
, "The entire exit policy of onion router"),
3397 ITEM("exit-policy/ipv4", policies
, "IPv4 parts of exit policy"),
3398 ITEM("exit-policy/ipv6", policies
, "IPv6 parts of exit policy"),
3399 PREFIX("ip-to-country/", geoip
, "Perform a GEOIP lookup"),
3400 ITEM("onions/current", onions
,
3401 "Onion services owned by the current control connection."),
3402 ITEM("onions/detached", onions
,
3403 "Onion services detached from the control connection."),
3404 ITEM("sr/current", sr
, "Get current shared random value."),
3405 ITEM("sr/previous", sr
, "Get previous shared random value."),
3406 { NULL
, NULL
, NULL
, 0 }
3409 /** Allocate and return a list of recognized GETINFO options. */
3411 list_getinfo_options(void)
3414 smartlist_t
*lines
= smartlist_new();
3416 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
3417 if (!getinfo_items
[i
].desc
)
3420 smartlist_add_asprintf(lines
, "%s%s -- %s\n",
3421 getinfo_items
[i
].varname
,
3422 getinfo_items
[i
].is_prefix
? "*" : "",
3423 getinfo_items
[i
].desc
);
3425 smartlist_sort_strings(lines
);
3427 ans
= smartlist_join_strings(lines
, "", 0, NULL
);
3428 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
3429 smartlist_free(lines
);
3434 /** Lookup the 'getinfo' entry <b>question</b>, and return
3435 * the answer in <b>*answer</b> (or NULL if key not recognized).
3436 * Return 0 if success or unrecognized, or -1 if recognized but
3437 * internal error. */
3439 handle_getinfo_helper(control_connection_t
*control_conn
,
3440 const char *question
, char **answer
,
3441 const char **err_out
)
3444 *answer
= NULL
; /* unrecognized key by default */
3446 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
3448 if (getinfo_items
[i
].is_prefix
)
3449 match
= !strcmpstart(question
, getinfo_items
[i
].varname
);
3451 match
= !strcmp(question
, getinfo_items
[i
].varname
);
3453 tor_assert(getinfo_items
[i
].fn
);
3454 return getinfo_items
[i
].fn(control_conn
, question
, answer
, err_out
);
3458 return 0; /* unrecognized */
3461 /** Called when we receive a GETINFO command. Try to fetch all requested
3462 * information, and reply with information or error message. */
3464 handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
3467 smartlist_t
*questions
= smartlist_new();
3468 smartlist_t
*answers
= smartlist_new();
3469 smartlist_t
*unrecognized
= smartlist_new();
3472 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
3474 smartlist_split_string(questions
, body
, " ",
3475 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3476 SMARTLIST_FOREACH_BEGIN(questions
, const char *, q
) {
3477 const char *errmsg
= NULL
;
3479 if (handle_getinfo_helper(conn
, q
, &ans
, &errmsg
) < 0) {
3481 errmsg
= "Internal error";
3482 connection_printf_to_buf(conn
, "551 %s\r\n", errmsg
);
3486 if (errmsg
) /* use provided error message */
3487 smartlist_add_strdup(unrecognized
, errmsg
);
3488 else /* use default error message */
3489 smartlist_add_asprintf(unrecognized
, "Unrecognized key \"%s\"", q
);
3491 smartlist_add_strdup(answers
, q
);
3492 smartlist_add(answers
, ans
);
3494 } SMARTLIST_FOREACH_END(q
);
3496 if (smartlist_len(unrecognized
)) {
3497 /* control-spec section 2.3, mid-reply '-' or end of reply ' ' */
3498 for (i
=0; i
< smartlist_len(unrecognized
)-1; ++i
)
3499 connection_printf_to_buf(conn
,
3501 (char *)smartlist_get(unrecognized
, i
));
3503 connection_printf_to_buf(conn
,
3505 (char *)smartlist_get(unrecognized
, i
));
3509 for (i
= 0; i
< smartlist_len(answers
); i
+= 2) {
3510 char *k
= smartlist_get(answers
, i
);
3511 char *v
= smartlist_get(answers
, i
+1);
3512 if (!strchr(v
, '\n') && !strchr(v
, '\r')) {
3513 connection_printf_to_buf(conn
, "250-%s=", k
);
3514 connection_write_str_to_buf(v
, conn
);
3515 connection_write_str_to_buf("\r\n", conn
);
3519 esc_len
= write_escaped_data(v
, strlen(v
), &esc
);
3520 connection_printf_to_buf(conn
, "250+%s=\r\n", k
);
3521 connection_buf_add(esc
, esc_len
, TO_CONN(conn
));
3525 connection_write_str_to_buf("250 OK\r\n", conn
);
3528 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
3529 smartlist_free(answers
);
3530 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
3531 smartlist_free(questions
);
3532 SMARTLIST_FOREACH(unrecognized
, char *, cp
, tor_free(cp
));
3533 smartlist_free(unrecognized
);
3538 /** Given a string, convert it to a circuit purpose. */
3540 circuit_purpose_from_string(const char *string
)
3542 if (!strcasecmpstart(string
, "purpose="))
3543 string
+= strlen("purpose=");
3545 if (!strcasecmp(string
, "general"))
3546 return CIRCUIT_PURPOSE_C_GENERAL
;
3547 else if (!strcasecmp(string
, "controller"))
3548 return CIRCUIT_PURPOSE_CONTROLLER
;
3550 return CIRCUIT_PURPOSE_UNKNOWN
;
3553 /** Return a newly allocated smartlist containing the arguments to the command
3554 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
3555 * or if <b>max_args</b> is nonnegative and there are more than
3556 * <b>max_args</b> arguments, send a 512 error to the controller, using
3557 * <b>command</b> as the command name in the error message. */
3558 static smartlist_t
*
3559 getargs_helper(const char *command
, control_connection_t
*conn
,
3560 const char *body
, int min_args
, int max_args
)
3562 smartlist_t
*args
= smartlist_new();
3563 smartlist_split_string(args
, body
, " ",
3564 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3565 if (smartlist_len(args
) < min_args
) {
3566 connection_printf_to_buf(conn
, "512 Missing argument to %s\r\n",command
);
3568 } else if (max_args
>= 0 && smartlist_len(args
) > max_args
) {
3569 connection_printf_to_buf(conn
, "512 Too many arguments to %s\r\n",command
);
3574 SMARTLIST_FOREACH(args
, char *, s
, tor_free(s
));
3575 smartlist_free(args
);
3579 /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
3580 * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
3581 * such element exists. */
3583 find_element_starting_with(smartlist_t
*sl
, int start_at
, const char *prefix
)
3586 for (i
= start_at
; i
< smartlist_len(sl
); ++i
) {
3587 const char *elt
= smartlist_get(sl
, i
);
3588 if (!strcasecmpstart(elt
, prefix
))
3594 /** Helper. Return true iff s is an argument that we should treat as a
3595 * key-value pair. */
3597 is_keyval_pair(const char *s
)
3599 /* An argument is a key-value pair if it has an =, and it isn't of the form
3600 * $fingeprint=name */
3601 return strchr(s
, '=') && s
[0] != '$';
3604 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
3605 * circuit, and report success or failure. */
3607 handle_control_extendcircuit(control_connection_t
*conn
, uint32_t len
,
3610 smartlist_t
*router_nicknames
=NULL
, *nodes
=NULL
;
3611 origin_circuit_t
*circ
= NULL
;
3613 uint8_t intended_purpose
= CIRCUIT_PURPOSE_C_GENERAL
;
3617 router_nicknames
= smartlist_new();
3619 args
= getargs_helper("EXTENDCIRCUIT", conn
, body
, 1, -1);
3623 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,0));
3626 const char *purp
= find_element_starting_with(args
, 1, "PURPOSE=");
3629 intended_purpose
= circuit_purpose_from_string(purp
);
3630 if (intended_purpose
== CIRCUIT_PURPOSE_UNKNOWN
) {
3631 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
3632 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3633 smartlist_free(args
);
3638 if ((smartlist_len(args
) == 1) ||
3639 (smartlist_len(args
) >= 2 && is_keyval_pair(smartlist_get(args
, 1)))) {
3640 // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
3641 circ
= circuit_launch(intended_purpose
, CIRCLAUNCH_NEED_CAPACITY
);
3643 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
3645 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
3646 (unsigned long)circ
->global_identifier
);
3648 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3649 smartlist_free(args
);
3652 // "EXTENDCIRCUIT 0 router1,router2" ||
3653 // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
3656 if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
,0)))) {
3657 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
3658 (char*)smartlist_get(args
, 0));
3659 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3660 smartlist_free(args
);
3664 if (smartlist_len(args
) < 2) {
3665 connection_printf_to_buf(conn
,
3666 "512 syntax error: not enough arguments.\r\n");
3667 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3668 smartlist_free(args
);
3672 smartlist_split_string(router_nicknames
, smartlist_get(args
,1), ",", 0, 0);
3674 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3675 smartlist_free(args
);
3677 nodes
= smartlist_new();
3678 int first_node
= zero_circ
;
3679 SMARTLIST_FOREACH_BEGIN(router_nicknames
, const char *, n
) {
3680 const node_t
*node
= node_get_by_nickname(n
, 0);
3682 connection_printf_to_buf(conn
, "552 No such router \"%s\"\r\n", n
);
3685 if (!node_has_preferred_descriptor(node
, first_node
)) {
3686 connection_printf_to_buf(conn
, "552 No descriptor for \"%s\"\r\n", n
);
3689 smartlist_add(nodes
, (void*)node
);
3691 } SMARTLIST_FOREACH_END(n
);
3692 if (!smartlist_len(nodes
)) {
3693 connection_write_str_to_buf("512 No router names provided\r\n", conn
);
3698 /* start a new circuit */
3699 circ
= origin_circuit_init(intended_purpose
, 0);
3702 /* now circ refers to something that is ready to be extended */
3703 first_node
= zero_circ
;
3704 SMARTLIST_FOREACH(nodes
, const node_t
*, node
,
3706 extend_info_t
*info
= extend_info_from_node(node
, first_node
);
3708 tor_assert_nonfatal(first_node
);
3709 log_warn(LD_CONTROL
,
3710 "controller tried to connect to a node that lacks a suitable "
3711 "descriptor, or which doesn't have any "
3712 "addresses that are allowed by the firewall configuration; "
3713 "circuit marked for closing.");
3714 circuit_mark_for_close(TO_CIRCUIT(circ
), -END_CIRC_REASON_CONNECTFAILED
);
3715 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
3718 circuit_append_new_exit(circ
, info
);
3719 if (circ
->build_state
->desired_path_len
> 1) {
3720 circ
->build_state
->onehop_tunnel
= 0;
3722 extend_info_free(info
);
3726 /* now that we've populated the cpath, start extending */
3729 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
3730 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
3731 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
3735 if (circ
->base_
.state
== CIRCUIT_STATE_OPEN
||
3736 circ
->base_
.state
== CIRCUIT_STATE_GUARD_WAIT
) {
3738 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
3739 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
3740 log_info(LD_CONTROL
,
3741 "send_next_onion_skin failed; circuit marked for closing.");
3742 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
3743 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn
);
3749 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
3750 (unsigned long)circ
->global_identifier
);
3751 if (zero_circ
) /* send a 'launched' event, for completeness */
3752 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
3754 SMARTLIST_FOREACH(router_nicknames
, char *, n
, tor_free(n
));
3755 smartlist_free(router_nicknames
);
3756 smartlist_free(nodes
);
3760 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
3761 * circuit and it's a valid purpose, change it. */
3763 handle_control_setcircuitpurpose(control_connection_t
*conn
,
3764 uint32_t len
, const char *body
)
3766 origin_circuit_t
*circ
= NULL
;
3767 uint8_t new_purpose
;
3769 (void) len
; /* body is NUL-terminated, so it's safe to ignore the length. */
3771 args
= getargs_helper("SETCIRCUITPURPOSE", conn
, body
, 2, -1);
3775 if (!(circ
= get_circ(smartlist_get(args
,0)))) {
3776 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
3777 (char*)smartlist_get(args
, 0));
3782 const char *purp
= find_element_starting_with(args
,1,"PURPOSE=");
3784 connection_write_str_to_buf("552 No purpose given\r\n", conn
);
3787 new_purpose
= circuit_purpose_from_string(purp
);
3788 if (new_purpose
== CIRCUIT_PURPOSE_UNKNOWN
) {
3789 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
3794 circuit_change_purpose(TO_CIRCUIT(circ
), new_purpose
);
3795 connection_write_str_to_buf("250 OK\r\n", conn
);
3799 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3800 smartlist_free(args
);
3805 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
3806 * stream, and report success or failure. */
3808 handle_control_attachstream(control_connection_t
*conn
, uint32_t len
,
3811 entry_connection_t
*ap_conn
= NULL
;
3812 origin_circuit_t
*circ
= NULL
;
3815 crypt_path_t
*cpath
=NULL
;
3816 int hop
=0, hop_line_ok
=1;
3819 args
= getargs_helper("ATTACHSTREAM", conn
, body
, 2, -1);
3823 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,1));
3825 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))) {
3826 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
3827 (char*)smartlist_get(args
, 0));
3828 } else if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
, 1)))) {
3829 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
3830 (char*)smartlist_get(args
, 1));
3832 const char *hopstring
= find_element_starting_with(args
,2,"HOP=");
3834 hopstring
+= strlen("HOP=");
3835 hop
= (int) tor_parse_ulong(hopstring
, 10, 0, INT_MAX
,
3836 &hop_line_ok
, NULL
);
3837 if (!hop_line_ok
) { /* broken hop line */
3838 connection_printf_to_buf(conn
, "552 Bad value hop=%s\r\n", hopstring
);
3842 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
3843 smartlist_free(args
);
3844 if (!ap_conn
|| (!zero_circ
&& !circ
) || !hop_line_ok
)
3847 if (ENTRY_TO_CONN(ap_conn
)->state
!= AP_CONN_STATE_CONTROLLER_WAIT
&&
3848 ENTRY_TO_CONN(ap_conn
)->state
!= AP_CONN_STATE_CONNECT_WAIT
&&
3849 ENTRY_TO_CONN(ap_conn
)->state
!= AP_CONN_STATE_RESOLVE_WAIT
) {
3850 connection_write_str_to_buf(
3851 "555 Connection is not managed by controller.\r\n",
3856 /* Do we need to detach it first? */
3857 if (ENTRY_TO_CONN(ap_conn
)->state
!= AP_CONN_STATE_CONTROLLER_WAIT
) {
3858 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(ap_conn
);
3859 circuit_t
*tmpcirc
= circuit_get_by_edge_conn(edge_conn
);
3860 connection_edge_end(edge_conn
, END_STREAM_REASON_TIMEOUT
);
3861 /* Un-mark it as ending, since we're going to reuse it. */
3862 edge_conn
->edge_has_sent_end
= 0;
3863 edge_conn
->end_reason
= 0;
3865 circuit_detach_stream(tmpcirc
, edge_conn
);
3866 CONNECTION_AP_EXPECT_NONPENDING(ap_conn
);
3867 TO_CONN(edge_conn
)->state
= AP_CONN_STATE_CONTROLLER_WAIT
;
3870 if (circ
&& (circ
->base_
.state
!= CIRCUIT_STATE_OPEN
)) {
3871 connection_write_str_to_buf(
3872 "551 Can't attach stream to non-open origin circuit\r\n",
3876 /* Is this a single hop circuit? */
3877 if (circ
&& (circuit_get_cpath_len(circ
)<2 || hop
==1)) {
3878 connection_write_str_to_buf(
3879 "551 Can't attach stream to this one-hop circuit.\r\n", conn
);
3883 if (circ
&& hop
>0) {
3884 /* find this hop in the circuit, and set cpath */
3885 cpath
= circuit_get_cpath_hop(circ
, hop
);
3887 connection_printf_to_buf(conn
,
3888 "551 Circuit doesn't have %d hops.\r\n", hop
);
3892 if (connection_ap_handshake_rewrite_and_attach(ap_conn
, circ
, cpath
) < 0) {
3893 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn
);
3896 send_control_done(conn
);
3900 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
3901 * descriptor, and report success or failure. */
3903 handle_control_postdescriptor(control_connection_t
*conn
, uint32_t len
,
3907 const char *msg
=NULL
;
3908 uint8_t purpose
= ROUTER_PURPOSE_GENERAL
;
3909 int cache
= 0; /* eventually, we may switch this to 1 */
3911 const char *cp
= memchr(body
, '\n', len
);
3914 connection_printf_to_buf(conn
, "251 Empty body\r\n");
3919 char *cmdline
= tor_memdup_nulterm(body
, cp
-body
);
3920 smartlist_t
*args
= smartlist_new();
3921 smartlist_split_string(args
, cmdline
, " ",
3922 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3923 SMARTLIST_FOREACH_BEGIN(args
, char *, option
) {
3924 if (!strcasecmpstart(option
, "purpose=")) {
3925 option
+= strlen("purpose=");
3926 purpose
= router_purpose_from_string(option
);
3927 if (purpose
== ROUTER_PURPOSE_UNKNOWN
) {
3928 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n",
3932 } else if (!strcasecmpstart(option
, "cache=")) {
3933 option
+= strlen("cache=");
3934 if (!strcasecmp(option
, "no"))
3936 else if (!strcasecmp(option
, "yes"))
3939 connection_printf_to_buf(conn
, "552 Unknown cache request \"%s\"\r\n",
3943 } else { /* unrecognized argument? */
3944 connection_printf_to_buf(conn
,
3945 "512 Unexpected argument \"%s\" to postdescriptor\r\n", option
);
3948 } SMARTLIST_FOREACH_END(option
);
3950 read_escaped_data(cp
, len
-(cp
-body
), &desc
);
3952 switch (router_load_single_router(desc
, purpose
, cache
, &msg
)) {
3954 if (!msg
) msg
= "Could not parse descriptor";
3955 connection_printf_to_buf(conn
, "554 %s\r\n", msg
);
3958 if (!msg
) msg
= "Descriptor not added";
3959 connection_printf_to_buf(conn
, "251 %s\r\n",msg
);
3962 send_control_done(conn
);
3968 SMARTLIST_FOREACH(args
, char *, arg
, tor_free(arg
));
3969 smartlist_free(args
);
3974 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
3975 * address of the named AP stream, and report success or failure. */
3977 handle_control_redirectstream(control_connection_t
*conn
, uint32_t len
,
3980 entry_connection_t
*ap_conn
= NULL
;
3981 char *new_addr
= NULL
;
3982 uint16_t new_port
= 0;
3986 args
= getargs_helper("REDIRECTSTREAM", conn
, body
, 2, -1);
3990 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))
3991 || !ap_conn
->socks_request
) {
3992 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
3993 (char*)smartlist_get(args
, 0));
3996 if (smartlist_len(args
) > 2) { /* they included a port too */
3997 new_port
= (uint16_t) tor_parse_ulong(smartlist_get(args
, 2),
3998 10, 1, 65535, &ok
, NULL
);
4001 connection_printf_to_buf(conn
, "512 Cannot parse port \"%s\"\r\n",
4002 (char*)smartlist_get(args
, 2));
4004 new_addr
= tor_strdup(smartlist_get(args
, 1));
4008 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4009 smartlist_free(args
);
4013 strlcpy(ap_conn
->socks_request
->address
, new_addr
,
4014 sizeof(ap_conn
->socks_request
->address
));
4016 ap_conn
->socks_request
->port
= new_port
;
4018 send_control_done(conn
);
4022 /** Called when we get a CLOSESTREAM command; try to close the named stream
4023 * and report success or failure. */
4025 handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
4028 entry_connection_t
*ap_conn
=NULL
;
4034 args
= getargs_helper("CLOSESTREAM", conn
, body
, 2, -1);
4038 else if (!(ap_conn
= get_stream(smartlist_get(args
, 0))))
4039 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
4040 (char*)smartlist_get(args
, 0));
4042 reason
= (uint8_t) tor_parse_ulong(smartlist_get(args
,1), 10, 0, 255,
4045 connection_printf_to_buf(conn
, "552 Unrecognized reason \"%s\"\r\n",
4046 (char*)smartlist_get(args
, 1));
4050 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4051 smartlist_free(args
);
4055 connection_mark_unattached_ap(ap_conn
, reason
);
4056 send_control_done(conn
);
4060 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
4061 * and report success or failure. */
4063 handle_control_closecircuit(control_connection_t
*conn
, uint32_t len
,
4066 origin_circuit_t
*circ
= NULL
;
4071 args
= getargs_helper("CLOSECIRCUIT", conn
, body
, 1, -1);
4075 if (!(circ
=get_circ(smartlist_get(args
, 0))))
4076 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
4077 (char*)smartlist_get(args
, 0));
4080 for (i
=1; i
< smartlist_len(args
); ++i
) {
4081 if (!strcasecmp(smartlist_get(args
, i
), "IfUnused"))
4084 log_info(LD_CONTROL
, "Skipping unknown option %s",
4085 (char*)smartlist_get(args
,i
));
4088 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4089 smartlist_free(args
);
4093 if (!safe
|| !circ
->p_streams
) {
4094 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_REQUESTED
);
4097 send_control_done(conn
);
4101 /** Called when we get a RESOLVE command: start trying to resolve
4102 * the listed addresses. */
4104 handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
4107 smartlist_t
*args
, *failed
;
4109 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
4111 if (!(conn
->event_mask
& (((event_mask_t
)1)<<EVENT_ADDRMAP
))) {
4112 log_warn(LD_CONTROL
, "Controller asked us to resolve an address, but "
4113 "isn't listening for ADDRMAP events. It probably won't see "
4116 args
= smartlist_new();
4117 smartlist_split_string(args
, body
, " ",
4118 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
4120 const char *modearg
= find_element_starting_with(args
, 0, "mode=");
4121 if (modearg
&& !strcasecmp(modearg
, "mode=reverse"))
4124 failed
= smartlist_new();
4125 SMARTLIST_FOREACH(args
, const char *, arg
, {
4126 if (!is_keyval_pair(arg
)) {
4127 if (dnsserv_launch_request(arg
, is_reverse
, conn
)<0)
4128 smartlist_add(failed
, (char*)arg
);
4132 send_control_done(conn
);
4133 SMARTLIST_FOREACH(failed
, const char *, arg
, {
4134 control_event_address_mapped(arg
, arg
, time(NULL
),
4138 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4139 smartlist_free(args
);
4140 smartlist_free(failed
);
4144 /** Called when we get a PROTOCOLINFO command: send back a reply. */
4146 handle_control_protocolinfo(control_connection_t
*conn
, uint32_t len
,
4149 const char *bad_arg
= NULL
;
4153 conn
->have_sent_protocolinfo
= 1;
4154 args
= smartlist_new();
4155 smartlist_split_string(args
, body
, " ",
4156 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
4157 SMARTLIST_FOREACH(args
, const char *, arg
, {
4159 tor_parse_long(arg
, 10, 0, LONG_MAX
, &ok
, NULL
);
4166 connection_printf_to_buf(conn
, "513 No such version %s\r\n",
4168 /* Don't tolerate bad arguments when not authenticated. */
4169 if (!STATE_IS_OPEN(TO_CONN(conn
)->state
))
4170 connection_mark_for_close(TO_CONN(conn
));
4173 const or_options_t
*options
= get_options();
4174 int cookies
= options
->CookieAuthentication
;
4175 char *cfile
= get_controller_cookie_file_name();
4179 abs_cfile
= make_path_absolute(cfile
);
4180 esc_cfile
= esc_for_log(abs_cfile
);
4182 int passwd
= (options
->HashedControlPassword
!= NULL
||
4183 options
->HashedControlSessionPassword
!= NULL
);
4184 smartlist_t
*mlist
= smartlist_new();
4186 smartlist_add(mlist
, (char*)"COOKIE");
4187 smartlist_add(mlist
, (char*)"SAFECOOKIE");
4190 smartlist_add(mlist
, (char*)"HASHEDPASSWORD");
4191 if (!cookies
&& !passwd
)
4192 smartlist_add(mlist
, (char*)"NULL");
4193 methods
= smartlist_join_strings(mlist
, ",", 0, NULL
);
4194 smartlist_free(mlist
);
4197 connection_printf_to_buf(conn
,
4198 "250-PROTOCOLINFO 1\r\n"
4199 "250-AUTH METHODS=%s%s%s\r\n"
4200 "250-VERSION Tor=%s\r\n"
4203 cookies
?" COOKIEFILE=":"",
4204 cookies
?esc_cfile
:"",
4208 tor_free(abs_cfile
);
4209 tor_free(esc_cfile
);
4212 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4213 smartlist_free(args
);
4217 /** Called when we get an AUTHCHALLENGE command. */
4219 handle_control_authchallenge(control_connection_t
*conn
, uint32_t len
,
4222 const char *cp
= body
;
4224 size_t client_nonce_len
;
4225 char server_hash
[DIGEST256_LEN
];
4226 char server_hash_encoded
[HEX_DIGEST256_LEN
+1];
4227 char server_nonce
[SAFECOOKIE_SERVER_NONCE_LEN
];
4228 char server_nonce_encoded
[(2*SAFECOOKIE_SERVER_NONCE_LEN
) + 1];
4230 cp
+= strspn(cp
, " \t\n\r");
4231 if (!strcasecmpstart(cp
, "SAFECOOKIE")) {
4232 cp
+= strlen("SAFECOOKIE");
4234 connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
4235 "authentication\r\n", conn
);
4236 connection_mark_for_close(TO_CONN(conn
));
4240 if (!authentication_cookie_is_set
) {
4241 connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
4243 connection_mark_for_close(TO_CONN(conn
));
4247 cp
+= strspn(cp
, " \t\n\r");
4250 decode_escaped_string(cp
, len
- (cp
- body
),
4251 &client_nonce
, &client_nonce_len
);
4252 if (newcp
== NULL
) {
4253 connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
4255 connection_mark_for_close(TO_CONN(conn
));
4260 size_t client_nonce_encoded_len
= strspn(cp
, "0123456789ABCDEFabcdef");
4262 client_nonce_len
= client_nonce_encoded_len
/ 2;
4263 client_nonce
= tor_malloc_zero(client_nonce_len
);
4265 if (base16_decode(client_nonce
, client_nonce_len
,
4266 cp
, client_nonce_encoded_len
)
4267 != (int) client_nonce_len
) {
4268 connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
4270 connection_mark_for_close(TO_CONN(conn
));
4271 tor_free(client_nonce
);
4275 cp
+= client_nonce_encoded_len
;
4278 cp
+= strspn(cp
, " \t\n\r");
4281 connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
4283 connection_mark_for_close(TO_CONN(conn
));
4284 tor_free(client_nonce
);
4287 crypto_rand(server_nonce
, SAFECOOKIE_SERVER_NONCE_LEN
);
4289 /* Now compute and send the server-to-controller response, and the
4290 * server's nonce. */
4291 tor_assert(authentication_cookie
!= NULL
);
4294 size_t tmp_len
= (AUTHENTICATION_COOKIE_LEN
+
4296 SAFECOOKIE_SERVER_NONCE_LEN
);
4297 char *tmp
= tor_malloc_zero(tmp_len
);
4298 char *client_hash
= tor_malloc_zero(DIGEST256_LEN
);
4299 memcpy(tmp
, authentication_cookie
, AUTHENTICATION_COOKIE_LEN
);
4300 memcpy(tmp
+ AUTHENTICATION_COOKIE_LEN
, client_nonce
, client_nonce_len
);
4301 memcpy(tmp
+ AUTHENTICATION_COOKIE_LEN
+ client_nonce_len
,
4302 server_nonce
, SAFECOOKIE_SERVER_NONCE_LEN
);
4304 crypto_hmac_sha256(server_hash
,
4305 SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT
,
4306 strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT
),
4310 crypto_hmac_sha256(client_hash
,
4311 SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT
,
4312 strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT
),
4316 conn
->safecookie_client_hash
= client_hash
;
4321 base16_encode(server_hash_encoded
, sizeof(server_hash_encoded
),
4322 server_hash
, sizeof(server_hash
));
4323 base16_encode(server_nonce_encoded
, sizeof(server_nonce_encoded
),
4324 server_nonce
, sizeof(server_nonce
));
4326 connection_printf_to_buf(conn
,
4327 "250 AUTHCHALLENGE SERVERHASH=%s "
4328 "SERVERNONCE=%s\r\n",
4329 server_hash_encoded
,
4330 server_nonce_encoded
);
4332 tor_free(client_nonce
);
4336 /** Called when we get a USEFEATURE command: parse the feature list, and
4337 * set up the control_connection's options properly. */
4339 handle_control_usefeature(control_connection_t
*conn
,
4345 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
4346 args
= smartlist_new();
4347 smartlist_split_string(args
, body
, " ",
4348 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
4349 SMARTLIST_FOREACH_BEGIN(args
, const char *, arg
) {
4350 if (!strcasecmp(arg
, "VERBOSE_NAMES"))
4352 else if (!strcasecmp(arg
, "EXTENDED_EVENTS"))
4355 connection_printf_to_buf(conn
, "552 Unrecognized feature \"%s\"\r\n",
4360 } SMARTLIST_FOREACH_END(arg
);
4363 send_control_done(conn
);
4366 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4367 smartlist_free(args
);
4371 /** Implementation for the DROPGUARDS command. */
4373 handle_control_dropguards(control_connection_t
*conn
,
4378 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
4379 args
= smartlist_new();
4380 smartlist_split_string(args
, body
, " ",
4381 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
4383 static int have_warned
= 0;
4384 if (! have_warned
) {
4385 log_warn(LD_CONTROL
, "DROPGUARDS is dangerous; make sure you understand "
4386 "the risks before using it. It may be removed in a future "
4391 if (smartlist_len(args
)) {
4392 connection_printf_to_buf(conn
, "512 Too many arguments to DROPGUARDS\r\n");
4394 remove_all_entry_guards();
4395 send_control_done(conn
);
4398 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4399 smartlist_free(args
);
4403 /** Implementation for the HSFETCH command. */
4405 handle_control_hsfetch(control_connection_t
*conn
, uint32_t len
,
4409 char *hsaddress
= NULL
, *arg1
= NULL
, *desc_id
= NULL
;
4410 smartlist_t
*args
= NULL
, *hsdirs
= NULL
;
4411 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
4412 static const char *hsfetch_command
= "HSFETCH";
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);
4424 /* We no longer support version 2 on the network and so immediately return an
4425 * error. We do this in order to not remove the code so to minimize the merge
4426 * forward conflicts. */
4427 connection_printf_to_buf(conn
, "513 Invalid argument \"%s\"\r\n",
4431 static const char *opt_server
= "SERVER=";
4433 /* Skip first argument because it's the HSAddress or DescID. */
4434 for (i
= 1; i
< smartlist_len(args
); ++i
) {
4435 const char *arg
= smartlist_get(args
, i
);
4438 if (!strcasecmpstart(arg
, opt_server
)) {
4441 server
= arg
+ strlen(opt_server
);
4442 node
= node_get_by_hex_id(server
, 0);
4444 connection_printf_to_buf(conn
, "552 Server \"%s\" not found\r\n",
4449 /* Stores routerstatus_t object for each specified server. */
4450 hsdirs
= smartlist_new();
4452 /* Valid server, add it to our local list. */
4453 smartlist_add(hsdirs
, node
->rs
);
4455 connection_printf_to_buf(conn
, "513 Unexpected argument \"%s\"\r\n",
4461 rend_query
= rend_data_client_create(hsaddress
, desc_id
, NULL
,
4463 if (rend_query
== NULL
) {
4464 connection_printf_to_buf(conn
, "551 Error creating the HS query\r\n");
4468 /* Using a descriptor ID, we force the user to provide at least one
4469 * hsdir server using the SERVER= option. */
4470 if (desc_id
&& (!hsdirs
|| !smartlist_len(hsdirs
))) {
4471 connection_printf_to_buf(conn
, "512 %s option is required\r\n",
4476 /* We are about to trigger HSDir fetch so send the OK now because after
4477 * that 650 event(s) are possible so better to have the 250 OK before them
4478 * to avoid out of order replies. */
4479 send_control_done(conn
);
4481 /* Trigger the fetch using the built rend query and possibly a list of HS
4482 * directory to use. This function ignores the client cache thus this will
4483 * always send a fetch command. */
4484 rend_client_fetch_v2_desc(rend_query
, hsdirs
);
4487 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
4488 smartlist_free(args
);
4489 /* Contains data pointer that we don't own thus no cleanup. */
4490 smartlist_free(hsdirs
);
4491 rend_data_free(rend_query
);
4496 /** Implementation for the HSPOST command. */
4498 handle_control_hspost(control_connection_t
*conn
,
4502 static const char *opt_server
= "SERVER=";
4503 static const char *opt_hsaddress
= "HSADDRESS=";
4504 smartlist_t
*hs_dirs
= NULL
;
4505 const char *encoded_desc
= body
;
4506 size_t encoded_desc_len
= len
;
4507 const char *onion_address
= NULL
;
4509 char *cp
= memchr(body
, '\n', len
);
4511 connection_printf_to_buf(conn
, "251 Empty body\r\n");
4514 char *argline
= tor_strndup(body
, cp
-body
);
4516 smartlist_t
*args
= smartlist_new();
4518 /* If any SERVER= or HSADDRESS= options were specified, try to parse
4519 * the options line. */
4520 if (!strcasecmpstart(argline
, opt_server
) ||
4521 !strcasecmpstart(argline
, opt_hsaddress
)) {
4522 /* encoded_desc begins after a newline character */
4525 encoded_desc_len
= len
-(cp
-body
);
4527 smartlist_split_string(args
, argline
, " ",
4528 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
4529 SMARTLIST_FOREACH_BEGIN(args
, const char *, arg
) {
4530 if (!strcasecmpstart(arg
, opt_server
)) {
4531 const char *server
= arg
+ strlen(opt_server
);
4532 const node_t
*node
= node_get_by_hex_id(server
, 0);
4534 if (!node
|| !node
->rs
) {
4535 connection_printf_to_buf(conn
, "552 Server \"%s\" not found\r\n",
4539 /* Valid server, add it to our local list. */
4541 hs_dirs
= smartlist_new();
4542 smartlist_add(hs_dirs
, node
->rs
);
4543 } else if (!strcasecmpstart(arg
, opt_hsaddress
)) {
4544 const char *address
= arg
+ strlen(opt_hsaddress
);
4545 if (!hs_address_is_valid(address
)) {
4546 connection_printf_to_buf(conn
, "512 Malformed onion address\r\n");
4549 onion_address
= address
;
4551 connection_printf_to_buf(conn
, "512 Unexpected argument \"%s\"\r\n",
4555 } SMARTLIST_FOREACH_END(arg
);
4558 /* Handle the v3 case. */
4559 if (onion_address
) {
4560 char *desc_str
= NULL
;
4561 read_escaped_data(encoded_desc
, encoded_desc_len
, &desc_str
);
4562 if (hs_control_hspost_command(desc_str
, onion_address
, hs_dirs
) < 0) {
4563 connection_printf_to_buf(conn
, "554 Invalid descriptor\r\n");
4565 send_control_done(conn
);
4570 /* As for HSFETCH, we no longer support v2 on the network and so we stop
4571 * right now. Code is not removed in order to minimize the merge forward
4575 /* From this point on, it is only v2. */
4577 /* Read the dot encoded descriptor, and parse it. */
4578 rend_encoded_v2_service_descriptor_t
*desc
=
4579 tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t
));
4580 read_escaped_data(encoded_desc
, encoded_desc_len
, &desc
->desc_str
);
4582 rend_service_descriptor_t
*parsed
= NULL
;
4583 char *intro_content
= NULL
;
4585 size_t encoded_size
;
4586 const char *next_desc
;
4587 if (!rend_parse_v2_service_descriptor(&parsed
, desc
->desc_id
, &intro_content
,
4588 &intro_size
, &encoded_size
,
4589 &next_desc
, desc
->desc_str
, 1)) {
4590 /* Post the descriptor. */
4591 char serviceid
[REND_SERVICE_ID_LEN_BASE32
+1];
4592 if (!rend_get_service_id(parsed
->pk
, serviceid
)) {
4593 smartlist_t
*descs
= smartlist_new();
4594 smartlist_add(descs
, desc
);
4596 /* We are about to trigger HS descriptor upload so send the OK now
4597 * because after that 650 event(s) are possible so better to have the
4598 * 250 OK before them to avoid out of order replies. */
4599 send_control_done(conn
);
4601 /* Trigger the descriptor upload */
4602 directory_post_to_hs_dir(parsed
, descs
, hs_dirs
, serviceid
, 0);
4603 smartlist_free(descs
);
4606 rend_service_descriptor_free(parsed
);
4608 connection_printf_to_buf(conn
, "554 Invalid descriptor\r\n");
4611 tor_free(intro_content
);
4612 rend_encoded_v2_service_descriptor_free(desc
);
4615 smartlist_free(hs_dirs
); /* Contents belong to the rend service code. */
4616 SMARTLIST_FOREACH(args
, char *, arg
, tor_free(arg
));
4617 smartlist_free(args
);
4621 /* Helper function for ADD_ONION that adds an ephemeral service depending on
4622 * the given hs_version.
4624 * The secret key in pk depends on the hs_version. The ownership of the key
4625 * used in pk is given to the HS subsystem so the caller must stop accessing
4628 * The port_cfgs is a list of service port. Ownership transferred to service.
4629 * The max_streams refers to the MaxStreams= key.
4630 * The max_streams_close_circuit refers to the MaxStreamsCloseCircuit key.
4631 * The auth_type is the authentication type of the clients in auth_clients.
4632 * The ownership of that list is transferred to the service.
4634 * On success (RSAE_OKAY), the address_out points to a newly allocated string
4635 * containing the onion address without the .onion part. On error, address_out
4637 static hs_service_add_ephemeral_status_t
4638 add_onion_helper_add_service(int hs_version
,
4639 add_onion_secret_key_t
*pk
,
4640 smartlist_t
*port_cfgs
, int max_streams
,
4641 int max_streams_close_circuit
, int auth_type
,
4642 smartlist_t
*auth_clients
, char **address_out
)
4644 hs_service_add_ephemeral_status_t ret
;
4647 tor_assert(port_cfgs
);
4648 tor_assert(address_out
);
4650 /* Version 2 is disabled. */
4652 (void) auth_clients
;
4654 switch (hs_version
) {
4655 case HS_VERSION_TWO
:
4656 ret
= RSAE_INTERNAL
;
4658 case HS_VERSION_THREE
:
4659 ret
= hs_service_add_ephemeral(pk
->v3
, port_cfgs
, max_streams
,
4660 max_streams_close_circuit
, address_out
);
4663 tor_assert_unreached();
4669 /** Called when we get a ADD_ONION command; parse the body, and set up
4670 * the new ephemeral Onion Service. */
4672 handle_control_add_onion(control_connection_t
*conn
,
4678 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
4679 args
= getargs_helper("ADD_ONION", conn
, body
, 2, -1);
4682 arg_len
= smartlist_len(args
);
4684 /* Parse all of the arguments that do not involve handling cryptographic
4685 * material first, since there's no reason to touch that at all if any of
4686 * the other arguments are malformed.
4688 smartlist_t
*port_cfgs
= smartlist_new();
4689 smartlist_t
*auth_clients
= NULL
;
4690 smartlist_t
*auth_created_clients
= NULL
;
4693 int max_streams
= 0;
4694 int max_streams_close_circuit
= 0;
4695 rend_auth_type_t auth_type
= REND_NO_AUTH
;
4696 /* Default to adding an anonymous hidden service if no flag is given */
4697 int non_anonymous
= 0;
4698 for (int i
= 1; i
< arg_len
; i
++) {
4699 static const char *port_prefix
= "Port=";
4700 static const char *flags_prefix
= "Flags=";
4701 static const char *max_s_prefix
= "MaxStreams=";
4702 static const char *auth_prefix
= "ClientAuth=";
4704 const char *arg
= smartlist_get(args
, (int)i
);
4705 if (!strcasecmpstart(arg
, port_prefix
)) {
4706 /* "Port=VIRTPORT[,TARGET]". */
4707 const char *port_str
= arg
+ strlen(port_prefix
);
4709 rend_service_port_config_t
*cfg
=
4710 rend_service_parse_port_config(port_str
, ",", NULL
);
4712 connection_printf_to_buf(conn
, "512 Invalid VIRTPORT/TARGET\r\n");
4715 smartlist_add(port_cfgs
, cfg
);
4716 } else if (!strcasecmpstart(arg
, max_s_prefix
)) {
4717 /* "MaxStreams=[0..65535]". */
4718 const char *max_s_str
= arg
+ strlen(max_s_prefix
);
4720 max_streams
= (int)tor_parse_long(max_s_str
, 10, 0, 65535, &ok
, NULL
);
4722 connection_printf_to_buf(conn
, "512 Invalid MaxStreams\r\n");
4725 } else if (!strcasecmpstart(arg
, flags_prefix
)) {
4726 /* "Flags=Flag[,Flag]", where Flag can be:
4727 * * 'DiscardPK' - If tor generates the keypair, do not include it in
4729 * * 'Detach' - Do not tie this onion service to any particular control
4731 * * 'MaxStreamsCloseCircuit' - Close the circuit if MaxStreams is
4733 * * 'BasicAuth' - Client authorization using the 'basic' method.
4734 * * 'NonAnonymous' - Add a non-anonymous Single Onion Service. If this
4735 * flag is present, tor must be in non-anonymous
4736 * hidden service mode. If this flag is absent,
4737 * tor must be in anonymous hidden service mode.
4739 static const char *discard_flag
= "DiscardPK";
4740 static const char *detach_flag
= "Detach";
4741 static const char *max_s_close_flag
= "MaxStreamsCloseCircuit";
4742 static const char *basicauth_flag
= "BasicAuth";
4743 static const char *non_anonymous_flag
= "NonAnonymous";
4745 smartlist_t
*flags
= smartlist_new();
4748 smartlist_split_string(flags
, arg
+ strlen(flags_prefix
), ",",
4749 SPLIT_IGNORE_BLANK
, 0);
4750 if (smartlist_len(flags
) < 1) {
4751 connection_printf_to_buf(conn
, "512 Invalid 'Flags' argument\r\n");
4754 SMARTLIST_FOREACH_BEGIN(flags
, const char *, flag
)
4756 if (!strcasecmp(flag
, discard_flag
)) {
4758 } else if (!strcasecmp(flag
, detach_flag
)) {
4760 } else if (!strcasecmp(flag
, max_s_close_flag
)) {
4761 max_streams_close_circuit
= 1;
4762 } else if (!strcasecmp(flag
, basicauth_flag
)) {
4763 auth_type
= REND_BASIC_AUTH
;
4764 } else if (!strcasecmp(flag
, non_anonymous_flag
)) {
4767 connection_printf_to_buf(conn
,
4768 "512 Invalid 'Flags' argument: %s\r\n",
4773 } SMARTLIST_FOREACH_END(flag
);
4774 SMARTLIST_FOREACH(flags
, char *, cp
, tor_free(cp
));
4775 smartlist_free(flags
);
4778 } else if (!strcasecmpstart(arg
, auth_prefix
)) {
4779 char *err_msg
= NULL
;
4781 rend_authorized_client_t
*client
=
4782 add_onion_helper_clientauth(arg
+ strlen(auth_prefix
),
4783 &created
, &err_msg
);
4786 connection_write_str_to_buf(err_msg
, conn
);
4792 if (auth_clients
!= NULL
) {
4794 SMARTLIST_FOREACH_BEGIN(auth_clients
, rend_authorized_client_t
*, ac
) {
4795 if (strcmp(ac
->client_name
, client
->client_name
) == 0) {
4799 } SMARTLIST_FOREACH_END(ac
);
4801 connection_printf_to_buf(conn
,
4802 "512 Duplicate name in ClientAuth\r\n");
4803 rend_authorized_client_free(client
);
4807 auth_clients
= smartlist_new();
4808 auth_created_clients
= smartlist_new();
4810 smartlist_add(auth_clients
, client
);
4812 smartlist_add(auth_created_clients
, client
);
4815 connection_printf_to_buf(conn
, "513 Invalid argument\r\n");
4819 if (smartlist_len(port_cfgs
) == 0) {
4820 connection_printf_to_buf(conn
, "512 Missing 'Port' argument\r\n");
4822 } else if (auth_type
== REND_NO_AUTH
&& auth_clients
!= NULL
) {
4823 connection_printf_to_buf(conn
, "512 No auth type specified\r\n");
4825 } else if (auth_type
!= REND_NO_AUTH
&& auth_clients
== NULL
) {
4826 connection_printf_to_buf(conn
, "512 No auth clients specified\r\n");
4828 } else if ((auth_type
== REND_BASIC_AUTH
&&
4829 smartlist_len(auth_clients
) > 512) ||
4830 (auth_type
== REND_STEALTH_AUTH
&&
4831 smartlist_len(auth_clients
) > 16)) {
4832 connection_printf_to_buf(conn
, "512 Too many auth clients\r\n");
4834 } else if (non_anonymous
!= rend_service_non_anonymous_mode_enabled(
4836 /* If we failed, and the non-anonymous flag is set, Tor must be in
4837 * anonymous hidden service mode.
4838 * The error message changes based on the current Tor config:
4839 * 512 Tor is in anonymous hidden service mode
4840 * 512 Tor is in non-anonymous hidden service mode
4841 * (I've deliberately written them out in full here to aid searchability.)
4843 connection_printf_to_buf(conn
, "512 Tor is in %sanonymous hidden service "
4845 non_anonymous
? "" : "non-");
4849 /* Parse the "keytype:keyblob" argument. */
4851 add_onion_secret_key_t pk
= { NULL
};
4852 const char *key_new_alg
= NULL
;
4853 char *key_new_blob
= NULL
;
4854 char *err_msg
= NULL
;
4856 if (add_onion_helper_keyarg(smartlist_get(args
, 0), discard_pk
,
4857 &key_new_alg
, &key_new_blob
, &pk
, &hs_version
,
4860 connection_write_str_to_buf(err_msg
, conn
);
4865 tor_assert(!err_msg
);
4867 /* Hidden service version 3 don't have client authentication support so if
4868 * ClientAuth was given, send back an error. */
4869 if (hs_version
== HS_VERSION_THREE
&& auth_clients
) {
4870 connection_printf_to_buf(conn
, "513 ClientAuth not supported\r\n");
4874 /* Create the HS, using private key pk, client authentication auth_type,
4875 * the list of auth_clients, and port config port_cfg.
4876 * rend_service_add_ephemeral() will take ownership of pk and port_cfg,
4877 * regardless of success/failure.
4879 char *service_id
= NULL
;
4880 int ret
= add_onion_helper_add_service(hs_version
, &pk
, port_cfgs
,
4882 max_streams_close_circuit
, auth_type
,
4883 auth_clients
, &service_id
);
4884 port_cfgs
= NULL
; /* port_cfgs is now owned by the rendservice code. */
4885 auth_clients
= NULL
; /* so is auth_clients */
4890 if (!detached_onion_services
)
4891 detached_onion_services
= smartlist_new();
4892 smartlist_add(detached_onion_services
, service_id
);
4894 if (!conn
->ephemeral_onion_services
)
4895 conn
->ephemeral_onion_services
= smartlist_new();
4896 smartlist_add(conn
->ephemeral_onion_services
, service_id
);
4899 tor_assert(service_id
);
4900 connection_printf_to_buf(conn
, "250-ServiceID=%s\r\n", service_id
);
4902 tor_assert(key_new_blob
);
4903 connection_printf_to_buf(conn
, "250-PrivateKey=%s:%s\r\n",
4904 key_new_alg
, key_new_blob
);
4906 if (auth_created_clients
) {
4907 SMARTLIST_FOREACH(auth_created_clients
, rend_authorized_client_t
*, ac
, {
4908 char *encoded
= rend_auth_encode_cookie(ac
->descriptor_cookie
,
4910 tor_assert(encoded
);
4911 connection_printf_to_buf(conn
, "250-ClientAuth=%s:%s\r\n",
4912 ac
->client_name
, encoded
);
4913 memwipe(encoded
, 0, strlen(encoded
));
4918 connection_printf_to_buf(conn
, "250 OK\r\n");
4921 case RSAE_BADPRIVKEY
:
4922 connection_printf_to_buf(conn
, "551 Failed to generate onion address\r\n");
4924 case RSAE_ADDREXISTS
:
4925 connection_printf_to_buf(conn
, "550 Onion address collision\r\n");
4927 case RSAE_BADVIRTPORT
:
4928 connection_printf_to_buf(conn
, "512 Invalid VIRTPORT/TARGET\r\n");
4931 connection_printf_to_buf(conn
, "512 Invalid client authorization\r\n");
4933 case RSAE_INTERNAL
: FALLTHROUGH
;
4935 connection_printf_to_buf(conn
, "551 Failed to add Onion Service\r\n");
4938 memwipe(key_new_blob
, 0, strlen(key_new_blob
));
4939 tor_free(key_new_blob
);
4944 SMARTLIST_FOREACH(port_cfgs
, rend_service_port_config_t
*, p
,
4945 rend_service_port_config_free(p
));
4946 smartlist_free(port_cfgs
);
4950 SMARTLIST_FOREACH(auth_clients
, rend_authorized_client_t
*, ac
,
4951 rend_authorized_client_free(ac
));
4952 smartlist_free(auth_clients
);
4954 if (auth_created_clients
) {
4955 // Do not free entries; they are the same as auth_clients
4956 smartlist_free(auth_created_clients
);
4959 SMARTLIST_FOREACH(args
, char *, cp
, {
4960 memwipe(cp
, 0, strlen(cp
));
4963 smartlist_free(args
);
4967 /** Helper function to handle parsing the KeyType:KeyBlob argument to the
4968 * ADD_ONION command. Return a new crypto_pk_t and if a new key was generated
4969 * and the private key not discarded, the algorithm and serialized private key,
4970 * or NULL and an optional control protocol error message on failure. The
4971 * caller is responsible for freeing the returned key_new_blob and err_msg.
4973 * Note: The error messages returned are deliberately vague to avoid echoing
4977 add_onion_helper_keyarg(const char *arg
, int discard_pk
,
4978 const char **key_new_alg_out
, char **key_new_blob_out
,
4979 add_onion_secret_key_t
*decoded_key
, int *hs_version
,
4982 smartlist_t
*key_args
= smartlist_new();
4983 crypto_pk_t
*pk
= NULL
;
4984 const char *key_new_alg
= NULL
;
4985 char *key_new_blob
= NULL
;
4986 char *err_msg
= NULL
;
4989 smartlist_split_string(key_args
, arg
, ":", SPLIT_IGNORE_BLANK
, 0);
4990 if (smartlist_len(key_args
) != 2) {
4991 err_msg
= tor_strdup("512 Invalid key type/blob\r\n");
4995 /* The format is "KeyType:KeyBlob". */
4996 static const char *key_type_new
= "NEW";
4997 static const char *key_type_best
= "BEST";
4998 static const char *key_type_rsa1024
= "RSA1024";
4999 static const char *key_type_ed25519_v3
= "ED25519-V3";
5001 const char *key_type
= smartlist_get(key_args
, 0);
5002 const char *key_blob
= smartlist_get(key_args
, 1);
5004 if (!strcasecmp(key_type_rsa1024
, key_type
)) {
5005 /* "RSA:<Base64 Blob>" - Loading a pre-existing RSA1024 key. */
5006 pk
= crypto_pk_base64_decode_private(key_blob
, strlen(key_blob
));
5008 err_msg
= tor_strdup("512 Failed to decode RSA key\r\n");
5011 if (crypto_pk_num_bits(pk
) != PK_BYTES
*8) {
5013 err_msg
= tor_strdup("512 Invalid RSA key size\r\n");
5016 decoded_key
->v2
= pk
;
5017 *hs_version
= HS_VERSION_TWO
;
5018 } else if (!strcasecmp(key_type_ed25519_v3
, key_type
)) {
5019 /* "ED25519-V3:<Base64 Blob>" - Loading a pre-existing ed25519 key. */
5020 ed25519_secret_key_t
*sk
= tor_malloc_zero(sizeof(*sk
));
5021 if (base64_decode((char *) sk
->seckey
, sizeof(sk
->seckey
), key_blob
,
5022 strlen(key_blob
)) != sizeof(sk
->seckey
)) {
5024 err_msg
= tor_strdup("512 Failed to decode ED25519-V3 key\r\n");
5027 decoded_key
->v3
= sk
;
5028 *hs_version
= HS_VERSION_THREE
;
5029 } else if (!strcasecmp(key_type_new
, key_type
)) {
5030 /* "NEW:<Algorithm>" - Generating a new key, blob as algorithm. */
5031 if (!strcasecmp(key_type_rsa1024
, key_blob
) ||
5032 !strcasecmp(key_type_best
, key_blob
)) {
5033 /* "RSA1024", RSA 1024 bit, also currently "BEST" by default. */
5034 pk
= crypto_pk_new();
5035 if (crypto_pk_generate_key(pk
)) {
5036 tor_asprintf(&err_msg
, "551 Failed to generate %s key\r\n",
5041 if (crypto_pk_base64_encode_private(pk
, &key_new_blob
)) {
5043 tor_asprintf(&err_msg
, "551 Failed to encode %s key\r\n",
5047 key_new_alg
= key_type_rsa1024
;
5049 decoded_key
->v2
= pk
;
5050 *hs_version
= HS_VERSION_TWO
;
5051 } else if (!strcasecmp(key_type_ed25519_v3
, key_blob
)) {
5052 ed25519_secret_key_t
*sk
= tor_malloc_zero(sizeof(*sk
));
5053 if (ed25519_secret_key_generate(sk
, 1) < 0) {
5055 tor_asprintf(&err_msg
, "551 Failed to generate %s key\r\n",
5056 key_type_ed25519_v3
);
5060 ssize_t len
= base64_encode_size(sizeof(sk
->seckey
), 0) + 1;
5061 key_new_blob
= tor_malloc_zero(len
);
5062 if (base64_encode(key_new_blob
, len
, (const char *) sk
->seckey
,
5063 sizeof(sk
->seckey
), 0) != (len
- 1)) {
5065 tor_free(key_new_blob
);
5066 tor_asprintf(&err_msg
, "551 Failed to encode %s key\r\n",
5067 key_type_ed25519_v3
);
5070 key_new_alg
= key_type_ed25519_v3
;
5072 decoded_key
->v3
= sk
;
5073 *hs_version
= HS_VERSION_THREE
;
5075 err_msg
= tor_strdup("513 Invalid key type\r\n");
5079 err_msg
= tor_strdup("513 Invalid key type\r\n");
5083 /* Succeeded in loading or generating a private key. */
5087 SMARTLIST_FOREACH(key_args
, char *, cp
, {
5088 memwipe(cp
, 0, strlen(cp
));
5091 smartlist_free(key_args
);
5094 *err_msg_out
= err_msg
;
5098 *key_new_alg_out
= key_new_alg
;
5099 *key_new_blob_out
= key_new_blob
;
5104 /** Helper function to handle parsing a ClientAuth argument to the
5105 * ADD_ONION command. Return a new rend_authorized_client_t, or NULL
5106 * and an optional control protocol error message on failure. The
5107 * caller is responsible for freeing the returned auth_client and err_msg.
5109 * If 'created' is specified, it will be set to 1 when a new cookie has
5112 STATIC rend_authorized_client_t
*
5113 add_onion_helper_clientauth(const char *arg
, int *created
, char **err_msg
)
5118 tor_assert(created
);
5119 tor_assert(err_msg
);
5122 smartlist_t
*auth_args
= smartlist_new();
5123 rend_authorized_client_t
*client
=
5124 tor_malloc_zero(sizeof(rend_authorized_client_t
));
5125 smartlist_split_string(auth_args
, arg
, ":", 0, 0);
5126 if (smartlist_len(auth_args
) < 1 || smartlist_len(auth_args
) > 2) {
5127 *err_msg
= tor_strdup("512 Invalid ClientAuth syntax\r\n");
5130 client
->client_name
= tor_strdup(smartlist_get(auth_args
, 0));
5131 if (smartlist_len(auth_args
) == 2) {
5132 char *decode_err_msg
= NULL
;
5133 if (rend_auth_decode_cookie(smartlist_get(auth_args
, 1),
5134 client
->descriptor_cookie
,
5135 NULL
, &decode_err_msg
) < 0) {
5136 tor_assert(decode_err_msg
);
5137 tor_asprintf(err_msg
, "512 %s\r\n", decode_err_msg
);
5138 tor_free(decode_err_msg
);
5143 crypto_rand((char *) client
->descriptor_cookie
, REND_DESC_COOKIE_LEN
);
5147 if (!rend_valid_client_name(client
->client_name
)) {
5148 *err_msg
= tor_strdup("512 Invalid name in ClientAuth\r\n");
5154 SMARTLIST_FOREACH(auth_args
, char *, item
, tor_free(item
));
5155 smartlist_free(auth_args
);
5157 rend_authorized_client_free(client
);
5163 /** Called when we get a DEL_ONION command; parse the body, and remove
5164 * the existing ephemeral Onion Service. */
5166 handle_control_del_onion(control_connection_t
*conn
,
5172 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
5173 args
= getargs_helper("DEL_ONION", conn
, body
, 1, 1);
5177 const char *service_id
= smartlist_get(args
, 0);
5178 if (rend_valid_v2_service_id(service_id
)) {
5179 hs_version
= HS_VERSION_TWO
;
5180 } else if (hs_address_is_valid(service_id
)) {
5181 hs_version
= HS_VERSION_THREE
;
5183 connection_printf_to_buf(conn
, "512 Malformed Onion Service id\r\n");
5187 /* Determine if the onion service belongs to this particular control
5188 * connection, or if it is in the global list of detached services. If it
5189 * is in neither, either the service ID is invalid in some way, or it
5190 * explicitly belongs to a different control connection, and an error
5191 * should be returned.
5193 smartlist_t
*services
[2] = {
5194 conn
->ephemeral_onion_services
,
5195 detached_onion_services
5197 smartlist_t
*onion_services
= NULL
;
5199 for (size_t i
= 0; i
< ARRAY_LENGTH(services
); i
++) {
5200 idx
= smartlist_string_pos(services
[i
], service_id
);
5202 onion_services
= services
[i
];
5206 if (onion_services
== NULL
) {
5207 connection_printf_to_buf(conn
, "552 Unknown Onion Service id\r\n");
5210 switch (hs_version
) {
5211 case HS_VERSION_TWO
:
5212 ret
= rend_service_del_ephemeral(service_id
);
5214 case HS_VERSION_THREE
:
5215 ret
= hs_service_del_ephemeral(service_id
);
5218 /* The ret value will be -1 thus hitting the warning below. This should
5219 * never happen because of the check at the start of the function. */
5223 /* This should *NEVER* fail, since the service is on either the
5224 * per-control connection list, or the global one.
5226 log_warn(LD_BUG
, "Failed to remove Onion Service %s.",
5227 escaped(service_id
));
5228 tor_fragile_assert();
5231 /* Remove/scrub the service_id from the appropriate list. */
5232 char *cp
= smartlist_get(onion_services
, idx
);
5233 smartlist_del(onion_services
, idx
);
5234 memwipe(cp
, 0, strlen(cp
));
5237 send_control_done(conn
);
5241 SMARTLIST_FOREACH(args
, char *, cp
, {
5242 memwipe(cp
, 0, strlen(cp
));
5245 smartlist_free(args
);
5249 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
5251 connection_control_finished_flushing(control_connection_t
*conn
)
5257 /** Called when <b>conn</b> has gotten its socket closed. */
5259 connection_control_reached_eof(control_connection_t
*conn
)
5263 log_info(LD_CONTROL
,"Control connection reached EOF. Closing.");
5264 connection_mark_for_close(TO_CONN(conn
));
5268 /** Shut down this Tor instance in the same way that SIGINT would, but
5269 * with a log message appropriate for the loss of an owning controller. */
5271 lost_owning_controller(const char *owner_type
, const char *loss_manner
)
5273 log_notice(LD_CONTROL
, "Owning controller %s has %s -- exiting now.",
5274 owner_type
, loss_manner
);
5276 activate_signal(SIGTERM
);
5279 /** Called when <b>conn</b> is being freed. */
5281 connection_control_closed(control_connection_t
*conn
)
5285 conn
->event_mask
= 0;
5286 control_update_global_event_mask();
5288 /* Close all ephemeral Onion Services if any.
5289 * The list and it's contents are scrubbed/freed in connection_free_.
5291 if (conn
->ephemeral_onion_services
) {
5292 SMARTLIST_FOREACH_BEGIN(conn
->ephemeral_onion_services
, char *, cp
) {
5293 if (rend_valid_v2_service_id(cp
)) {
5294 rend_service_del_ephemeral(cp
);
5295 } else if (hs_address_is_valid(cp
)) {
5296 hs_service_del_ephemeral(cp
);
5298 /* An invalid .onion in our list should NEVER happen */
5299 tor_fragile_assert();
5301 } SMARTLIST_FOREACH_END(cp
);
5304 if (conn
->is_owning_control_connection
) {
5305 lost_owning_controller("connection", "closed");
5309 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
5310 * stage of the protocol. */
5312 is_valid_initial_command(control_connection_t
*conn
, const char *cmd
)
5314 if (conn
->base_
.state
== CONTROL_CONN_STATE_OPEN
)
5316 if (!strcasecmp(cmd
, "PROTOCOLINFO"))
5317 return (!conn
->have_sent_protocolinfo
&&
5318 conn
->safecookie_client_hash
== NULL
);
5319 if (!strcasecmp(cmd
, "AUTHCHALLENGE"))
5320 return (conn
->safecookie_client_hash
== NULL
);
5321 if (!strcasecmp(cmd
, "AUTHENTICATE") ||
5322 !strcasecmp(cmd
, "QUIT"))
5327 /** Do not accept any control command of more than 1MB in length. Anything
5328 * that needs to be anywhere near this long probably means that one of our
5329 * interfaces is broken. */
5330 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
5332 /** Wrapper around peek_buf_has_control0 command: presents the same
5333 * interface as that underlying functions, but takes a connection_t intead of
5337 peek_connection_has_control0_command(connection_t
*conn
)
5339 return peek_buf_has_control0_command(conn
->inbuf
);
5343 peek_connection_has_http_command(connection_t
*conn
)
5345 return peek_buf_has_http_command(conn
->inbuf
);
5348 static const char CONTROLPORT_IS_NOT_AN_HTTP_PROXY_MSG
[] =
5349 "HTTP/1.0 501 Tor ControlPort is not an HTTP proxy"
5350 "\r\nContent-Type: text/html; charset=iso-8859-1\r\n\r\n"
5353 "<title>Tor's ControlPort is not an HTTP proxy</title>\n"
5356 "<h1>Tor's ControlPort is not an HTTP proxy</h1>\n"
5358 "It appears you have configured your web browser to use Tor's control port"
5359 " as an HTTP proxy.\n"
5360 "This is not correct: Tor's default SOCKS proxy port is 9050.\n"
5361 "Please configure your client accordingly.\n"
5364 "See <a href=\"https://www.torproject.org/documentation.html\">"
5365 "https://www.torproject.org/documentation.html</a> for more "
5367 "<!-- Plus this comment, to make the body response more than 512 bytes, so "
5368 " IE will be willing to display it. Comment comment comment comment "
5369 " comment comment comment comment comment comment comment comment.-->\n"
5374 /** Called when data has arrived on a v1 control connection: Try to fetch
5375 * commands from conn->inbuf, and execute them.
5378 connection_control_process_inbuf(control_connection_t
*conn
)
5381 uint32_t cmd_data_len
;
5386 tor_assert(conn
->base_
.state
== CONTROL_CONN_STATE_OPEN
||
5387 conn
->base_
.state
== CONTROL_CONN_STATE_NEEDAUTH
);
5389 if (!conn
->incoming_cmd
) {
5390 conn
->incoming_cmd
= tor_malloc(1024);
5391 conn
->incoming_cmd_len
= 1024;
5392 conn
->incoming_cmd_cur_len
= 0;
5395 if (conn
->base_
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
5396 peek_connection_has_control0_command(TO_CONN(conn
))) {
5397 /* Detect v0 commands and send a "no more v0" message. */
5400 set_uint16(buf
+2, htons(0x0000)); /* type == error */
5401 set_uint16(buf
+4, htons(0x0001)); /* code == internal error */
5402 strlcpy(buf
+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
5403 "and later; upgrade your controller.",
5405 body_len
= 2+strlen(buf
+6)+2; /* code, msg, nul. */
5406 set_uint16(buf
+0, htons(body_len
));
5407 connection_buf_add(buf
, 4+body_len
, TO_CONN(conn
));
5409 connection_mark_and_flush(TO_CONN(conn
));
5413 /* If the user has the HTTP proxy port and the control port confused. */
5414 if (conn
->base_
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
5415 peek_connection_has_http_command(TO_CONN(conn
))) {
5416 connection_write_str_to_buf(CONTROLPORT_IS_NOT_AN_HTTP_PROXY_MSG
, conn
);
5417 log_notice(LD_CONTROL
, "Received HTTP request on ControlPort");
5418 connection_mark_and_flush(TO_CONN(conn
));
5426 /* First, fetch a line. */
5428 data_len
= conn
->incoming_cmd_len
- conn
->incoming_cmd_cur_len
;
5429 r
= connection_buf_get_line(TO_CONN(conn
),
5430 conn
->incoming_cmd
+conn
->incoming_cmd_cur_len
,
5433 /* Line not all here yet. Wait. */
5436 if (data_len
+ conn
->incoming_cmd_cur_len
> MAX_COMMAND_LINE_LENGTH
) {
5437 connection_write_str_to_buf("500 Line too long.\r\n", conn
);
5438 connection_stop_reading(TO_CONN(conn
));
5439 connection_mark_and_flush(TO_CONN(conn
));
5441 while (conn
->incoming_cmd_len
< data_len
+conn
->incoming_cmd_cur_len
)
5442 conn
->incoming_cmd_len
*= 2;
5443 conn
->incoming_cmd
= tor_realloc(conn
->incoming_cmd
,
5444 conn
->incoming_cmd_len
);
5448 tor_assert(data_len
);
5450 last_idx
= conn
->incoming_cmd_cur_len
;
5451 conn
->incoming_cmd_cur_len
+= (int)data_len
;
5453 /* We have appended a line to incoming_cmd. Is the command done? */
5454 if (last_idx
== 0 && *conn
->incoming_cmd
!= '+')
5455 /* One line command, didn't start with '+'. */
5457 /* XXXX this code duplication is kind of dumb. */
5458 if (last_idx
+3 == conn
->incoming_cmd_cur_len
&&
5459 tor_memeq(conn
->incoming_cmd
+ last_idx
, ".\r\n", 3)) {
5460 /* Just appended ".\r\n"; we're done. Remove it. */
5461 conn
->incoming_cmd
[last_idx
] = '\0';
5462 conn
->incoming_cmd_cur_len
-= 3;
5464 } else if (last_idx
+2 == conn
->incoming_cmd_cur_len
&&
5465 tor_memeq(conn
->incoming_cmd
+ last_idx
, ".\n", 2)) {
5466 /* Just appended ".\n"; we're done. Remove it. */
5467 conn
->incoming_cmd
[last_idx
] = '\0';
5468 conn
->incoming_cmd_cur_len
-= 2;
5471 /* Otherwise, read another line. */
5473 data_len
= conn
->incoming_cmd_cur_len
;
5474 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
5478 while ((size_t)cmd_len
< data_len
5479 && !TOR_ISSPACE(conn
->incoming_cmd
[cmd_len
]))
5482 conn
->incoming_cmd
[cmd_len
]='\0';
5483 args
= conn
->incoming_cmd
+cmd_len
+1;
5484 tor_assert(data_len
>(size_t)cmd_len
);
5485 data_len
-= (cmd_len
+1); /* skip the command and NUL we added after it */
5486 while (TOR_ISSPACE(*args
)) {
5491 /* If the connection is already closing, ignore further commands */
5492 if (TO_CONN(conn
)->marked_for_close
) {
5496 /* Otherwise, Quit is always valid. */
5497 if (!strcasecmp(conn
->incoming_cmd
, "QUIT")) {
5498 connection_write_str_to_buf("250 closing connection\r\n", conn
);
5499 connection_mark_and_flush(TO_CONN(conn
));
5503 if (conn
->base_
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
5504 !is_valid_initial_command(conn
, conn
->incoming_cmd
)) {
5505 connection_write_str_to_buf("514 Authentication required.\r\n", conn
);
5506 connection_mark_for_close(TO_CONN(conn
));
5510 if (data_len
>= UINT32_MAX
) {
5511 connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn
);
5512 connection_mark_for_close(TO_CONN(conn
));
5516 /* XXXX Why is this not implemented as a table like the GETINFO
5517 * items are? Even handling the plus signs at the beginnings of
5518 * commands wouldn't be very hard with proper macros. */
5519 cmd_data_len
= (uint32_t)data_len
;
5520 if (!strcasecmp(conn
->incoming_cmd
, "SETCONF")) {
5521 if (handle_control_setconf(conn
, cmd_data_len
, args
))
5523 } else if (!strcasecmp(conn
->incoming_cmd
, "RESETCONF")) {
5524 if (handle_control_resetconf(conn
, cmd_data_len
, args
))
5526 } else if (!strcasecmp(conn
->incoming_cmd
, "GETCONF")) {
5527 if (handle_control_getconf(conn
, cmd_data_len
, args
))
5529 } else if (!strcasecmp(conn
->incoming_cmd
, "+LOADCONF")) {
5530 if (handle_control_loadconf(conn
, cmd_data_len
, args
))
5532 } else if (!strcasecmp(conn
->incoming_cmd
, "SETEVENTS")) {
5533 if (handle_control_setevents(conn
, cmd_data_len
, args
))
5535 } else if (!strcasecmp(conn
->incoming_cmd
, "AUTHENTICATE")) {
5536 if (handle_control_authenticate(conn
, cmd_data_len
, args
))
5538 } else if (!strcasecmp(conn
->incoming_cmd
, "SAVECONF")) {
5539 if (handle_control_saveconf(conn
, cmd_data_len
, args
))
5541 } else if (!strcasecmp(conn
->incoming_cmd
, "SIGNAL")) {
5542 if (handle_control_signal(conn
, cmd_data_len
, args
))
5544 } else if (!strcasecmp(conn
->incoming_cmd
, "TAKEOWNERSHIP")) {
5545 if (handle_control_takeownership(conn
, cmd_data_len
, args
))
5547 } else if (!strcasecmp(conn
->incoming_cmd
, "MAPADDRESS")) {
5548 if (handle_control_mapaddress(conn
, cmd_data_len
, args
))
5550 } else if (!strcasecmp(conn
->incoming_cmd
, "GETINFO")) {
5551 if (handle_control_getinfo(conn
, cmd_data_len
, args
))
5553 } else if (!strcasecmp(conn
->incoming_cmd
, "EXTENDCIRCUIT")) {
5554 if (handle_control_extendcircuit(conn
, cmd_data_len
, args
))
5556 } else if (!strcasecmp(conn
->incoming_cmd
, "SETCIRCUITPURPOSE")) {
5557 if (handle_control_setcircuitpurpose(conn
, cmd_data_len
, args
))
5559 } else if (!strcasecmp(conn
->incoming_cmd
, "SETROUTERPURPOSE")) {
5560 connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn
);
5561 } else if (!strcasecmp(conn
->incoming_cmd
, "ATTACHSTREAM")) {
5562 if (handle_control_attachstream(conn
, cmd_data_len
, args
))
5564 } else if (!strcasecmp(conn
->incoming_cmd
, "+POSTDESCRIPTOR")) {
5565 if (handle_control_postdescriptor(conn
, cmd_data_len
, args
))
5567 } else if (!strcasecmp(conn
->incoming_cmd
, "REDIRECTSTREAM")) {
5568 if (handle_control_redirectstream(conn
, cmd_data_len
, args
))
5570 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSESTREAM")) {
5571 if (handle_control_closestream(conn
, cmd_data_len
, args
))
5573 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSECIRCUIT")) {
5574 if (handle_control_closecircuit(conn
, cmd_data_len
, args
))
5576 } else if (!strcasecmp(conn
->incoming_cmd
, "USEFEATURE")) {
5577 if (handle_control_usefeature(conn
, cmd_data_len
, args
))
5579 } else if (!strcasecmp(conn
->incoming_cmd
, "RESOLVE")) {
5580 if (handle_control_resolve(conn
, cmd_data_len
, args
))
5582 } else if (!strcasecmp(conn
->incoming_cmd
, "PROTOCOLINFO")) {
5583 if (handle_control_protocolinfo(conn
, cmd_data_len
, args
))
5585 } else if (!strcasecmp(conn
->incoming_cmd
, "AUTHCHALLENGE")) {
5586 if (handle_control_authchallenge(conn
, cmd_data_len
, args
))
5588 } else if (!strcasecmp(conn
->incoming_cmd
, "DROPGUARDS")) {
5589 if (handle_control_dropguards(conn
, cmd_data_len
, args
))
5591 } else if (!strcasecmp(conn
->incoming_cmd
, "HSFETCH")) {
5592 if (handle_control_hsfetch(conn
, cmd_data_len
, args
))
5594 } else if (!strcasecmp(conn
->incoming_cmd
, "+HSPOST")) {
5595 if (handle_control_hspost(conn
, cmd_data_len
, args
))
5597 } else if (!strcasecmp(conn
->incoming_cmd
, "ADD_ONION")) {
5598 int ret
= handle_control_add_onion(conn
, cmd_data_len
, args
);
5599 memwipe(args
, 0, cmd_data_len
); /* Scrub the private key. */
5602 } else if (!strcasecmp(conn
->incoming_cmd
, "DEL_ONION")) {
5603 int ret
= handle_control_del_onion(conn
, cmd_data_len
, args
);
5604 memwipe(args
, 0, cmd_data_len
); /* Scrub the service id/pk. */
5608 connection_printf_to_buf(conn
, "510 Unrecognized command \"%s\"\r\n",
5609 conn
->incoming_cmd
);
5612 conn
->incoming_cmd_cur_len
= 0;
5616 /** Something major has happened to circuit <b>circ</b>: tell any
5617 * interested control connections. */
5619 control_event_circuit_status(origin_circuit_t
*circ
, circuit_status_event_t tp
,
5623 char reasons
[64] = "";
5624 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS
))
5630 case CIRC_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
5631 case CIRC_EVENT_BUILT
: status
= "BUILT"; break;
5632 case CIRC_EVENT_EXTENDED
: status
= "EXTENDED"; break;
5633 case CIRC_EVENT_FAILED
: status
= "FAILED"; break;
5634 case CIRC_EVENT_CLOSED
: status
= "CLOSED"; break;
5636 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
5637 tor_fragile_assert();
5641 if (tp
== CIRC_EVENT_FAILED
|| tp
== CIRC_EVENT_CLOSED
) {
5642 const char *reason_str
= circuit_end_reason_to_control_string(reason_code
);
5643 char unk_reason_buf
[16];
5645 tor_snprintf(unk_reason_buf
, 16, "UNKNOWN_%d", reason_code
);
5646 reason_str
= unk_reason_buf
;
5648 if (reason_code
> 0 && reason_code
& END_CIRC_REASON_FLAG_REMOTE
) {
5649 tor_snprintf(reasons
, sizeof(reasons
),
5650 " REASON=DESTROYED REMOTE_REASON=%s", reason_str
);
5652 tor_snprintf(reasons
, sizeof(reasons
),
5653 " REASON=%s", reason_str
);
5658 char *circdesc
= circuit_describe_status_for_controller(circ
);
5659 const char *sp
= strlen(circdesc
) ? " " : "";
5660 send_control_event(EVENT_CIRCUIT_STATUS
,
5661 "650 CIRC %lu %s%s%s%s\r\n",
5662 (unsigned long)circ
->global_identifier
,
5672 /** Something minor has happened to circuit <b>circ</b>: tell any
5673 * interested control connections. */
5675 control_event_circuit_status_minor(origin_circuit_t
*circ
,
5676 circuit_status_minor_event_t e
,
5677 int purpose
, const struct timeval
*tv
)
5679 const char *event_desc
;
5680 char event_tail
[160] = "";
5681 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR
))
5687 case CIRC_MINOR_EVENT_PURPOSE_CHANGED
:
5688 event_desc
= "PURPOSE_CHANGED";
5691 /* event_tail can currently be up to 68 chars long */
5692 const char *hs_state_str
=
5693 circuit_purpose_to_controller_hs_state_string(purpose
);
5694 tor_snprintf(event_tail
, sizeof(event_tail
),
5695 " OLD_PURPOSE=%s%s%s",
5696 circuit_purpose_to_controller_string(purpose
),
5697 (hs_state_str
!= NULL
) ? " OLD_HS_STATE=" : "",
5698 (hs_state_str
!= NULL
) ? hs_state_str
: "");
5702 case CIRC_MINOR_EVENT_CANNIBALIZED
:
5703 event_desc
= "CANNIBALIZED";
5706 /* event_tail can currently be up to 130 chars long */
5707 const char *hs_state_str
=
5708 circuit_purpose_to_controller_hs_state_string(purpose
);
5709 const struct timeval
*old_timestamp_began
= tv
;
5710 char tbuf
[ISO_TIME_USEC_LEN
+1];
5711 format_iso_time_nospace_usec(tbuf
, old_timestamp_began
);
5713 tor_snprintf(event_tail
, sizeof(event_tail
),
5714 " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
5715 circuit_purpose_to_controller_string(purpose
),
5716 (hs_state_str
!= NULL
) ? " OLD_HS_STATE=" : "",
5717 (hs_state_str
!= NULL
) ? hs_state_str
: "",
5723 log_warn(LD_BUG
, "Unrecognized status code %d", (int)e
);
5724 tor_fragile_assert();
5729 char *circdesc
= circuit_describe_status_for_controller(circ
);
5730 const char *sp
= strlen(circdesc
) ? " " : "";
5731 send_control_event(EVENT_CIRCUIT_STATUS_MINOR
,
5732 "650 CIRC_MINOR %lu %s%s%s%s\r\n",
5733 (unsigned long)circ
->global_identifier
,
5744 * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
5745 * interested controllers.
5748 control_event_circuit_purpose_changed(origin_circuit_t
*circ
,
5751 return control_event_circuit_status_minor(circ
,
5752 CIRC_MINOR_EVENT_PURPOSE_CHANGED
,
5758 * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
5759 * created-time from <b>old_tv_created</b>: tell any interested controllers.
5762 control_event_circuit_cannibalized(origin_circuit_t
*circ
,
5764 const struct timeval
*old_tv_created
)
5766 return control_event_circuit_status_minor(circ
,
5767 CIRC_MINOR_EVENT_CANNIBALIZED
,
5772 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
5773 * <b>buf</b>, determine the address:port combination requested on
5774 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
5777 write_stream_target_to_buf(entry_connection_t
*conn
, char *buf
, size_t len
)
5780 if (conn
->chosen_exit_name
)
5781 if (tor_snprintf(buf2
, sizeof(buf2
), ".%s.exit", conn
->chosen_exit_name
)<0)
5783 if (!conn
->socks_request
)
5785 if (tor_snprintf(buf
, len
, "%s%s%s:%d",
5786 conn
->socks_request
->address
,
5787 conn
->chosen_exit_name
? buf2
: "",
5788 !conn
->chosen_exit_name
&& connection_edge_is_rendezvous_stream(
5789 ENTRY_TO_EDGE_CONN(conn
)) ? ".onion" : "",
5790 conn
->socks_request
->port
)<0)
5795 /** Something has happened to the stream associated with AP connection
5796 * <b>conn</b>: tell any interested control connections. */
5798 control_event_stream_status(entry_connection_t
*conn
, stream_status_event_t tp
,
5801 char reason_buf
[64];
5802 char addrport_buf
[64];
5805 origin_circuit_t
*origin_circ
= NULL
;
5807 const char *purpose
= "";
5808 tor_assert(conn
->socks_request
);
5810 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS
))
5813 if (tp
== STREAM_EVENT_CLOSED
&&
5814 (reason_code
& END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
))
5817 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
5819 reason_buf
[0] = '\0';
5822 case STREAM_EVENT_SENT_CONNECT
: status
= "SENTCONNECT"; break;
5823 case STREAM_EVENT_SENT_RESOLVE
: status
= "SENTRESOLVE"; break;
5824 case STREAM_EVENT_SUCCEEDED
: status
= "SUCCEEDED"; break;
5825 case STREAM_EVENT_FAILED
: status
= "FAILED"; break;
5826 case STREAM_EVENT_CLOSED
: status
= "CLOSED"; break;
5827 case STREAM_EVENT_NEW
: status
= "NEW"; break;
5828 case STREAM_EVENT_NEW_RESOLVE
: status
= "NEWRESOLVE"; break;
5829 case STREAM_EVENT_FAILED_RETRIABLE
: status
= "DETACHED"; break;
5830 case STREAM_EVENT_REMAP
: status
= "REMAP"; break;
5832 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
5835 if (reason_code
&& (tp
== STREAM_EVENT_FAILED
||
5836 tp
== STREAM_EVENT_CLOSED
||
5837 tp
== STREAM_EVENT_FAILED_RETRIABLE
)) {
5838 const char *reason_str
= stream_end_reason_to_control_string(reason_code
);
5841 tor_asprintf(&r
, " UNKNOWN_%d", reason_code
);
5844 if (reason_code
& END_STREAM_REASON_FLAG_REMOTE
)
5845 tor_snprintf(reason_buf
, sizeof(reason_buf
),
5846 " REASON=END REMOTE_REASON=%s", reason_str
);
5848 tor_snprintf(reason_buf
, sizeof(reason_buf
),
5849 " REASON=%s", reason_str
);
5851 } else if (reason_code
&& tp
== STREAM_EVENT_REMAP
) {
5852 switch (reason_code
) {
5853 case REMAP_STREAM_SOURCE_CACHE
:
5854 strlcpy(reason_buf
, " SOURCE=CACHE", sizeof(reason_buf
));
5856 case REMAP_STREAM_SOURCE_EXIT
:
5857 strlcpy(reason_buf
, " SOURCE=EXIT", sizeof(reason_buf
));
5860 tor_snprintf(reason_buf
, sizeof(reason_buf
), " REASON=UNKNOWN_%d",
5862 /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
5867 if (tp
== STREAM_EVENT_NEW
|| tp
== STREAM_EVENT_NEW_RESOLVE
) {
5869 * When the control conn is an AF_UNIX socket and we have no address,
5870 * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
5873 if (strcmp(ENTRY_TO_CONN(conn
)->address
, "(Tor_internal)") != 0) {
5874 tor_snprintf(addrport_buf
,sizeof(addrport_buf
), " SOURCE_ADDR=%s:%d",
5875 ENTRY_TO_CONN(conn
)->address
, ENTRY_TO_CONN(conn
)->port
);
5878 * else leave it blank so control on AF_UNIX doesn't need to make
5881 addrport_buf
[0] = '\0';
5884 addrport_buf
[0] = '\0';
5887 if (tp
== STREAM_EVENT_NEW_RESOLVE
) {
5888 purpose
= " PURPOSE=DNS_REQUEST";
5889 } else if (tp
== STREAM_EVENT_NEW
) {
5890 if (conn
->use_begindir
) {
5891 connection_t
*linked
= ENTRY_TO_CONN(conn
)->linked_conn
;
5892 int linked_dir_purpose
= -1;
5893 if (linked
&& linked
->type
== CONN_TYPE_DIR
)
5894 linked_dir_purpose
= linked
->purpose
;
5895 if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose
))
5896 purpose
= " PURPOSE=DIR_UPLOAD";
5898 purpose
= " PURPOSE=DIR_FETCH";
5900 purpose
= " PURPOSE=USER";
5903 circ
= circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn
));
5904 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
5905 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
5906 send_control_event(EVENT_STREAM_STATUS
,
5907 "650 STREAM %"PRIu64
" %s %lu %s%s%s%s\r\n",
5908 (ENTRY_TO_CONN(conn
)->global_identifier
),
5911 (unsigned long)origin_circ
->global_identifier
: 0ul,
5912 buf
, reason_buf
, addrport_buf
, purpose
);
5914 /* XXX need to specify its intended exit, etc? */
5919 /** Figure out the best name for the target router of an OR connection
5920 * <b>conn</b>, and write it into the <b>len</b>-character buffer
5923 orconn_target_get_name(char *name
, size_t len
, or_connection_t
*conn
)
5925 const node_t
*node
= node_get_by_id(conn
->identity_digest
);
5927 tor_assert(len
> MAX_VERBOSE_NICKNAME_LEN
);
5928 node_get_verbose_nickname(node
, name
);
5929 } else if (! tor_digest_is_zero(conn
->identity_digest
)) {
5931 base16_encode(name
+1, len
-1, conn
->identity_digest
,
5934 tor_snprintf(name
, len
, "%s:%d",
5935 conn
->base_
.address
, conn
->base_
.port
);
5939 /** Called when the status of an OR connection <b>conn</b> changes: tell any
5940 * interested control connections. <b>tp</b> is the new status for the
5941 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
5942 * may be the reason why.
5945 control_event_or_conn_status(or_connection_t
*conn
, or_conn_status_event_t tp
,
5951 char ncircs_buf
[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
5953 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS
))
5958 case OR_CONN_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
5959 case OR_CONN_EVENT_CONNECTED
: status
= "CONNECTED"; break;
5960 case OR_CONN_EVENT_FAILED
: status
= "FAILED"; break;
5961 case OR_CONN_EVENT_CLOSED
: status
= "CLOSED"; break;
5962 case OR_CONN_EVENT_NEW
: status
= "NEW"; break;
5964 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
5968 ncircs
= circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn
->chan
));
5972 ncircs
+= connection_or_get_num_circuits(conn
);
5973 if (ncircs
&& (tp
== OR_CONN_EVENT_FAILED
|| tp
== OR_CONN_EVENT_CLOSED
)) {
5974 tor_snprintf(ncircs_buf
, sizeof(ncircs_buf
), " NCIRCS=%d", ncircs
);
5977 orconn_target_get_name(name
, sizeof(name
), conn
);
5978 send_control_event(EVENT_OR_CONN_STATUS
,
5979 "650 ORCONN %s %s%s%s%s ID=%"PRIu64
"\r\n",
5981 reason
? " REASON=" : "",
5982 orconn_end_reason_to_control_string(reason
),
5984 (conn
->base_
.global_identifier
));
5990 * Print out STREAM_BW event for a single conn
5993 control_event_stream_bandwidth(edge_connection_t
*edge_conn
)
5996 char tbuf
[ISO_TIME_USEC_LEN
+1];
5997 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED
)) {
5998 if (!edge_conn
->n_read
&& !edge_conn
->n_written
)
6001 tor_gettimeofday(&now
);
6002 format_iso_time_nospace_usec(tbuf
, &now
);
6003 send_control_event(EVENT_STREAM_BANDWIDTH_USED
,
6004 "650 STREAM_BW %"PRIu64
" %lu %lu %s\r\n",
6005 (edge_conn
->base_
.global_identifier
),
6006 (unsigned long)edge_conn
->n_read
,
6007 (unsigned long)edge_conn
->n_written
,
6010 edge_conn
->n_written
= edge_conn
->n_read
= 0;
6016 /** A second or more has elapsed: tell any interested control
6017 * connections how much bandwidth streams have used. */
6019 control_event_stream_bandwidth_used(void)
6021 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED
)) {
6022 smartlist_t
*conns
= get_connection_array();
6023 edge_connection_t
*edge_conn
;
6025 char tbuf
[ISO_TIME_USEC_LEN
+1];
6027 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
)
6029 if (conn
->type
!= CONN_TYPE_AP
)
6031 edge_conn
= TO_EDGE_CONN(conn
);
6032 if (!edge_conn
->n_read
&& !edge_conn
->n_written
)
6035 tor_gettimeofday(&now
);
6036 format_iso_time_nospace_usec(tbuf
, &now
);
6037 send_control_event(EVENT_STREAM_BANDWIDTH_USED
,
6038 "650 STREAM_BW %"PRIu64
" %lu %lu %s\r\n",
6039 (edge_conn
->base_
.global_identifier
),
6040 (unsigned long)edge_conn
->n_read
,
6041 (unsigned long)edge_conn
->n_written
,
6044 edge_conn
->n_written
= edge_conn
->n_read
= 0;
6046 SMARTLIST_FOREACH_END(conn
);
6052 /** A second or more has elapsed: tell any interested control connections
6053 * how much bandwidth origin circuits have used. */
6055 control_event_circ_bandwidth_used(void)
6057 if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED
))
6060 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t
*, circ
) {
6061 if (!CIRCUIT_IS_ORIGIN(circ
))
6064 control_event_circ_bandwidth_used_for_circ(TO_ORIGIN_CIRCUIT(circ
));
6066 SMARTLIST_FOREACH_END(circ
);
6072 * Emit a CIRC_BW event line for a specific circuit.
6074 * This function sets the values it emits to 0, and does not emit
6075 * an event if there is no new data to report since the last call.
6077 * Therefore, it may be called at any frequency.
6080 control_event_circ_bandwidth_used_for_circ(origin_circuit_t
*ocirc
)
6083 char tbuf
[ISO_TIME_USEC_LEN
+1];
6087 if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED
))
6090 /* n_read_circ_bw and n_written_circ_bw are always updated
6091 * when there is any new cell on a circuit, and set to 0 after
6094 * Therefore, checking them is sufficient to determine if there
6095 * is new data to report. */
6096 if (!ocirc
->n_read_circ_bw
&& !ocirc
->n_written_circ_bw
)
6099 tor_gettimeofday(&now
);
6100 format_iso_time_nospace_usec(tbuf
, &now
);
6101 send_control_event(EVENT_CIRC_BANDWIDTH_USED
,
6102 "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu TIME=%s "
6103 "DELIVERED_READ=%lu OVERHEAD_READ=%lu "
6104 "DELIVERED_WRITTEN=%lu OVERHEAD_WRITTEN=%lu\r\n",
6105 ocirc
->global_identifier
,
6106 (unsigned long)ocirc
->n_read_circ_bw
,
6107 (unsigned long)ocirc
->n_written_circ_bw
,
6109 (unsigned long)ocirc
->n_delivered_read_circ_bw
,
6110 (unsigned long)ocirc
->n_overhead_read_circ_bw
,
6111 (unsigned long)ocirc
->n_delivered_written_circ_bw
,
6112 (unsigned long)ocirc
->n_overhead_written_circ_bw
);
6113 ocirc
->n_written_circ_bw
= ocirc
->n_read_circ_bw
= 0;
6114 ocirc
->n_overhead_written_circ_bw
= ocirc
->n_overhead_read_circ_bw
= 0;
6115 ocirc
->n_delivered_written_circ_bw
= ocirc
->n_delivered_read_circ_bw
= 0;
6120 /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
6121 * bandwidth counters. */
6123 control_event_conn_bandwidth(connection_t
*conn
)
6125 const char *conn_type_str
;
6126 if (!get_options()->TestingEnableConnBwEvent
||
6127 !EVENT_IS_INTERESTING(EVENT_CONN_BW
))
6129 if (!conn
->n_read_conn_bw
&& !conn
->n_written_conn_bw
)
6131 switch (conn
->type
) {
6133 conn_type_str
= "OR";
6136 conn_type_str
= "DIR";
6138 case CONN_TYPE_EXIT
:
6139 conn_type_str
= "EXIT";
6144 send_control_event(EVENT_CONN_BW
,
6145 "650 CONN_BW ID=%"PRIu64
" TYPE=%s "
6146 "READ=%lu WRITTEN=%lu\r\n",
6147 (conn
->global_identifier
),
6149 (unsigned long)conn
->n_read_conn_bw
,
6150 (unsigned long)conn
->n_written_conn_bw
);
6151 conn
->n_written_conn_bw
= conn
->n_read_conn_bw
= 0;
6155 /** A second or more has elapsed: tell any interested control
6156 * connections how much bandwidth connections have used. */
6158 control_event_conn_bandwidth_used(void)
6160 if (get_options()->TestingEnableConnBwEvent
&&
6161 EVENT_IS_INTERESTING(EVENT_CONN_BW
)) {
6162 SMARTLIST_FOREACH(get_connection_array(), connection_t
*, conn
,
6163 control_event_conn_bandwidth(conn
));
6168 /** Helper: iterate over cell statistics of <b>circ</b> and sum up added
6169 * cells, removed cells, and waiting times by cell command and direction.
6170 * Store results in <b>cell_stats</b>. Free cell statistics of the
6171 * circuit afterwards. */
6173 sum_up_cell_stats_by_command(circuit_t
*circ
, cell_stats_t
*cell_stats
)
6175 memset(cell_stats
, 0, sizeof(cell_stats_t
));
6176 SMARTLIST_FOREACH_BEGIN(circ
->testing_cell_stats
,
6177 const testing_cell_stats_entry_t
*, ent
) {
6178 tor_assert(ent
->command
<= CELL_COMMAND_MAX_
);
6179 if (!ent
->removed
&& !ent
->exitward
) {
6180 cell_stats
->added_cells_appward
[ent
->command
] += 1;
6181 } else if (!ent
->removed
&& ent
->exitward
) {
6182 cell_stats
->added_cells_exitward
[ent
->command
] += 1;
6183 } else if (!ent
->exitward
) {
6184 cell_stats
->removed_cells_appward
[ent
->command
] += 1;
6185 cell_stats
->total_time_appward
[ent
->command
] += ent
->waiting_time
* 10;
6187 cell_stats
->removed_cells_exitward
[ent
->command
] += 1;
6188 cell_stats
->total_time_exitward
[ent
->command
] += ent
->waiting_time
* 10;
6190 } SMARTLIST_FOREACH_END(ent
);
6191 circuit_clear_testing_cell_stats(circ
);
6194 /** Helper: append a cell statistics string to <code>event_parts</code>,
6195 * prefixed with <code>key</code>=. Statistics consist of comma-separated
6196 * key:value pairs with lower-case command strings as keys and cell
6197 * numbers or total waiting times as values. A key:value pair is included
6198 * if the entry in <code>include_if_non_zero</code> is not zero, but with
6199 * the (possibly zero) entry from <code>number_to_include</code>. Both
6200 * arrays are expected to have a length of CELL_COMMAND_MAX_ + 1. If no
6201 * entry in <code>include_if_non_zero</code> is positive, no string will
6202 * be added to <code>event_parts</code>. */
6204 append_cell_stats_by_command(smartlist_t
*event_parts
, const char *key
,
6205 const uint64_t *include_if_non_zero
,
6206 const uint64_t *number_to_include
)
6208 smartlist_t
*key_value_strings
= smartlist_new();
6210 for (i
= 0; i
<= CELL_COMMAND_MAX_
; i
++) {
6211 if (include_if_non_zero
[i
] > 0) {
6212 smartlist_add_asprintf(key_value_strings
, "%s:%"PRIu64
,
6213 cell_command_to_string(i
),
6214 (number_to_include
[i
]));
6217 if (smartlist_len(key_value_strings
) > 0) {
6218 char *joined
= smartlist_join_strings(key_value_strings
, ",", 0, NULL
);
6219 smartlist_add_asprintf(event_parts
, "%s=%s", key
, joined
);
6220 SMARTLIST_FOREACH(key_value_strings
, char *, cp
, tor_free(cp
));
6223 smartlist_free(key_value_strings
);
6226 /** Helper: format <b>cell_stats</b> for <b>circ</b> for inclusion in a
6227 * CELL_STATS event and write result string to <b>event_string</b>. */
6229 format_cell_stats(char **event_string
, circuit_t
*circ
,
6230 cell_stats_t
*cell_stats
)
6232 smartlist_t
*event_parts
= smartlist_new();
6233 if (CIRCUIT_IS_ORIGIN(circ
)) {
6234 origin_circuit_t
*ocirc
= TO_ORIGIN_CIRCUIT(circ
);
6235 smartlist_add_asprintf(event_parts
, "ID=%lu",
6236 (unsigned long)ocirc
->global_identifier
);
6237 } else if (TO_OR_CIRCUIT(circ
)->p_chan
) {
6238 or_circuit_t
*or_circ
= TO_OR_CIRCUIT(circ
);
6239 smartlist_add_asprintf(event_parts
, "InboundQueue=%lu",
6240 (unsigned long)or_circ
->p_circ_id
);
6241 smartlist_add_asprintf(event_parts
, "InboundConn=%"PRIu64
,
6242 (or_circ
->p_chan
->global_identifier
));
6243 append_cell_stats_by_command(event_parts
, "InboundAdded",
6244 cell_stats
->added_cells_appward
,
6245 cell_stats
->added_cells_appward
);
6246 append_cell_stats_by_command(event_parts
, "InboundRemoved",
6247 cell_stats
->removed_cells_appward
,
6248 cell_stats
->removed_cells_appward
);
6249 append_cell_stats_by_command(event_parts
, "InboundTime",
6250 cell_stats
->removed_cells_appward
,
6251 cell_stats
->total_time_appward
);
6254 smartlist_add_asprintf(event_parts
, "OutboundQueue=%lu",
6255 (unsigned long)circ
->n_circ_id
);
6256 smartlist_add_asprintf(event_parts
, "OutboundConn=%"PRIu64
,
6257 (circ
->n_chan
->global_identifier
));
6258 append_cell_stats_by_command(event_parts
, "OutboundAdded",
6259 cell_stats
->added_cells_exitward
,
6260 cell_stats
->added_cells_exitward
);
6261 append_cell_stats_by_command(event_parts
, "OutboundRemoved",
6262 cell_stats
->removed_cells_exitward
,
6263 cell_stats
->removed_cells_exitward
);
6264 append_cell_stats_by_command(event_parts
, "OutboundTime",
6265 cell_stats
->removed_cells_exitward
,
6266 cell_stats
->total_time_exitward
);
6268 *event_string
= smartlist_join_strings(event_parts
, " ", 0, NULL
);
6269 SMARTLIST_FOREACH(event_parts
, char *, cp
, tor_free(cp
));
6270 smartlist_free(event_parts
);
6273 /** A second or more has elapsed: tell any interested control connection
6274 * how many cells have been processed for a given circuit. */
6276 control_event_circuit_cell_stats(void)
6278 cell_stats_t
*cell_stats
;
6280 if (!get_options()->TestingEnableCellStatsEvent
||
6281 !EVENT_IS_INTERESTING(EVENT_CELL_STATS
))
6283 cell_stats
= tor_malloc(sizeof(cell_stats_t
));
6284 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t
*, circ
) {
6285 if (!circ
->testing_cell_stats
)
6287 sum_up_cell_stats_by_command(circ
, cell_stats
);
6288 format_cell_stats(&event_string
, circ
, cell_stats
);
6289 send_control_event(EVENT_CELL_STATS
,
6290 "650 CELL_STATS %s\r\n", event_string
);
6291 tor_free(event_string
);
6293 SMARTLIST_FOREACH_END(circ
);
6294 tor_free(cell_stats
);
6298 /* about 5 minutes worth. */
6299 #define N_BW_EVENTS_TO_CACHE 300
6300 /* Index into cached_bw_events to next write. */
6301 static int next_measurement_idx
= 0;
6302 /* number of entries set in n_measurements */
6303 static int n_measurements
= 0;
6304 static struct cached_bw_event_s
{
6307 } cached_bw_events
[N_BW_EVENTS_TO_CACHE
];
6309 /** A second or more has elapsed: tell any interested control
6310 * connections how much bandwidth we used. */
6312 control_event_bandwidth_used(uint32_t n_read
, uint32_t n_written
)
6314 cached_bw_events
[next_measurement_idx
].n_read
= n_read
;
6315 cached_bw_events
[next_measurement_idx
].n_written
= n_written
;
6316 if (++next_measurement_idx
== N_BW_EVENTS_TO_CACHE
)
6317 next_measurement_idx
= 0;
6318 if (n_measurements
< N_BW_EVENTS_TO_CACHE
)
6321 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED
)) {
6322 send_control_event(EVENT_BANDWIDTH_USED
,
6323 "650 BW %lu %lu\r\n",
6324 (unsigned long)n_read
,
6325 (unsigned long)n_written
);
6332 get_bw_samples(void)
6335 int idx
= (next_measurement_idx
+ N_BW_EVENTS_TO_CACHE
- n_measurements
)
6336 % N_BW_EVENTS_TO_CACHE
;
6337 tor_assert(0 <= idx
&& idx
< N_BW_EVENTS_TO_CACHE
);
6339 smartlist_t
*elements
= smartlist_new();
6341 for (i
= 0; i
< n_measurements
; ++i
) {
6342 tor_assert(0 <= idx
&& idx
< N_BW_EVENTS_TO_CACHE
);
6343 const struct cached_bw_event_s
*bwe
= &cached_bw_events
[idx
];
6345 smartlist_add_asprintf(elements
, "%u,%u",
6346 (unsigned)bwe
->n_read
,
6347 (unsigned)bwe
->n_written
);
6349 idx
= (idx
+ 1) % N_BW_EVENTS_TO_CACHE
;
6352 char *result
= smartlist_join_strings(elements
, " ", 0, NULL
);
6354 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
6355 smartlist_free(elements
);
6360 /** Called when we are sending a log message to the controllers: suspend
6361 * sending further log messages to the controllers until we're done. Used by
6362 * CONN_LOG_PROTECT. */
6364 disable_control_logging(void)
6366 ++disable_log_messages
;
6369 /** We're done sending a log message to the controllers: re-enable controller
6370 * logging. Used by CONN_LOG_PROTECT. */
6372 enable_control_logging(void)
6374 if (--disable_log_messages
< 0)
6378 /** We got a log message: tell any interested control connections. */
6380 control_event_logmsg(int severity
, uint32_t domain
, const char *msg
)
6384 /* Don't even think of trying to add stuff to a buffer from a cpuworker
6385 * thread. (See #25987 for plan to fix.) */
6386 if (! in_main_thread())
6389 if (disable_log_messages
)
6392 if (domain
== LD_BUG
&& EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
) &&
6393 severity
<= LOG_NOTICE
) {
6394 char *esc
= esc_for_log(msg
);
6395 ++disable_log_messages
;
6396 control_event_general_status(severity
, "BUG REASON=%s", esc
);
6397 --disable_log_messages
;
6401 event
= log_severity_to_event(severity
);
6402 if (event
>= 0 && EVENT_IS_INTERESTING(event
)) {
6405 if (strchr(msg
, '\n')) {
6407 b
= tor_strdup(msg
);
6408 for (cp
= b
; *cp
; ++cp
)
6409 if (*cp
== '\r' || *cp
== '\n')
6413 case LOG_DEBUG
: s
= "DEBUG"; break;
6414 case LOG_INFO
: s
= "INFO"; break;
6415 case LOG_NOTICE
: s
= "NOTICE"; break;
6416 case LOG_WARN
: s
= "WARN"; break;
6417 case LOG_ERR
: s
= "ERR"; break;
6418 default: s
= "UnknownLogSeverity"; break;
6420 ++disable_log_messages
;
6421 send_control_event(event
, "650 %s %s\r\n", s
, b
?b
:msg
);
6422 if (severity
== LOG_ERR
) {
6423 /* Force a flush, since we may be about to die horribly */
6424 queued_events_flush_all(1);
6426 --disable_log_messages
;
6432 * Logging callback: called when there is a queued pending log callback.
6435 control_event_logmsg_pending(void)
6437 if (! in_main_thread()) {
6438 /* We can't handle this case yet, since we're using a
6439 * mainloop_event_t to invoke queued_events_flush_all. We ought to
6440 * use a different mechanism instead: see #25987.
6444 tor_assert(flush_queued_events_event
);
6445 mainloop_event_activate(flush_queued_events_event
);
6448 /** Called whenever we receive new router descriptors: tell any
6449 * interested control connections. <b>routers</b> is a list of
6453 control_event_descriptors_changed(smartlist_t
*routers
)
6457 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC
))
6461 smartlist_t
*names
= smartlist_new();
6463 SMARTLIST_FOREACH(routers
, routerinfo_t
*, ri
, {
6464 char *b
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
6465 router_get_verbose_nickname(b
, ri
);
6466 smartlist_add(names
, b
);
6468 ids
= smartlist_join_strings(names
, " ", 0, NULL
);
6469 tor_asprintf(&msg
, "650 NEWDESC %s\r\n", ids
);
6470 send_control_event_string(EVENT_NEW_DESC
, msg
);
6473 SMARTLIST_FOREACH(names
, char *, cp
, tor_free(cp
));
6474 smartlist_free(names
);
6479 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
6480 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
6481 * <b>error</b> is non-NULL, it is an error code describing the failure
6482 * mode of the mapping.
6485 control_event_address_mapped(const char *from
, const char *to
, time_t expires
,
6486 const char *error
, const int cached
)
6488 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP
))
6491 if (expires
< 3 || expires
== TIME_MAX
)
6492 send_control_event(EVENT_ADDRMAP
,
6493 "650 ADDRMAP %s %s NEVER %s%s"
6494 "CACHED=\"%s\"\r\n",
6495 from
, to
, error
?error
:"", error
?" ":"",
6498 char buf
[ISO_TIME_LEN
+1];
6499 char buf2
[ISO_TIME_LEN
+1];
6500 format_local_iso_time(buf
,expires
);
6501 format_iso_time(buf2
,expires
);
6502 send_control_event(EVENT_ADDRMAP
,
6503 "650 ADDRMAP %s %s \"%s\""
6504 " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
6506 error
?error
:"", error
?" ":"",
6507 buf2
, cached
?"YES":"NO");
6513 /** Cached liveness for network liveness events and GETINFO
6516 static int network_is_live
= 0;
6519 get_cached_network_liveness(void)
6521 return network_is_live
;
6525 set_cached_network_liveness(int liveness
)
6527 network_is_live
= liveness
;
6530 /** The network liveness has changed; this is called from circuitstats.c
6531 * whenever we receive a cell, or when timeout expires and we assume the
6532 * network is down. */
6534 control_event_network_liveness_update(int liveness
)
6537 if (get_cached_network_liveness() <= 0) {
6538 /* Update cached liveness */
6539 set_cached_network_liveness(1);
6540 log_debug(LD_CONTROL
, "Sending NETWORK_LIVENESS UP");
6541 send_control_event_string(EVENT_NETWORK_LIVENESS
,
6542 "650 NETWORK_LIVENESS UP\r\n");
6544 /* else was already live, no-op */
6546 if (get_cached_network_liveness() > 0) {
6547 /* Update cached liveness */
6548 set_cached_network_liveness(0);
6549 log_debug(LD_CONTROL
, "Sending NETWORK_LIVENESS DOWN");
6550 send_control_event_string(EVENT_NETWORK_LIVENESS
,
6551 "650 NETWORK_LIVENESS DOWN\r\n");
6553 /* else was already dead, no-op */
6559 /** Helper function for NS-style events. Constructs and sends an event
6560 * of type <b>event</b> with string <b>event_string</b> out of the set of
6561 * networkstatuses <b>statuses</b>. Currently it is used for NS events
6562 * and NEWCONSENSUS events. */
6564 control_event_networkstatus_changed_helper(smartlist_t
*statuses
,
6566 const char *event_string
)
6569 char *s
, *esc
= NULL
;
6570 if (!EVENT_IS_INTERESTING(event
) || !smartlist_len(statuses
))
6573 strs
= smartlist_new();
6574 smartlist_add_strdup(strs
, "650+");
6575 smartlist_add_strdup(strs
, event_string
);
6576 smartlist_add_strdup(strs
, "\r\n");
6577 SMARTLIST_FOREACH(statuses
, const routerstatus_t
*, rs
,
6579 s
= networkstatus_getinfo_helper_single(rs
);
6581 smartlist_add(strs
, s
);
6584 s
= smartlist_join_strings(strs
, "", 0, NULL
);
6585 write_escaped_data(s
, strlen(s
), &esc
);
6586 SMARTLIST_FOREACH(strs
, char *, cp
, tor_free(cp
));
6587 smartlist_free(strs
);
6589 send_control_event_string(event
, esc
);
6590 send_control_event_string(event
,
6597 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
6598 * an NS event to any controller that cares. */
6600 control_event_networkstatus_changed(smartlist_t
*statuses
)
6602 return control_event_networkstatus_changed_helper(statuses
, EVENT_NS
, "NS");
6605 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
6606 * event consisting of an NS-style line for each relay in the consensus. */
6608 control_event_newconsensus(const networkstatus_t
*consensus
)
6610 if (!control_event_is_interesting(EVENT_NEWCONSENSUS
))
6612 return control_event_networkstatus_changed_helper(
6613 consensus
->routerstatus_list
, EVENT_NEWCONSENSUS
, "NEWCONSENSUS");
6616 /** Called when we compute a new circuitbuildtimeout */
6618 control_event_buildtimeout_set(buildtimeout_set_event_t type
,
6621 const char *type_string
= NULL
;
6623 if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET
))
6627 case BUILDTIMEOUT_SET_EVENT_COMPUTED
:
6628 type_string
= "COMPUTED";
6630 case BUILDTIMEOUT_SET_EVENT_RESET
:
6631 type_string
= "RESET";
6633 case BUILDTIMEOUT_SET_EVENT_SUSPENDED
:
6634 type_string
= "SUSPENDED";
6636 case BUILDTIMEOUT_SET_EVENT_DISCARD
:
6637 type_string
= "DISCARD";
6639 case BUILDTIMEOUT_SET_EVENT_RESUME
:
6640 type_string
= "RESUME";
6643 type_string
= "UNKNOWN";
6647 send_control_event(EVENT_BUILDTIMEOUT_SET
,
6648 "650 BUILDTIMEOUT_SET %s %s\r\n",
6654 /** Called when a signal has been processed from signal_callback */
6656 control_event_signal(uintptr_t signal_num
)
6658 const char *signal_string
= NULL
;
6660 if (!control_event_is_interesting(EVENT_GOT_SIGNAL
))
6663 switch (signal_num
) {
6665 signal_string
= "RELOAD";
6668 signal_string
= "DUMP";
6671 signal_string
= "DEBUG";
6674 signal_string
= "NEWNYM";
6676 case SIGCLEARDNSCACHE
:
6677 signal_string
= "CLEARDNSCACHE";
6680 signal_string
= "HEARTBEAT";
6683 log_warn(LD_BUG
, "Unrecognized signal %lu in control_event_signal",
6684 (unsigned long)signal_num
);
6688 send_control_event(EVENT_GOT_SIGNAL
, "650 SIGNAL %s\r\n",
6693 /** Called when a single local_routerstatus_t has changed: Sends an NS event
6694 * to any controller that cares. */
6696 control_event_networkstatus_changed_single(const routerstatus_t
*rs
)
6698 smartlist_t
*statuses
;
6701 if (!EVENT_IS_INTERESTING(EVENT_NS
))
6704 statuses
= smartlist_new();
6705 smartlist_add(statuses
, (void*)rs
);
6706 r
= control_event_networkstatus_changed(statuses
);
6707 smartlist_free(statuses
);
6711 /** Our own router descriptor has changed; tell any controllers that care.
6714 control_event_my_descriptor_changed(void)
6716 send_control_event(EVENT_DESCCHANGED
, "650 DESCCHANGED\r\n");
6720 /** Helper: sends a status event where <b>type</b> is one of
6721 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
6722 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
6723 * string corresponding to <b>args</b>. */
6725 control_event_status(int type
, int severity
, const char *format
, va_list args
)
6727 char *user_buf
= NULL
;
6728 char format_buf
[160];
6729 const char *status
, *sev
;
6732 case EVENT_STATUS_GENERAL
:
6733 status
= "STATUS_GENERAL";
6735 case EVENT_STATUS_CLIENT
:
6736 status
= "STATUS_CLIENT";
6738 case EVENT_STATUS_SERVER
:
6739 status
= "STATUS_SERVER";
6742 log_warn(LD_BUG
, "Unrecognized status type %d", type
);
6756 log_warn(LD_BUG
, "Unrecognized status severity %d", severity
);
6759 if (tor_snprintf(format_buf
, sizeof(format_buf
), "650 %s %s",
6761 log_warn(LD_BUG
, "Format string too long.");
6764 tor_vasprintf(&user_buf
, format
, args
);
6766 send_control_event(type
, "%s %s\r\n", format_buf
, user_buf
);
6771 #define CONTROL_EVENT_STATUS_BODY(event, sev) \
6775 if (!EVENT_IS_INTERESTING(event)) \
6778 va_start(ap, format); \
6779 r = control_event_status((event), (sev), format, ap); \
6783 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
6784 * by formatting the arguments using the printf-style <b>format</b>. */
6786 control_event_general_status(int severity
, const char *format
, ...)
6788 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL
, severity
);
6792 /** Format and send an EVENT_STATUS_GENERAL LOG_ERR event, and flush it to the
6793 * controller(s) immediately. */
6795 control_event_general_error(const char *format
, ...)
6797 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL
, LOG_ERR
);
6798 /* Force a flush, since we may be about to die horribly */
6799 queued_events_flush_all(1);
6803 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
6804 * by formatting the arguments using the printf-style <b>format</b>. */
6806 control_event_client_status(int severity
, const char *format
, ...)
6808 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT
, severity
);
6812 /** Format and send an EVENT_STATUS_CLIENT LOG_ERR event, and flush it to the
6813 * controller(s) immediately. */
6815 control_event_client_error(const char *format
, ...)
6817 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT
, LOG_ERR
);
6818 /* Force a flush, since we may be about to die horribly */
6819 queued_events_flush_all(1);
6823 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
6824 * by formatting the arguments using the printf-style <b>format</b>. */
6826 control_event_server_status(int severity
, const char *format
, ...)
6828 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER
, severity
);
6832 /** Format and send an EVENT_STATUS_SERVER LOG_ERR event, and flush it to the
6833 * controller(s) immediately. */
6835 control_event_server_error(const char *format
, ...)
6837 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER
, LOG_ERR
);
6838 /* Force a flush, since we may be about to die horribly */
6839 queued_events_flush_all(1);
6843 /** Called when the status of an entry guard with the given <b>nickname</b>
6844 * and identity <b>digest</b> has changed to <b>status</b>: tells any
6845 * controllers that care. */
6847 control_event_guard(const char *nickname
, const char *digest
,
6850 char hbuf
[HEX_DIGEST_LEN
+1];
6851 base16_encode(hbuf
, sizeof(hbuf
), digest
, DIGEST_LEN
);
6852 if (!EVENT_IS_INTERESTING(EVENT_GUARD
))
6856 char buf
[MAX_VERBOSE_NICKNAME_LEN
+1];
6857 const node_t
*node
= node_get_by_id(digest
);
6859 node_get_verbose_nickname(node
, buf
);
6861 tor_snprintf(buf
, sizeof(buf
), "$%s~%s", hbuf
, nickname
);
6863 send_control_event(EVENT_GUARD
,
6864 "650 GUARD ENTRY %s %s\r\n", buf
, status
);
6869 /** Called when a configuration option changes. This is generally triggered
6870 * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
6871 * a smartlist_t containing (key, value, ...) pairs in sequence.
6872 * <b>value</b> can be NULL. */
6874 control_event_conf_changed(const smartlist_t
*elements
)
6879 if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED
) ||
6880 smartlist_len(elements
) == 0) {
6883 lines
= smartlist_new();
6884 for (i
= 0; i
< smartlist_len(elements
); i
+= 2) {
6885 char *k
= smartlist_get(elements
, i
);
6886 char *v
= smartlist_get(elements
, i
+1);
6888 smartlist_add_asprintf(lines
, "650-%s", k
);
6890 smartlist_add_asprintf(lines
, "650-%s=%s", k
, v
);
6893 result
= smartlist_join_strings(lines
, "\r\n", 0, NULL
);
6894 send_control_event(EVENT_CONF_CHANGED
,
6895 "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result
);
6897 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
6898 smartlist_free(lines
);
6902 /** Helper: Return a newly allocated string containing a path to the
6903 * file where we store our authentication cookie. */
6905 get_controller_cookie_file_name(void)
6907 const or_options_t
*options
= get_options();
6908 if (options
->CookieAuthFile
&& strlen(options
->CookieAuthFile
)) {
6909 return tor_strdup(options
->CookieAuthFile
);
6911 return get_datadir_fname("control_auth_cookie");
6915 /* Initialize the cookie-based authentication system of the
6916 * ControlPort. If <b>enabled</b> is 0, then disable the cookie
6917 * authentication system. */
6919 init_control_cookie_authentication(int enabled
)
6925 authentication_cookie_is_set
= 0;
6929 fname
= get_controller_cookie_file_name();
6930 retval
= init_cookie_authentication(fname
, "", /* no header */
6931 AUTHENTICATION_COOKIE_LEN
,
6932 get_options()->CookieAuthFileGroupReadable
,
6933 &authentication_cookie
,
6934 &authentication_cookie_is_set
);
6939 /** A copy of the process specifier of Tor's owning controller, or
6940 * NULL if this Tor instance is not currently owned by a process. */
6941 static char *owning_controller_process_spec
= NULL
;
6943 /** A process-termination monitor for Tor's owning controller, or NULL
6944 * if this Tor instance is not currently owned by a process. */
6945 static tor_process_monitor_t
*owning_controller_process_monitor
= NULL
;
6947 /** Process-termination monitor callback for Tor's owning controller
6950 owning_controller_procmon_cb(void *unused
)
6954 lost_owning_controller("process", "vanished");
6957 /** Set <b>process_spec</b> as Tor's owning controller process.
6958 * Exit on failure. */
6960 monitor_owning_controller_process(const char *process_spec
)
6964 tor_assert((owning_controller_process_spec
== NULL
) ==
6965 (owning_controller_process_monitor
== NULL
));
6967 if (owning_controller_process_spec
!= NULL
) {
6968 if ((process_spec
!= NULL
) && !strcmp(process_spec
,
6969 owning_controller_process_spec
)) {
6970 /* Same process -- return now, instead of disposing of and
6971 * recreating the process-termination monitor. */
6975 /* We are currently owned by a process, and we should no longer be
6976 * owned by it. Free the process-termination monitor. */
6977 tor_process_monitor_free(owning_controller_process_monitor
);
6978 owning_controller_process_monitor
= NULL
;
6980 tor_free(owning_controller_process_spec
);
6981 owning_controller_process_spec
= NULL
;
6984 tor_assert((owning_controller_process_spec
== NULL
) &&
6985 (owning_controller_process_monitor
== NULL
));
6987 if (process_spec
== NULL
)
6990 owning_controller_process_spec
= tor_strdup(process_spec
);
6991 owning_controller_process_monitor
=
6992 tor_process_monitor_new(tor_libevent_get_base(),
6993 owning_controller_process_spec
,
6995 owning_controller_procmon_cb
, NULL
,
6998 if (owning_controller_process_monitor
== NULL
) {
6999 log_err(LD_BUG
, "Couldn't create process-termination monitor for "
7000 "owning controller: %s. Exiting.",
7002 owning_controller_process_spec
= NULL
;
7003 tor_shutdown_event_loop_and_exit(1);
7007 /** Convert the name of a bootstrapping phase <b>s</b> into strings
7008 * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
7010 bootstrap_status_to_string(bootstrap_status_t s
, const char **tag
,
7011 const char **summary
)
7014 case BOOTSTRAP_STATUS_UNDEF
:
7016 *summary
= "Undefined";
7018 case BOOTSTRAP_STATUS_STARTING
:
7020 *summary
= "Starting";
7022 case BOOTSTRAP_STATUS_CONN_DIR
:
7024 *summary
= "Connecting to directory server";
7026 case BOOTSTRAP_STATUS_HANDSHAKE
:
7027 *tag
= "status_handshake";
7028 *summary
= "Finishing handshake";
7030 case BOOTSTRAP_STATUS_HANDSHAKE_DIR
:
7031 *tag
= "handshake_dir";
7032 *summary
= "Finishing handshake with directory server";
7034 case BOOTSTRAP_STATUS_ONEHOP_CREATE
:
7035 *tag
= "onehop_create";
7036 *summary
= "Establishing an encrypted directory connection";
7038 case BOOTSTRAP_STATUS_REQUESTING_STATUS
:
7039 *tag
= "requesting_status";
7040 *summary
= "Asking for networkstatus consensus";
7042 case BOOTSTRAP_STATUS_LOADING_STATUS
:
7043 *tag
= "loading_status";
7044 *summary
= "Loading networkstatus consensus";
7046 case BOOTSTRAP_STATUS_LOADING_KEYS
:
7047 *tag
= "loading_keys";
7048 *summary
= "Loading authority key certs";
7050 case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS
:
7051 *tag
= "requesting_descriptors";
7052 /* XXXX this appears to incorrectly report internal on most loads */
7053 *summary
= router_have_consensus_path() == CONSENSUS_PATH_INTERNAL
?
7054 "Asking for relay descriptors for internal paths" :
7055 "Asking for relay descriptors";
7057 /* If we're sure there are no exits in the consensus,
7058 * inform the controller by adding "internal"
7059 * to the status summaries.
7060 * (We only check this while loading descriptors,
7061 * so we may not know in the earlier stages.)
7062 * But if there are exits, we can't be sure whether
7063 * we're creating internal or exit paths/circuits.
7064 * XXXX Or should be use different tags or statuses
7065 * for internal and exit/all? */
7066 case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS
:
7067 *tag
= "loading_descriptors";
7068 *summary
= router_have_consensus_path() == CONSENSUS_PATH_INTERNAL
?
7069 "Loading relay descriptors for internal paths" :
7070 "Loading relay descriptors";
7072 case BOOTSTRAP_STATUS_CONN_OR
:
7074 *summary
= router_have_consensus_path() == CONSENSUS_PATH_INTERNAL
?
7075 "Connecting to the Tor network internally" :
7076 "Connecting to the Tor network";
7078 case BOOTSTRAP_STATUS_HANDSHAKE_OR
:
7079 *tag
= "handshake_or";
7080 *summary
= router_have_consensus_path() == CONSENSUS_PATH_INTERNAL
?
7081 "Finishing handshake with first hop of internal circuit" :
7082 "Finishing handshake with first hop";
7084 case BOOTSTRAP_STATUS_CIRCUIT_CREATE
:
7085 *tag
= "circuit_create";
7086 *summary
= router_have_consensus_path() == CONSENSUS_PATH_INTERNAL
?
7087 "Establishing an internal Tor circuit" :
7088 "Establishing a Tor circuit";
7090 case BOOTSTRAP_STATUS_DONE
:
7095 // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
7096 *tag
= *summary
= "unknown";
7102 /** What percentage through the bootstrap process are we? We remember
7103 * this so we can avoid sending redundant bootstrap status events, and
7104 * so we can guess context for the bootstrap messages which are
7105 * ambiguous. It starts at 'undef', but gets set to 'starting' while
7106 * Tor initializes. */
7107 static int bootstrap_percent
= BOOTSTRAP_STATUS_UNDEF
;
7109 /** Like bootstrap_percent, but only takes on the enumerated values in
7110 * bootstrap_status_t.
7112 static int bootstrap_phase
= BOOTSTRAP_STATUS_UNDEF
;
7114 /** As bootstrap_percent, but holds the bootstrapping level at which we last
7115 * logged a NOTICE-level message. We use this, plus BOOTSTRAP_PCT_INCREMENT,
7116 * to avoid flooding the log with a new message every time we get a few more
7117 * microdescriptors */
7118 static int notice_bootstrap_percent
= 0;
7120 /** How many problems have we had getting to the next bootstrapping phase?
7121 * These include failure to establish a connection to a Tor relay,
7122 * failures to finish the TLS handshake, failures to validate the
7123 * consensus document, etc. */
7124 static int bootstrap_problems
= 0;
7126 /** We only tell the controller once we've hit a threshold of problems
7127 * for the current phase. */
7128 #define BOOTSTRAP_PROBLEM_THRESHOLD 10
7130 /** When our bootstrapping progress level changes, but our bootstrapping
7131 * status has not advanced, we only log at NOTICE when we have made at least
7132 * this much progress.
7134 #define BOOTSTRAP_PCT_INCREMENT 5
7136 /** Do the actual logging and notifications for
7137 * control_event_bootstrap(). Doesn't change any state beyond that.
7140 control_event_bootstrap_core(int loglevel
, bootstrap_status_t status
,
7143 char buf
[BOOTSTRAP_MSG_LEN
];
7144 const char *tag
, *summary
;
7146 bootstrap_status_to_string(status
, &tag
, &summary
);
7147 /* Locally reset status if there's incremental progress */
7151 tor_log(loglevel
, LD_CONTROL
,
7152 "Bootstrapped %d%%: %s", status
, summary
);
7153 tor_snprintf(buf
, sizeof(buf
),
7154 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
7155 status
, tag
, summary
);
7156 tor_snprintf(last_sent_bootstrap_message
,
7157 sizeof(last_sent_bootstrap_message
),
7159 control_event_client_status(LOG_NOTICE
, "%s", buf
);
7162 /** Called when Tor has made progress at bootstrapping its directory
7163 * information and initial circuits.
7165 * <b>status</b> is the new status, that is, what task we will be doing
7166 * next. <b>progress</b> is zero if we just started this task, else it
7167 * represents progress on the task.
7170 control_event_bootstrap(bootstrap_status_t status
, int progress
)
7172 int loglevel
= LOG_NOTICE
;
7174 if (bootstrap_percent
== BOOTSTRAP_STATUS_DONE
)
7175 return; /* already bootstrapped; nothing to be done here. */
7177 /* special case for handshaking status, since our TLS handshaking code
7178 * can't distinguish what the connection is going to be for. */
7179 if (status
== BOOTSTRAP_STATUS_HANDSHAKE
) {
7180 if (bootstrap_percent
< BOOTSTRAP_STATUS_CONN_OR
) {
7181 status
= BOOTSTRAP_STATUS_HANDSHAKE_DIR
;
7183 status
= BOOTSTRAP_STATUS_HANDSHAKE_OR
;
7187 if (status
<= bootstrap_percent
) {
7188 /* If there's no new progress, return early. */
7189 if (!progress
|| progress
<= bootstrap_percent
)
7191 /* Log at INFO if not enough progress happened. */
7192 if (progress
< notice_bootstrap_percent
+ BOOTSTRAP_PCT_INCREMENT
)
7193 loglevel
= LOG_INFO
;
7196 control_event_bootstrap_core(loglevel
, status
, progress
);
7198 if (status
> bootstrap_percent
) {
7199 bootstrap_phase
= status
; /* new milestone reached */
7200 bootstrap_percent
= status
;
7202 if (progress
> bootstrap_percent
) {
7203 /* incremental progress within a milestone */
7204 bootstrap_percent
= progress
;
7205 bootstrap_problems
= 0; /* Progress! Reset our problem counter. */
7207 if (loglevel
== LOG_NOTICE
&&
7208 bootstrap_percent
> notice_bootstrap_percent
) {
7209 /* Remember that we gave a notice at this level. */
7210 notice_bootstrap_percent
= bootstrap_percent
;
7214 /** Flag whether we've opened an OR_CONN yet */
7215 static int bootstrap_first_orconn
= 0;
7217 /** Like bootstrap_phase, but for (possibly deferred) directory progress */
7218 static int bootstrap_dir_phase
= BOOTSTRAP_STATUS_UNDEF
;
7220 /** Like bootstrap_problems, but for (possibly deferred) directory progress */
7221 static int bootstrap_dir_progress
= BOOTSTRAP_STATUS_UNDEF
;
7223 /** Defer directory info bootstrap events until we have successfully
7224 * completed our first connection to a router. */
7226 control_event_boot_dir(bootstrap_status_t status
, int progress
)
7228 if (status
> bootstrap_dir_progress
) {
7229 bootstrap_dir_progress
= status
;
7230 bootstrap_dir_phase
= status
;
7232 if (progress
&& progress
>= bootstrap_dir_progress
) {
7233 bootstrap_dir_progress
= progress
;
7236 /* Don't report unless we have successfully opened at least one OR_CONN */
7237 if (!bootstrap_first_orconn
)
7240 control_event_bootstrap(status
, progress
);
7243 /** Set a flag to allow reporting of directory bootstrap progress.
7244 * (Code that reports completion of an OR_CONN calls this.) Also,
7245 * report directory progress so far. */
7247 control_event_boot_first_orconn(void)
7249 bootstrap_first_orconn
= 1;
7250 control_event_bootstrap(bootstrap_dir_phase
, bootstrap_dir_progress
);
7253 /** Called when Tor has failed to make bootstrapping progress in a way
7254 * that indicates a problem. <b>warn</b> gives a human-readable hint
7255 * as to why, and <b>reason</b> provides a controller-facing short
7256 * tag. <b>conn</b> is the connection that caused this problem and
7257 * can be NULL if a connection cannot be easily identified.
7260 control_event_bootstrap_problem(const char *warn
, const char *reason
,
7261 const connection_t
*conn
, int dowarn
)
7263 int status
= bootstrap_percent
;
7264 const char *tag
= "", *summary
= "";
7265 char buf
[BOOTSTRAP_MSG_LEN
];
7266 const char *recommendation
= "ignore";
7268 char *or_id
= NULL
, *hostaddr
= NULL
;
7269 or_connection_t
*or_conn
= NULL
;
7271 /* bootstrap_percent must not be in "undefined" state here. */
7272 tor_assert(status
>= 0);
7274 if (bootstrap_percent
== 100)
7275 return; /* already bootstrapped; nothing to be done here. */
7277 bootstrap_problems
++;
7279 if (bootstrap_problems
>= BOOTSTRAP_PROBLEM_THRESHOLD
)
7282 /* Don't warn about our bootstrapping status if we are hibernating or
7284 if (we_are_hibernating())
7287 tor_assert(bootstrap_status_to_string(bootstrap_phase
, &tag
, &summary
) == 0);
7289 severity
= dowarn
? LOG_WARN
: LOG_INFO
;
7292 recommendation
= "warn";
7294 if (conn
&& conn
->type
== CONN_TYPE_OR
) {
7295 /* XXX TO_OR_CONN can't deal with const */
7296 or_conn
= TO_OR_CONN((connection_t
*)conn
);
7297 or_id
= tor_strdup(hex_str(or_conn
->identity_digest
, DIGEST_LEN
));
7299 or_id
= tor_strdup("?");
7303 tor_asprintf(&hostaddr
, "%s:%d", conn
->address
, (int)conn
->port
);
7305 hostaddr
= tor_strdup("?");
7308 LD_CONTROL
, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
7309 "count %d; recommendation %s; host %s at %s)",
7310 status
, summary
, warn
, reason
,
7311 bootstrap_problems
, recommendation
,
7314 connection_or_report_broken_states(severity
, LD_HANDSHAKE
);
7316 tor_snprintf(buf
, sizeof(buf
),
7317 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
7318 "COUNT=%d RECOMMENDATION=%s HOSTID=\"%s\" HOSTADDR=\"%s\"",
7319 bootstrap_percent
, tag
, summary
, warn
, reason
, bootstrap_problems
,
7323 tor_snprintf(last_sent_bootstrap_message
,
7324 sizeof(last_sent_bootstrap_message
),
7326 control_event_client_status(LOG_WARN
, "%s", buf
);
7332 /** Called when Tor has failed to make bootstrapping progress in a way
7333 * that indicates a problem. <b>warn</b> gives a hint as to why, and
7334 * <b>reason</b> provides an "or_conn_end_reason" tag. <b>or_conn</b>
7335 * is the connection that caused this problem.
7338 control_event_bootstrap_prob_or
, (const char *warn
, int reason
,
7339 or_connection_t
*or_conn
))
7343 if (or_conn
->have_noted_bootstrap_problem
)
7346 or_conn
->have_noted_bootstrap_problem
= 1;
7348 if (reason
== END_OR_CONN_REASON_NO_ROUTE
)
7351 /* If we are using bridges and all our OR connections are now
7352 closed, it means that we totally failed to connect to our
7353 bridges. Throw a warning. */
7354 if (get_options()->UseBridges
&& !any_other_active_or_conns(or_conn
))
7357 control_event_bootstrap_problem(warn
,
7358 orconn_end_reason_to_control_string(reason
),
7359 TO_CONN(or_conn
), dowarn
);
7362 /** We just generated a new summary of which countries we've seen clients
7363 * from recently. Send a copy to the controller in case it wants to
7364 * display it for the user. */
7366 control_event_clients_seen(const char *controller_str
)
7368 send_control_event(EVENT_CLIENTS_SEEN
,
7369 "650 CLIENTS_SEEN %s\r\n", controller_str
);
7372 /** A new pluggable transport called <b>transport_name</b> was
7373 * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
7374 * "server" or "client" depending on the mode of the pluggable
7376 * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
7379 control_event_transport_launched(const char *mode
, const char *transport_name
,
7380 tor_addr_t
*addr
, uint16_t port
)
7382 send_control_event(EVENT_TRANSPORT_LAUNCHED
,
7383 "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
7384 mode
, transport_name
, fmt_addr(addr
), port
);
7387 /** Convert rendezvous auth type to string for HS_DESC control events
7390 rend_auth_type_to_string(rend_auth_type_t auth_type
)
7394 switch (auth_type
) {
7398 case REND_BASIC_AUTH
:
7401 case REND_STEALTH_AUTH
:
7402 str
= "STEALTH_AUTH";
7411 /** Return a longname the node whose identity is <b>id_digest</b>. If
7412 * node_get_by_id() returns NULL, base 16 encoding of <b>id_digest</b> is
7415 * This function is not thread-safe. Each call to this function invalidates
7416 * previous values returned by this function.
7418 MOCK_IMPL(const char *,
7419 node_describe_longname_by_id
,(const char *id_digest
))
7421 static char longname
[MAX_VERBOSE_NICKNAME_LEN
+1];
7422 node_get_verbose_nickname_by_id(id_digest
, longname
);
7426 /** Return either the onion address if the given pointer is a non empty
7427 * string else the unknown string. */
7429 rend_hsaddress_str_or_unknown(const char *onion_address
)
7431 static const char *str_unknown
= "UNKNOWN";
7432 const char *str_ret
= str_unknown
;
7434 /* No valid pointer, unknown it is. */
7435 if (!onion_address
) {
7438 /* Empty onion address thus we don't know, unknown it is. */
7439 if (onion_address
[0] == '\0') {
7442 /* All checks are good so return the given onion address. */
7443 str_ret
= onion_address
;
7449 /** send HS_DESC requested event.
7451 * <b>rend_query</b> is used to fetch requested onion address and auth type.
7452 * <b>hs_dir</b> is the description of contacting hs directory.
7453 * <b>desc_id_base32</b> is the ID of requested hs descriptor.
7454 * <b>hsdir_index</b> is the HSDir fetch index value for v3, an hex string.
7457 control_event_hs_descriptor_requested(const char *onion_address
,
7458 rend_auth_type_t auth_type
,
7459 const char *id_digest
,
7460 const char *desc_id
,
7461 const char *hsdir_index
)
7463 char *hsdir_index_field
= NULL
;
7465 if (BUG(!id_digest
|| !desc_id
)) {
7470 tor_asprintf(&hsdir_index_field
, " HSDIR_INDEX=%s", hsdir_index
);
7473 send_control_event(EVENT_HS_DESC
,
7474 "650 HS_DESC REQUESTED %s %s %s %s%s\r\n",
7475 rend_hsaddress_str_or_unknown(onion_address
),
7476 rend_auth_type_to_string(auth_type
),
7477 node_describe_longname_by_id(id_digest
),
7479 hsdir_index_field
? hsdir_index_field
: "");
7480 tor_free(hsdir_index_field
);
7483 /** For an HS descriptor query <b>rend_data</b>, using the
7484 * <b>onion_address</b> and HSDir fingerprint <b>hsdir_fp</b>, find out
7485 * which descriptor ID in the query is the right one.
7487 * Return a pointer of the binary descriptor ID found in the query's object
7488 * or NULL if not found. */
7490 get_desc_id_from_query(const rend_data_t
*rend_data
, const char *hsdir_fp
)
7493 const char *desc_id
= NULL
;
7494 const rend_data_v2_t
*rend_data_v2
= TO_REND_DATA_V2(rend_data
);
7496 /* Possible if the fetch was done using a descriptor ID. This means that
7497 * the HSFETCH command was used. */
7498 if (!tor_digest_is_zero(rend_data_v2
->desc_id_fetch
)) {
7499 desc_id
= rend_data_v2
->desc_id_fetch
;
7503 /* Without a directory fingerprint at this stage, we can't do much. */
7504 if (hsdir_fp
== NULL
) {
7508 /* OK, we have an onion address so now let's find which descriptor ID
7509 * is the one associated with the HSDir fingerprint. */
7510 for (replica
= 0; replica
< REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS
;
7512 const char *digest
= rend_data_get_desc_id(rend_data
, replica
, NULL
);
7514 SMARTLIST_FOREACH_BEGIN(rend_data
->hsdirs_fp
, char *, fingerprint
) {
7515 if (tor_memcmp(fingerprint
, hsdir_fp
, DIGEST_LEN
) == 0) {
7516 /* Found it! This descriptor ID is the right one. */
7520 } SMARTLIST_FOREACH_END(fingerprint
);
7527 /** send HS_DESC CREATED event when a local service generates a descriptor.
7529 * <b>onion_address</b> is service address.
7530 * <b>desc_id</b> is the descriptor ID.
7531 * <b>replica</b> is the the descriptor replica number. If it is negative, it
7535 control_event_hs_descriptor_created(const char *onion_address
,
7536 const char *desc_id
,
7539 char *replica_field
= NULL
;
7541 if (BUG(!onion_address
|| !desc_id
)) {
7546 tor_asprintf(&replica_field
, " REPLICA=%d", replica
);
7549 send_control_event(EVENT_HS_DESC
,
7550 "650 HS_DESC CREATED %s UNKNOWN UNKNOWN %s%s\r\n",
7551 onion_address
, desc_id
,
7552 replica_field
? replica_field
: "");
7553 tor_free(replica_field
);
7556 /** send HS_DESC upload event.
7558 * <b>onion_address</b> is service address.
7559 * <b>hs_dir</b> is the description of contacting hs directory.
7560 * <b>desc_id</b> is the ID of requested hs descriptor.
7563 control_event_hs_descriptor_upload(const char *onion_address
,
7564 const char *id_digest
,
7565 const char *desc_id
,
7566 const char *hsdir_index
)
7568 char *hsdir_index_field
= NULL
;
7570 if (BUG(!onion_address
|| !id_digest
|| !desc_id
)) {
7575 tor_asprintf(&hsdir_index_field
, " HSDIR_INDEX=%s", hsdir_index
);
7578 send_control_event(EVENT_HS_DESC
,
7579 "650 HS_DESC UPLOAD %s UNKNOWN %s %s%s\r\n",
7581 node_describe_longname_by_id(id_digest
),
7583 hsdir_index_field
? hsdir_index_field
: "");
7584 tor_free(hsdir_index_field
);
7587 /** send HS_DESC event after got response from hs directory.
7589 * NOTE: this is an internal function used by following functions:
7590 * control_event_hsv2_descriptor_received
7591 * control_event_hsv2_descriptor_failed
7592 * control_event_hsv3_descriptor_failed
7594 * So do not call this function directly.
7597 event_hs_descriptor_receive_end(const char *action
,
7598 const char *onion_address
,
7599 const char *desc_id
,
7600 rend_auth_type_t auth_type
,
7601 const char *hsdir_id_digest
,
7604 char *reason_field
= NULL
;
7606 if (BUG(!action
|| !onion_address
)) {
7611 tor_asprintf(&reason_field
, " REASON=%s", reason
);
7614 send_control_event(EVENT_HS_DESC
,
7615 "650 HS_DESC %s %s %s %s%s%s\r\n",
7617 rend_hsaddress_str_or_unknown(onion_address
),
7618 rend_auth_type_to_string(auth_type
),
7620 node_describe_longname_by_id(hsdir_id_digest
) :
7622 desc_id
? desc_id
: "",
7623 reason_field
? reason_field
: "");
7625 tor_free(reason_field
);
7628 /** send HS_DESC event after got response from hs directory.
7630 * NOTE: this is an internal function used by following functions:
7631 * control_event_hs_descriptor_uploaded
7632 * control_event_hs_descriptor_upload_failed
7634 * So do not call this function directly.
7637 control_event_hs_descriptor_upload_end(const char *action
,
7638 const char *onion_address
,
7639 const char *id_digest
,
7642 char *reason_field
= NULL
;
7644 if (BUG(!action
|| !id_digest
)) {
7649 tor_asprintf(&reason_field
, " REASON=%s", reason
);
7652 send_control_event(EVENT_HS_DESC
,
7653 "650 HS_DESC %s %s UNKNOWN %s%s\r\n",
7655 rend_hsaddress_str_or_unknown(onion_address
),
7656 node_describe_longname_by_id(id_digest
),
7657 reason_field
? reason_field
: "");
7659 tor_free(reason_field
);
7662 /** send HS_DESC RECEIVED event
7664 * called when we successfully received a hidden service descriptor.
7667 control_event_hsv2_descriptor_received(const char *onion_address
,
7668 const rend_data_t
*rend_data
,
7669 const char *hsdir_id_digest
)
7671 char *desc_id_field
= NULL
;
7672 const char *desc_id
;
7674 if (BUG(!rend_data
|| !hsdir_id_digest
|| !onion_address
)) {
7678 desc_id
= get_desc_id_from_query(rend_data
, hsdir_id_digest
);
7679 if (desc_id
!= NULL
) {
7680 char desc_id_base32
[REND_DESC_ID_V2_LEN_BASE32
+ 1];
7681 /* Set the descriptor ID digest to base32 so we can send it. */
7682 base32_encode(desc_id_base32
, sizeof(desc_id_base32
), desc_id
,
7684 /* Extra whitespace is needed before the value. */
7685 tor_asprintf(&desc_id_field
, " %s", desc_id_base32
);
7688 event_hs_descriptor_receive_end("RECEIVED", onion_address
, desc_id_field
,
7689 TO_REND_DATA_V2(rend_data
)->auth_type
,
7690 hsdir_id_digest
, NULL
);
7691 tor_free(desc_id_field
);
7694 /* Send HS_DESC RECEIVED event
7696 * Called when we successfully received a hidden service descriptor. */
7698 control_event_hsv3_descriptor_received(const char *onion_address
,
7699 const char *desc_id
,
7700 const char *hsdir_id_digest
)
7702 char *desc_id_field
= NULL
;
7704 if (BUG(!onion_address
|| !desc_id
|| !hsdir_id_digest
)) {
7708 /* Because DescriptorID is an optional positional value, we need to add a
7709 * whitespace before in order to not be next to the HsDir value. */
7710 tor_asprintf(&desc_id_field
, " %s", desc_id
);
7712 event_hs_descriptor_receive_end("RECEIVED", onion_address
, desc_id_field
,
7713 REND_NO_AUTH
, hsdir_id_digest
, NULL
);
7714 tor_free(desc_id_field
);
7717 /** send HS_DESC UPLOADED event
7719 * called when we successfully uploaded a hidden service descriptor.
7722 control_event_hs_descriptor_uploaded(const char *id_digest
,
7723 const char *onion_address
)
7725 if (BUG(!id_digest
)) {
7729 control_event_hs_descriptor_upload_end("UPLOADED", onion_address
,
7733 /** Send HS_DESC event to inform controller that query <b>rend_data</b>
7734 * failed to retrieve hidden service descriptor from directory identified by
7735 * <b>id_digest</b>. If NULL, "UNKNOWN" is used. If <b>reason</b> is not NULL,
7736 * add it to REASON= field.
7739 control_event_hsv2_descriptor_failed(const rend_data_t
*rend_data
,
7740 const char *hsdir_id_digest
,
7743 char *desc_id_field
= NULL
;
7744 const char *desc_id
;
7746 if (BUG(!rend_data
)) {
7750 desc_id
= get_desc_id_from_query(rend_data
, hsdir_id_digest
);
7751 if (desc_id
!= NULL
) {
7752 char desc_id_base32
[REND_DESC_ID_V2_LEN_BASE32
+ 1];
7753 /* Set the descriptor ID digest to base32 so we can send it. */
7754 base32_encode(desc_id_base32
, sizeof(desc_id_base32
), desc_id
,
7756 /* Extra whitespace is needed before the value. */
7757 tor_asprintf(&desc_id_field
, " %s", desc_id_base32
);
7760 event_hs_descriptor_receive_end("FAILED", rend_data_get_address(rend_data
),
7762 TO_REND_DATA_V2(rend_data
)->auth_type
,
7763 hsdir_id_digest
, reason
);
7764 tor_free(desc_id_field
);
7767 /** Send HS_DESC event to inform controller that the query to
7768 * <b>onion_address</b> failed to retrieve hidden service descriptor
7769 * <b>desc_id</b> from directory identified by <b>hsdir_id_digest</b>. If
7770 * NULL, "UNKNOWN" is used. If <b>reason</b> is not NULL, add it to REASON=
7773 control_event_hsv3_descriptor_failed(const char *onion_address
,
7774 const char *desc_id
,
7775 const char *hsdir_id_digest
,
7778 char *desc_id_field
= NULL
;
7780 if (BUG(!onion_address
|| !desc_id
|| !reason
)) {
7784 /* Because DescriptorID is an optional positional value, we need to add a
7785 * whitespace before in order to not be next to the HsDir value. */
7786 tor_asprintf(&desc_id_field
, " %s", desc_id
);
7788 event_hs_descriptor_receive_end("FAILED", onion_address
, desc_id_field
,
7789 REND_NO_AUTH
, hsdir_id_digest
, reason
);
7790 tor_free(desc_id_field
);
7793 /** Send HS_DESC_CONTENT event after completion of a successful fetch
7794 * from hs directory. If <b>hsdir_id_digest</b> is NULL, it is replaced
7795 * by "UNKNOWN". If <b>content</b> is NULL, it is replaced by an empty
7796 * string. The <b>onion_address</b> or <b>desc_id</b> set to NULL will
7797 * not trigger the control event. */
7799 control_event_hs_descriptor_content(const char *onion_address
,
7800 const char *desc_id
,
7801 const char *hsdir_id_digest
,
7802 const char *content
)
7804 static const char *event_name
= "HS_DESC_CONTENT";
7805 char *esc_content
= NULL
;
7807 if (!onion_address
|| !desc_id
) {
7808 log_warn(LD_BUG
, "Called with onion_address==%p, desc_id==%p, ",
7809 onion_address
, desc_id
);
7813 if (content
== NULL
) {
7814 /* Point it to empty content so it can still be escaped. */
7817 write_escaped_data(content
, strlen(content
), &esc_content
);
7819 send_control_event(EVENT_HS_DESC_CONTENT
,
7820 "650+%s %s %s %s\r\n%s650 OK\r\n",
7822 rend_hsaddress_str_or_unknown(onion_address
),
7825 node_describe_longname_by_id(hsdir_id_digest
) :
7828 tor_free(esc_content
);
7831 /** Send HS_DESC event to inform controller upload of hidden service
7832 * descriptor identified by <b>id_digest</b> failed. If <b>reason</b>
7833 * is not NULL, add it to REASON= field.
7836 control_event_hs_descriptor_upload_failed(const char *id_digest
,
7837 const char *onion_address
,
7840 if (BUG(!id_digest
)) {
7843 control_event_hs_descriptor_upload_end("FAILED", onion_address
,
7847 /** Free any leftover allocated memory of the control.c subsystem. */
7849 control_free_all(void)
7851 smartlist_t
*queued_events
= NULL
;
7853 stats_prev_n_read
= stats_prev_n_written
= 0;
7855 if (authentication_cookie
) /* Free the auth cookie */
7856 tor_free(authentication_cookie
);
7857 if (detached_onion_services
) { /* Free the detached onion services */
7858 SMARTLIST_FOREACH(detached_onion_services
, char *, cp
, tor_free(cp
));
7859 smartlist_free(detached_onion_services
);
7862 if (queued_control_events_lock
) {
7863 tor_mutex_acquire(queued_control_events_lock
);
7864 flush_queued_event_pending
= 0;
7865 queued_events
= queued_control_events
;
7866 queued_control_events
= NULL
;
7867 tor_mutex_release(queued_control_events_lock
);
7869 if (queued_events
) {
7870 SMARTLIST_FOREACH(queued_events
, queued_event_t
*, ev
,
7871 queued_event_free(ev
));
7872 smartlist_free(queued_events
);
7874 if (flush_queued_events_event
) {
7875 mainloop_event_free(flush_queued_events_event
);
7876 flush_queued_events_event
= NULL
;
7878 bootstrap_percent
= BOOTSTRAP_STATUS_UNDEF
;
7879 bootstrap_phase
= BOOTSTRAP_STATUS_UNDEF
;
7880 notice_bootstrap_percent
= 0;
7881 bootstrap_problems
= 0;
7882 bootstrap_first_orconn
= 0;
7883 bootstrap_dir_progress
= BOOTSTRAP_STATUS_UNDEF
;
7884 bootstrap_dir_phase
= BOOTSTRAP_STATUS_UNDEF
;
7885 authentication_cookie_is_set
= 0;
7886 global_event_mask
= 0;
7887 disable_log_messages
= 0;
7888 memset(last_sent_bootstrap_message
, 0, sizeof(last_sent_bootstrap_message
));
7891 #ifdef TOR_UNIT_TESTS
7892 /* For testing: change the value of global_event_mask */
7894 control_testing_set_global_event_mask(uint64_t mask
)
7896 global_event_mask
= mask
;
7898 #endif /* defined(TOR_UNIT_TESTS) */