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