protover: Fix old tor hardcoded version check
[tor.git] / src / or / control.c
blobc8c5062e86ff42f3dfcb93b6137a4b5faf7d407e
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2016, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file control.c
7 * \brief Implementation for Tor's control-socket interface.
9 * A "controller" is an external program that monitors and controls a Tor
10 * instance via a text-based protocol. It connects to Tor via a connection
11 * to a local socket.
13 * The protocol is line-driven. The controller sends commands terminated by a
14 * CRLF. Tor sends lines that are either <em>replies</em> to what the
15 * controller has said, or <em>events</em> that Tor sends to the controller
16 * asynchronously based on occurrences in the Tor network model.
18 * See the control-spec.txt file in the torspec.git repository for full
19 * details on protocol.
21 * This module generally has two kinds of entry points: those based on having
22 * received a command on a controller socket, which are handled in
23 * connection_control_process_inbuf(), and dispatched to individual functions
24 * with names like control_handle_COMMANDNAME(); and those based on events
25 * that occur elsewhere in Tor, which are handled by functions with names like
26 * control_event_EVENTTYPE().
28 * Controller events are not sent immediately; rather, they are inserted into
29 * the queued_control_events array, and flushed later from
30 * flush_queued_events_cb(). Doing this simplifies our callgraph greatly,
31 * by limiting the number of places in Tor that can call back into the network
32 * stack.
33 **/
35 #define CONTROL_PRIVATE
37 #include "or.h"
38 #include "addressmap.h"
39 #include "buffers.h"
40 #include "channel.h"
41 #include "channeltls.h"
42 #include "circuitbuild.h"
43 #include "circuitlist.h"
44 #include "circuitstats.h"
45 #include "circuituse.h"
46 #include "command.h"
47 #include "compat_libevent.h"
48 #include "config.h"
49 #include "confparse.h"
50 #include "connection.h"
51 #include "connection_edge.h"
52 #include "connection_or.h"
53 #include "control.h"
54 #include "directory.h"
55 #include "dirserv.h"
56 #include "dnsserv.h"
57 #include "entrynodes.h"
58 #include "geoip.h"
59 #include "hibernate.h"
60 #include "main.h"
61 #include "networkstatus.h"
62 #include "nodelist.h"
63 #include "policies.h"
64 #include "reasons.h"
65 #include "rendclient.h"
66 #include "rendcommon.h"
67 #include "rendservice.h"
68 #include "rephist.h"
69 #include "router.h"
70 #include "routerlist.h"
71 #include "routerparse.h"
73 #ifndef _WIN32
74 #include <pwd.h>
75 #include <sys/resource.h>
76 #endif
78 #include <event2/event.h>
80 #include "crypto_s2k.h"
81 #include "procmon.h"
83 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
84 * finished authentication and is accepting commands. */
85 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
87 /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
88 * connection is interested in events of type <b>e</b>. We use this
89 * so that we can decide to skip generating event messages that nobody
90 * has interest in without having to walk over the global connection
91 * list to find out.
92 **/
93 typedef uint64_t event_mask_t;
95 /** An event mask of all the events that any controller is interested in
96 * receiving. */
97 static event_mask_t global_event_mask = 0;
99 /** True iff we have disabled log messages from being sent to the controller */
100 static int disable_log_messages = 0;
102 /** Macro: true if any control connection is interested in events of type
103 * <b>e</b>. */
104 #define EVENT_IS_INTERESTING(e) \
105 (!! (global_event_mask & EVENT_MASK_(e)))
107 /** If we're using cookie-type authentication, how long should our cookies be?
109 #define AUTHENTICATION_COOKIE_LEN 32
111 /** If true, we've set authentication_cookie to a secret code and
112 * stored it to disk. */
113 static int authentication_cookie_is_set = 0;
114 /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
115 * and which we're using to authenticate controllers. (If the controller can
116 * read it off disk, it has permission to connect.) */
117 static uint8_t *authentication_cookie = NULL;
119 #define SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT \
120 "Tor safe cookie authentication server-to-controller hash"
121 #define SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT \
122 "Tor safe cookie authentication controller-to-server hash"
123 #define SAFECOOKIE_SERVER_NONCE_LEN DIGEST256_LEN
125 /** The list of onion services that have been added via ADD_ONION that do not
126 * belong to any particular control connection.
128 static smartlist_t *detached_onion_services = NULL;
130 /** A sufficiently large size to record the last bootstrap phase string. */
131 #define BOOTSTRAP_MSG_LEN 1024
133 /** What was the last bootstrap phase message we sent? We keep track
134 * of this so we can respond to getinfo status/bootstrap-phase queries. */
135 static char last_sent_bootstrap_message[BOOTSTRAP_MSG_LEN];
137 static void connection_printf_to_buf(control_connection_t *conn,
138 const char *format, ...)
139 CHECK_PRINTF(2,3);
140 static void send_control_event_impl(uint16_t event,
141 const char *format, va_list ap)
142 CHECK_PRINTF(2,0);
143 static int control_event_status(int type, int severity, const char *format,
144 va_list args)
145 CHECK_PRINTF(3,0);
147 static void send_control_done(control_connection_t *conn);
148 static void send_control_event(uint16_t event,
149 const char *format, ...)
150 CHECK_PRINTF(2,3);
151 static int handle_control_setconf(control_connection_t *conn, uint32_t len,
152 char *body);
153 static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
154 char *body);
155 static int handle_control_getconf(control_connection_t *conn, uint32_t len,
156 const char *body);
157 static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
158 const char *body);
159 static int handle_control_setevents(control_connection_t *conn, uint32_t len,
160 const char *body);
161 static int handle_control_authenticate(control_connection_t *conn,
162 uint32_t len,
163 const char *body);
164 static int handle_control_signal(control_connection_t *conn, uint32_t len,
165 const char *body);
166 static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
167 const char *body);
168 static char *list_getinfo_options(void);
169 static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
170 const char *body);
171 static int handle_control_extendcircuit(control_connection_t *conn,
172 uint32_t len,
173 const char *body);
174 static int handle_control_setcircuitpurpose(control_connection_t *conn,
175 uint32_t len, const char *body);
176 static int handle_control_attachstream(control_connection_t *conn,
177 uint32_t len,
178 const char *body);
179 static int handle_control_postdescriptor(control_connection_t *conn,
180 uint32_t len,
181 const char *body);
182 static int handle_control_redirectstream(control_connection_t *conn,
183 uint32_t len,
184 const char *body);
185 static int handle_control_closestream(control_connection_t *conn, uint32_t len,
186 const char *body);
187 static int handle_control_closecircuit(control_connection_t *conn,
188 uint32_t len,
189 const char *body);
190 static int handle_control_resolve(control_connection_t *conn, uint32_t len,
191 const char *body);
192 static int handle_control_usefeature(control_connection_t *conn,
193 uint32_t len,
194 const char *body);
195 static int handle_control_hsfetch(control_connection_t *conn, uint32_t len,
196 const char *body);
197 static int handle_control_hspost(control_connection_t *conn, uint32_t len,
198 const char *body);
199 static int handle_control_add_onion(control_connection_t *conn, uint32_t len,
200 const char *body);
201 static int handle_control_del_onion(control_connection_t *conn, uint32_t len,
202 const char *body);
203 static int write_stream_target_to_buf(entry_connection_t *conn, char *buf,
204 size_t len);
205 static void orconn_target_get_name(char *buf, size_t len,
206 or_connection_t *conn);
208 static int get_cached_network_liveness(void);
209 static void set_cached_network_liveness(int liveness);
211 static void flush_queued_events_cb(evutil_socket_t fd, short what, void *arg);
213 static char * download_status_to_string(const download_status_t *dl);
215 /** Given a control event code for a message event, return the corresponding
216 * log severity. */
217 static inline int
218 event_to_log_severity(int event)
220 switch (event) {
221 case EVENT_DEBUG_MSG: return LOG_DEBUG;
222 case EVENT_INFO_MSG: return LOG_INFO;
223 case EVENT_NOTICE_MSG: return LOG_NOTICE;
224 case EVENT_WARN_MSG: return LOG_WARN;
225 case EVENT_ERR_MSG: return LOG_ERR;
226 default: return -1;
230 /** Given a log severity, return the corresponding control event code. */
231 static inline int
232 log_severity_to_event(int severity)
234 switch (severity) {
235 case LOG_DEBUG: return EVENT_DEBUG_MSG;
236 case LOG_INFO: return EVENT_INFO_MSG;
237 case LOG_NOTICE: return EVENT_NOTICE_MSG;
238 case LOG_WARN: return EVENT_WARN_MSG;
239 case LOG_ERR: return EVENT_ERR_MSG;
240 default: return -1;
244 /** Helper: clear bandwidth counters of all origin circuits. */
245 static void
246 clear_circ_bw_fields(void)
248 origin_circuit_t *ocirc;
249 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
250 if (!CIRCUIT_IS_ORIGIN(circ))
251 continue;
252 ocirc = TO_ORIGIN_CIRCUIT(circ);
253 ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
255 SMARTLIST_FOREACH_END(circ);
258 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
259 * connection's event_mask field. */
260 void
261 control_update_global_event_mask(void)
263 smartlist_t *conns = get_connection_array();
264 event_mask_t old_mask, new_mask;
265 old_mask = global_event_mask;
267 global_event_mask = 0;
268 SMARTLIST_FOREACH(conns, connection_t *, _conn,
270 if (_conn->type == CONN_TYPE_CONTROL &&
271 STATE_IS_OPEN(_conn->state)) {
272 control_connection_t *conn = TO_CONTROL_CONN(_conn);
273 global_event_mask |= conn->event_mask;
277 new_mask = global_event_mask;
279 /* Handle the aftermath. Set up the log callback to tell us only what
280 * we want to hear...*/
281 control_adjust_event_log_severity();
283 /* ...then, if we've started logging stream or circ bw, clear the
284 * appropriate fields. */
285 if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
286 (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
287 SMARTLIST_FOREACH(conns, connection_t *, conn,
289 if (conn->type == CONN_TYPE_AP) {
290 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
291 edge_conn->n_written = edge_conn->n_read = 0;
295 if (! (old_mask & EVENT_CIRC_BANDWIDTH_USED) &&
296 (new_mask & EVENT_CIRC_BANDWIDTH_USED)) {
297 clear_circ_bw_fields();
301 /** Adjust the log severities that result in control_event_logmsg being called
302 * to match the severity of log messages that any controllers are interested
303 * in. */
304 void
305 control_adjust_event_log_severity(void)
307 int i;
308 int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
310 for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
311 if (EVENT_IS_INTERESTING(i)) {
312 min_log_event = i;
313 break;
316 for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
317 if (EVENT_IS_INTERESTING(i)) {
318 max_log_event = i;
319 break;
322 if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
323 if (min_log_event > EVENT_NOTICE_MSG)
324 min_log_event = EVENT_NOTICE_MSG;
325 if (max_log_event < EVENT_ERR_MSG)
326 max_log_event = EVENT_ERR_MSG;
328 if (min_log_event <= max_log_event)
329 change_callback_log_severity(event_to_log_severity(min_log_event),
330 event_to_log_severity(max_log_event),
331 control_event_logmsg);
332 else
333 change_callback_log_severity(LOG_ERR, LOG_ERR,
334 control_event_logmsg);
337 /** Return true iff the event with code <b>c</b> is being sent to any current
338 * control connection. This is useful if the amount of work needed to prepare
339 * to call the appropriate control_event_...() function is high.
342 control_event_is_interesting(int event)
344 return EVENT_IS_INTERESTING(event);
347 /** Append a NUL-terminated string <b>s</b> to the end of
348 * <b>conn</b>-\>outbuf.
350 static inline void
351 connection_write_str_to_buf(const char *s, control_connection_t *conn)
353 size_t len = strlen(s);
354 connection_write_to_buf(s, len, TO_CONN(conn));
357 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
358 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
359 * contents of <b>data</b> into *<b>out</b>, adding a period before any period
360 * that appears at the start of a line, and adding a period-CRLF line at
361 * the end. Replace all LF characters sequences with CRLF. Return the number
362 * of bytes in *<b>out</b>.
364 STATIC size_t
365 write_escaped_data(const char *data, size_t len, char **out)
367 size_t sz_out = len+8;
368 char *outp;
369 const char *start = data, *end;
370 int i;
371 int start_of_line;
372 for (i=0; i<(int)len; ++i) {
373 if (data[i]== '\n')
374 sz_out += 2; /* Maybe add a CR; maybe add a dot. */
376 *out = outp = tor_malloc(sz_out+1);
377 end = data+len;
378 start_of_line = 1;
379 while (data < end) {
380 if (*data == '\n') {
381 if (data > start && data[-1] != '\r')
382 *outp++ = '\r';
383 start_of_line = 1;
384 } else if (*data == '.') {
385 if (start_of_line) {
386 start_of_line = 0;
387 *outp++ = '.';
389 } else {
390 start_of_line = 0;
392 *outp++ = *data++;
394 if (outp < *out+2 || fast_memcmp(outp-2, "\r\n", 2)) {
395 *outp++ = '\r';
396 *outp++ = '\n';
398 *outp++ = '.';
399 *outp++ = '\r';
400 *outp++ = '\n';
401 *outp = '\0'; /* NUL-terminate just in case. */
402 tor_assert((outp - *out) <= (int)sz_out);
403 return outp - *out;
406 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
407 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
408 * the contents of <b>data</b> into *<b>out</b>, removing any period
409 * that appears at the start of a line, and replacing all CRLF sequences
410 * with LF. Return the number of
411 * bytes in *<b>out</b>. */
412 STATIC size_t
413 read_escaped_data(const char *data, size_t len, char **out)
415 char *outp;
416 const char *next;
417 const char *end;
419 *out = outp = tor_malloc(len+1);
421 end = data+len;
423 while (data < end) {
424 /* we're at the start of a line. */
425 if (*data == '.')
426 ++data;
427 next = memchr(data, '\n', end-data);
428 if (next) {
429 size_t n_to_copy = next-data;
430 /* Don't copy a CR that precedes this LF. */
431 if (n_to_copy && *(next-1) == '\r')
432 --n_to_copy;
433 memcpy(outp, data, n_to_copy);
434 outp += n_to_copy;
435 data = next+1; /* This will point at the start of the next line,
436 * or the end of the string, or a period. */
437 } else {
438 memcpy(outp, data, end-data);
439 outp += (end-data);
440 *outp = '\0';
441 return outp - *out;
443 *outp++ = '\n';
446 *outp = '\0';
447 return outp - *out;
450 /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
451 * double-quoted string with escaped characters, return the length of that
452 * string (as encoded, including quotes). Otherwise return -1. */
453 static inline int
454 get_escaped_string_length(const char *start, size_t in_len_max,
455 int *chars_out)
457 const char *cp, *end;
458 int chars = 0;
460 if (*start != '\"')
461 return -1;
463 cp = start+1;
464 end = start+in_len_max;
466 /* Calculate length. */
467 while (1) {
468 if (cp >= end) {
469 return -1; /* Too long. */
470 } else if (*cp == '\\') {
471 if (++cp == end)
472 return -1; /* Can't escape EOS. */
473 ++cp;
474 ++chars;
475 } else if (*cp == '\"') {
476 break;
477 } else {
478 ++cp;
479 ++chars;
482 if (chars_out)
483 *chars_out = chars;
484 return (int)(cp - start+1);
487 /** As decode_escaped_string, but does not decode the string: copies the
488 * entire thing, including quotation marks. */
489 static const char *
490 extract_escaped_string(const char *start, size_t in_len_max,
491 char **out, size_t *out_len)
493 int length = get_escaped_string_length(start, in_len_max, NULL);
494 if (length<0)
495 return NULL;
496 *out_len = length;
497 *out = tor_strndup(start, *out_len);
498 return start+length;
501 /** Given a pointer to a string starting at <b>start</b> containing
502 * <b>in_len_max</b> characters, decode a string beginning with one double
503 * quote, containing any number of non-quote characters or characters escaped
504 * with a backslash, and ending with a final double quote. Place the resulting
505 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
506 * store its length in <b>out_len</b>. On success, return a pointer to the
507 * character immediately following the escaped string. On failure, return
508 * NULL. */
509 static const char *
510 decode_escaped_string(const char *start, size_t in_len_max,
511 char **out, size_t *out_len)
513 const char *cp, *end;
514 char *outp;
515 int len, n_chars = 0;
517 len = get_escaped_string_length(start, in_len_max, &n_chars);
518 if (len<0)
519 return NULL;
521 end = start+len-1; /* Index of last quote. */
522 tor_assert(*end == '\"');
523 outp = *out = tor_malloc(len+1);
524 *out_len = n_chars;
526 cp = start+1;
527 while (cp < end) {
528 if (*cp == '\\')
529 ++cp;
530 *outp++ = *cp++;
532 *outp = '\0';
533 tor_assert((outp - *out) == (int)*out_len);
535 return end+1;
538 /** Acts like sprintf, but writes its formatted string to the end of
539 * <b>conn</b>-\>outbuf. */
540 static void
541 connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
543 va_list ap;
544 char *buf = NULL;
545 int len;
547 va_start(ap,format);
548 len = tor_vasprintf(&buf, format, ap);
549 va_end(ap);
551 if (len < 0) {
552 log_err(LD_BUG, "Unable to format string for controller.");
553 tor_assert(0);
556 connection_write_to_buf(buf, (size_t)len, TO_CONN(conn));
558 tor_free(buf);
561 /** Write all of the open control ports to ControlPortWriteToFile */
562 void
563 control_ports_write_to_file(void)
565 smartlist_t *lines;
566 char *joined = NULL;
567 const or_options_t *options = get_options();
569 if (!options->ControlPortWriteToFile)
570 return;
572 lines = smartlist_new();
574 SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t *, conn) {
575 if (conn->type != CONN_TYPE_CONTROL_LISTENER || conn->marked_for_close)
576 continue;
577 #ifdef AF_UNIX
578 if (conn->socket_family == AF_UNIX) {
579 smartlist_add_asprintf(lines, "UNIX_PORT=%s\n", conn->address);
580 continue;
582 #endif
583 smartlist_add_asprintf(lines, "PORT=%s:%d\n", conn->address, conn->port);
584 } SMARTLIST_FOREACH_END(conn);
586 joined = smartlist_join_strings(lines, "", 0, NULL);
588 if (write_str_to_file(options->ControlPortWriteToFile, joined, 0) < 0) {
589 log_warn(LD_CONTROL, "Writing %s failed: %s",
590 options->ControlPortWriteToFile, strerror(errno));
592 #ifndef _WIN32
593 if (options->ControlPortFileGroupReadable) {
594 if (chmod(options->ControlPortWriteToFile, 0640)) {
595 log_warn(LD_FS,"Unable to make %s group-readable.",
596 options->ControlPortWriteToFile);
599 #endif
600 tor_free(joined);
601 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
602 smartlist_free(lines);
605 /** Send a "DONE" message down the control connection <b>conn</b>. */
606 static void
607 send_control_done(control_connection_t *conn)
609 connection_write_str_to_buf("250 OK\r\n", conn);
612 /** Represents an event that's queued to be sent to one or more
613 * controllers. */
614 typedef struct queued_event_s {
615 uint16_t event;
616 char *msg;
617 } queued_event_t;
619 /** Pointer to int. If this is greater than 0, we don't allow new events to be
620 * queued. */
621 static tor_threadlocal_t block_event_queue_flag;
623 /** Holds a smartlist of queued_event_t objects that may need to be sent
624 * to one or more controllers */
625 static smartlist_t *queued_control_events = NULL;
627 /** True if the flush_queued_events_event is pending. */
628 static int flush_queued_event_pending = 0;
630 /** Lock to protect the above fields. */
631 static tor_mutex_t *queued_control_events_lock = NULL;
633 /** An event that should fire in order to flush the contents of
634 * queued_control_events. */
635 static struct event *flush_queued_events_event = NULL;
637 void
638 control_initialize_event_queue(void)
640 if (queued_control_events == NULL) {
641 queued_control_events = smartlist_new();
644 if (flush_queued_events_event == NULL) {
645 struct event_base *b = tor_libevent_get_base();
646 if (b) {
647 flush_queued_events_event = tor_event_new(b,
648 -1, 0, flush_queued_events_cb,
649 NULL);
650 tor_assert(flush_queued_events_event);
654 if (queued_control_events_lock == NULL) {
655 queued_control_events_lock = tor_mutex_new();
656 tor_threadlocal_init(&block_event_queue_flag);
660 static int *
661 get_block_event_queue(void)
663 int *val = tor_threadlocal_get(&block_event_queue_flag);
664 if (PREDICT_UNLIKELY(val == NULL)) {
665 val = tor_malloc_zero(sizeof(int));
666 tor_threadlocal_set(&block_event_queue_flag, val);
668 return val;
671 /** Helper: inserts an event on the list of events queued to be sent to
672 * one or more controllers, and schedules the events to be flushed if needed.
674 * This function takes ownership of <b>msg</b>, and may free it.
676 * We queue these events rather than send them immediately in order to break
677 * the dependency in our callgraph from code that generates events for the
678 * controller, and the network layer at large. Otherwise, nearly every
679 * interesting part of Tor would potentially call every other interesting part
680 * of Tor.
682 MOCK_IMPL(STATIC void,
683 queue_control_event_string,(uint16_t event, char *msg))
685 /* This is redundant with checks done elsewhere, but it's a last-ditch
686 * attempt to avoid queueing something we shouldn't have to queue. */
687 if (PREDICT_UNLIKELY( ! EVENT_IS_INTERESTING(event) )) {
688 tor_free(msg);
689 return;
692 int *block_event_queue = get_block_event_queue();
693 if (*block_event_queue) {
694 tor_free(msg);
695 return;
698 queued_event_t *ev = tor_malloc(sizeof(*ev));
699 ev->event = event;
700 ev->msg = msg;
702 /* No queueing an event while queueing an event */
703 ++*block_event_queue;
705 tor_mutex_acquire(queued_control_events_lock);
706 tor_assert(queued_control_events);
707 smartlist_add(queued_control_events, ev);
709 int activate_event = 0;
710 if (! flush_queued_event_pending && in_main_thread()) {
711 activate_event = 1;
712 flush_queued_event_pending = 1;
715 tor_mutex_release(queued_control_events_lock);
717 --*block_event_queue;
719 /* We just put an event on the queue; mark the queue to be
720 * flushed. We only do this from the main thread for now; otherwise,
721 * we'd need to incur locking overhead in Libevent or use a socket.
723 if (activate_event) {
724 tor_assert(flush_queued_events_event);
725 event_active(flush_queued_events_event, EV_READ, 1);
729 /** Release all storage held by <b>ev</b>. */
730 static void
731 queued_event_free(queued_event_t *ev)
733 if (ev == NULL)
734 return;
736 tor_free(ev->msg);
737 tor_free(ev);
740 /** Send every queued event to every controller that's interested in it,
741 * and remove the events from the queue. If <b>force</b> is true,
742 * then make all controllers send their data out immediately, since we
743 * may be about to shut down. */
744 static void
745 queued_events_flush_all(int force)
747 if (PREDICT_UNLIKELY(queued_control_events == NULL)) {
748 return;
750 smartlist_t *all_conns = get_connection_array();
751 smartlist_t *controllers = smartlist_new();
752 smartlist_t *queued_events;
754 int *block_event_queue = get_block_event_queue();
755 ++*block_event_queue;
757 tor_mutex_acquire(queued_control_events_lock);
758 /* No queueing an event while flushing events. */
759 flush_queued_event_pending = 0;
760 queued_events = queued_control_events;
761 queued_control_events = smartlist_new();
762 tor_mutex_release(queued_control_events_lock);
764 /* Gather all the controllers that will care... */
765 SMARTLIST_FOREACH_BEGIN(all_conns, connection_t *, conn) {
766 if (conn->type == CONN_TYPE_CONTROL &&
767 !conn->marked_for_close &&
768 conn->state == CONTROL_CONN_STATE_OPEN) {
769 control_connection_t *control_conn = TO_CONTROL_CONN(conn);
771 smartlist_add(controllers, control_conn);
773 } SMARTLIST_FOREACH_END(conn);
775 SMARTLIST_FOREACH_BEGIN(queued_events, queued_event_t *, ev) {
776 const event_mask_t bit = ((event_mask_t)1) << ev->event;
777 const size_t msg_len = strlen(ev->msg);
778 SMARTLIST_FOREACH_BEGIN(controllers, control_connection_t *,
779 control_conn) {
780 if (control_conn->event_mask & bit) {
781 connection_write_to_buf(ev->msg, msg_len, TO_CONN(control_conn));
783 } SMARTLIST_FOREACH_END(control_conn);
785 queued_event_free(ev);
786 } SMARTLIST_FOREACH_END(ev);
788 if (force) {
789 SMARTLIST_FOREACH_BEGIN(controllers, control_connection_t *,
790 control_conn) {
791 connection_flush(TO_CONN(control_conn));
792 } SMARTLIST_FOREACH_END(control_conn);
795 smartlist_free(queued_events);
796 smartlist_free(controllers);
798 --*block_event_queue;
801 /** Libevent callback: Flushes pending events to controllers that are
802 * interested in them */
803 static void
804 flush_queued_events_cb(evutil_socket_t fd, short what, void *arg)
806 (void) fd;
807 (void) what;
808 (void) arg;
809 queued_events_flush_all(0);
812 /** Send an event to all v1 controllers that are listening for code
813 * <b>event</b>. The event's body is given by <b>msg</b>.
815 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
816 * respect to the EXTENDED_EVENTS feature. */
817 MOCK_IMPL(STATIC void,
818 send_control_event_string,(uint16_t event,
819 const char *msg))
821 tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
822 queue_control_event_string(event, tor_strdup(msg));
825 /** Helper for send_control_event and control_event_status:
826 * Send an event to all v1 controllers that are listening for code
827 * <b>event</b>. The event's body is created by the printf-style format in
828 * <b>format</b>, and other arguments as provided. */
829 static void
830 send_control_event_impl(uint16_t event,
831 const char *format, va_list ap)
833 char *buf = NULL;
834 int len;
836 len = tor_vasprintf(&buf, format, ap);
837 if (len < 0) {
838 log_warn(LD_BUG, "Unable to format event for controller.");
839 return;
842 queue_control_event_string(event, buf);
845 /** Send an event to all v1 controllers that are listening for code
846 * <b>event</b>. The event's body is created by the printf-style format in
847 * <b>format</b>, and other arguments as provided. */
848 static void
849 send_control_event(uint16_t event,
850 const char *format, ...)
852 va_list ap;
853 va_start(ap, format);
854 send_control_event_impl(event, format, ap);
855 va_end(ap);
858 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
859 static origin_circuit_t *
860 get_circ(const char *id)
862 uint32_t n_id;
863 int ok;
864 n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
865 if (!ok)
866 return NULL;
867 return circuit_get_by_global_id(n_id);
870 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
871 static entry_connection_t *
872 get_stream(const char *id)
874 uint64_t n_id;
875 int ok;
876 connection_t *conn;
877 n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
878 if (!ok)
879 return NULL;
880 conn = connection_get_by_global_id(n_id);
881 if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
882 return NULL;
883 return TO_ENTRY_CONN(conn);
886 /** Helper for setconf and resetconf. Acts like setconf, except
887 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
888 * contents of body.
890 static int
891 control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
892 int use_defaults)
894 setopt_err_t opt_err;
895 config_line_t *lines=NULL;
896 char *start = body;
897 char *errstring = NULL;
898 const unsigned flags =
899 CAL_CLEAR_FIRST | (use_defaults ? CAL_USE_DEFAULTS : 0);
901 char *config;
902 smartlist_t *entries = smartlist_new();
904 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
905 * separated by space. break it into a list of configuration entries. */
906 while (*body) {
907 char *eq = body;
908 char *key;
909 char *entry;
910 while (!TOR_ISSPACE(*eq) && *eq != '=')
911 ++eq;
912 key = tor_strndup(body, eq-body);
913 body = eq+1;
914 if (*eq == '=') {
915 char *val=NULL;
916 size_t val_len=0;
917 if (*body != '\"') {
918 char *val_start = body;
919 while (!TOR_ISSPACE(*body))
920 body++;
921 val = tor_strndup(val_start, body-val_start);
922 val_len = strlen(val);
923 } else {
924 body = (char*)extract_escaped_string(body, (len - (body-start)),
925 &val, &val_len);
926 if (!body) {
927 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
928 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
929 smartlist_free(entries);
930 tor_free(key);
931 return 0;
934 tor_asprintf(&entry, "%s %s", key, val);
935 tor_free(key);
936 tor_free(val);
937 } else {
938 entry = key;
940 smartlist_add(entries, entry);
941 while (TOR_ISSPACE(*body))
942 ++body;
945 smartlist_add(entries, tor_strdup(""));
946 config = smartlist_join_strings(entries, "\n", 0, NULL);
947 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
948 smartlist_free(entries);
950 if (config_get_lines(config, &lines, 0) < 0) {
951 log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
952 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
953 conn);
954 tor_free(config);
955 return 0;
957 tor_free(config);
959 opt_err = options_trial_assign(lines, flags, &errstring);
961 const char *msg;
962 switch (opt_err) {
963 case SETOPT_ERR_MISC:
964 msg = "552 Unrecognized option";
965 break;
966 case SETOPT_ERR_PARSE:
967 msg = "513 Unacceptable option value";
968 break;
969 case SETOPT_ERR_TRANSITION:
970 msg = "553 Transition not allowed";
971 break;
972 case SETOPT_ERR_SETTING:
973 default:
974 msg = "553 Unable to set option";
975 break;
976 case SETOPT_OK:
977 config_free_lines(lines);
978 send_control_done(conn);
979 return 0;
981 log_warn(LD_CONTROL,
982 "Controller gave us config lines that didn't validate: %s",
983 errstring);
984 connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
985 config_free_lines(lines);
986 tor_free(errstring);
987 return 0;
991 /** Called when we receive a SETCONF message: parse the body and try
992 * to update our configuration. Reply with a DONE or ERROR message.
993 * Modifies the contents of body.*/
994 static int
995 handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
997 return control_setconf_helper(conn, len, body, 0);
1000 /** Called when we receive a RESETCONF message: parse the body and try
1001 * to update our configuration. Reply with a DONE or ERROR message.
1002 * Modifies the contents of body. */
1003 static int
1004 handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
1006 return control_setconf_helper(conn, len, body, 1);
1009 /** Called when we receive a GETCONF message. Parse the request, and
1010 * reply with a CONFVALUE or an ERROR message */
1011 static int
1012 handle_control_getconf(control_connection_t *conn, uint32_t body_len,
1013 const char *body)
1015 smartlist_t *questions = smartlist_new();
1016 smartlist_t *answers = smartlist_new();
1017 smartlist_t *unrecognized = smartlist_new();
1018 char *msg = NULL;
1019 size_t msg_len;
1020 const or_options_t *options = get_options();
1021 int i, len;
1023 (void) body_len; /* body is NUL-terminated; so we can ignore len. */
1024 smartlist_split_string(questions, body, " ",
1025 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1026 SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
1027 if (!option_is_recognized(q)) {
1028 smartlist_add(unrecognized, (char*) q);
1029 } else {
1030 config_line_t *answer = option_get_assignment(options,q);
1031 if (!answer) {
1032 const char *name = option_get_canonical_name(q);
1033 smartlist_add_asprintf(answers, "250-%s\r\n", name);
1036 while (answer) {
1037 config_line_t *next;
1038 smartlist_add_asprintf(answers, "250-%s=%s\r\n",
1039 answer->key, answer->value);
1041 next = answer->next;
1042 tor_free(answer->key);
1043 tor_free(answer->value);
1044 tor_free(answer);
1045 answer = next;
1048 } SMARTLIST_FOREACH_END(q);
1050 if ((len = smartlist_len(unrecognized))) {
1051 for (i=0; i < len-1; ++i)
1052 connection_printf_to_buf(conn,
1053 "552-Unrecognized configuration key \"%s\"\r\n",
1054 (char*)smartlist_get(unrecognized, i));
1055 connection_printf_to_buf(conn,
1056 "552 Unrecognized configuration key \"%s\"\r\n",
1057 (char*)smartlist_get(unrecognized, len-1));
1058 } else if ((len = smartlist_len(answers))) {
1059 char *tmp = smartlist_get(answers, len-1);
1060 tor_assert(strlen(tmp)>4);
1061 tmp[3] = ' ';
1062 msg = smartlist_join_strings(answers, "", 0, &msg_len);
1063 connection_write_to_buf(msg, msg_len, TO_CONN(conn));
1064 } else {
1065 connection_write_str_to_buf("250 OK\r\n", conn);
1068 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
1069 smartlist_free(answers);
1070 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
1071 smartlist_free(questions);
1072 smartlist_free(unrecognized);
1074 tor_free(msg);
1076 return 0;
1079 /** Called when we get a +LOADCONF message. */
1080 static int
1081 handle_control_loadconf(control_connection_t *conn, uint32_t len,
1082 const char *body)
1084 setopt_err_t retval;
1085 char *errstring = NULL;
1086 const char *msg = NULL;
1087 (void) len;
1089 retval = options_init_from_string(NULL, body, CMD_RUN_TOR, NULL, &errstring);
1091 if (retval != SETOPT_OK)
1092 log_warn(LD_CONTROL,
1093 "Controller gave us config file that didn't validate: %s",
1094 errstring);
1096 switch (retval) {
1097 case SETOPT_ERR_PARSE:
1098 msg = "552 Invalid config file";
1099 break;
1100 case SETOPT_ERR_TRANSITION:
1101 msg = "553 Transition not allowed";
1102 break;
1103 case SETOPT_ERR_SETTING:
1104 msg = "553 Unable to set option";
1105 break;
1106 case SETOPT_ERR_MISC:
1107 default:
1108 msg = "550 Unable to load config";
1109 break;
1110 case SETOPT_OK:
1111 break;
1113 if (msg) {
1114 if (errstring)
1115 connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
1116 else
1117 connection_printf_to_buf(conn, "%s\r\n", msg);
1118 } else {
1119 send_control_done(conn);
1121 tor_free(errstring);
1122 return 0;
1125 /** Helper structure: maps event values to their names. */
1126 struct control_event_t {
1127 uint16_t event_code;
1128 const char *event_name;
1130 /** Table mapping event values to their names. Used to implement SETEVENTS
1131 * and GETINFO events/names, and to keep they in sync. */
1132 static const struct control_event_t control_event_table[] = {
1133 { EVENT_CIRCUIT_STATUS, "CIRC" },
1134 { EVENT_CIRCUIT_STATUS_MINOR, "CIRC_MINOR" },
1135 { EVENT_STREAM_STATUS, "STREAM" },
1136 { EVENT_OR_CONN_STATUS, "ORCONN" },
1137 { EVENT_BANDWIDTH_USED, "BW" },
1138 { EVENT_DEBUG_MSG, "DEBUG" },
1139 { EVENT_INFO_MSG, "INFO" },
1140 { EVENT_NOTICE_MSG, "NOTICE" },
1141 { EVENT_WARN_MSG, "WARN" },
1142 { EVENT_ERR_MSG, "ERR" },
1143 { EVENT_NEW_DESC, "NEWDESC" },
1144 { EVENT_ADDRMAP, "ADDRMAP" },
1145 { EVENT_AUTHDIR_NEWDESCS, "AUTHDIR_NEWDESCS" },
1146 { EVENT_DESCCHANGED, "DESCCHANGED" },
1147 { EVENT_NS, "NS" },
1148 { EVENT_STATUS_GENERAL, "STATUS_GENERAL" },
1149 { EVENT_STATUS_CLIENT, "STATUS_CLIENT" },
1150 { EVENT_STATUS_SERVER, "STATUS_SERVER" },
1151 { EVENT_GUARD, "GUARD" },
1152 { EVENT_STREAM_BANDWIDTH_USED, "STREAM_BW" },
1153 { EVENT_CLIENTS_SEEN, "CLIENTS_SEEN" },
1154 { EVENT_NEWCONSENSUS, "NEWCONSENSUS" },
1155 { EVENT_BUILDTIMEOUT_SET, "BUILDTIMEOUT_SET" },
1156 { EVENT_GOT_SIGNAL, "SIGNAL" },
1157 { EVENT_CONF_CHANGED, "CONF_CHANGED"},
1158 { EVENT_CONN_BW, "CONN_BW" },
1159 { EVENT_CELL_STATS, "CELL_STATS" },
1160 { EVENT_TB_EMPTY, "TB_EMPTY" },
1161 { EVENT_CIRC_BANDWIDTH_USED, "CIRC_BW" },
1162 { EVENT_TRANSPORT_LAUNCHED, "TRANSPORT_LAUNCHED" },
1163 { EVENT_HS_DESC, "HS_DESC" },
1164 { EVENT_HS_DESC_CONTENT, "HS_DESC_CONTENT" },
1165 { EVENT_NETWORK_LIVENESS, "NETWORK_LIVENESS" },
1166 { 0, NULL },
1169 /** Called when we get a SETEVENTS message: update conn->event_mask,
1170 * and reply with DONE or ERROR. */
1171 static int
1172 handle_control_setevents(control_connection_t *conn, uint32_t len,
1173 const char *body)
1175 int event_code;
1176 event_mask_t event_mask = 0;
1177 smartlist_t *events = smartlist_new();
1179 (void) len;
1181 smartlist_split_string(events, body, " ",
1182 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1183 SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
1185 if (!strcasecmp(ev, "EXTENDED")) {
1186 continue;
1187 } else {
1188 int i;
1189 event_code = -1;
1191 for (i = 0; control_event_table[i].event_name != NULL; ++i) {
1192 if (!strcasecmp(ev, control_event_table[i].event_name)) {
1193 event_code = control_event_table[i].event_code;
1194 break;
1198 if (event_code == -1) {
1199 connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
1200 ev);
1201 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
1202 smartlist_free(events);
1203 return 0;
1206 event_mask |= (((event_mask_t)1) << event_code);
1208 SMARTLIST_FOREACH_END(ev);
1209 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
1210 smartlist_free(events);
1212 conn->event_mask = event_mask;
1214 control_update_global_event_mask();
1215 send_control_done(conn);
1216 return 0;
1219 /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
1220 * Return a smartlist of acceptable passwords (unterminated strings of
1221 * length S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on
1222 * failure.
1224 smartlist_t *
1225 decode_hashed_passwords(config_line_t *passwords)
1227 char decoded[64];
1228 config_line_t *cl;
1229 smartlist_t *sl = smartlist_new();
1231 tor_assert(passwords);
1233 for (cl = passwords; cl; cl = cl->next) {
1234 const char *hashed = cl->value;
1236 if (!strcmpstart(hashed, "16:")) {
1237 if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))
1238 != S2K_RFC2440_SPECIFIER_LEN + DIGEST_LEN
1239 || strlen(hashed+3) != (S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN)*2) {
1240 goto err;
1242 } else {
1243 if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
1244 != S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN) {
1245 goto err;
1248 smartlist_add(sl,
1249 tor_memdup(decoded, S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN));
1252 return sl;
1254 err:
1255 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
1256 smartlist_free(sl);
1257 return NULL;
1260 /** Called when we get an AUTHENTICATE message. Check whether the
1261 * authentication is valid, and if so, update the connection's state to
1262 * OPEN. Reply with DONE or ERROR.
1264 static int
1265 handle_control_authenticate(control_connection_t *conn, uint32_t len,
1266 const char *body)
1268 int used_quoted_string = 0;
1269 const or_options_t *options = get_options();
1270 const char *errstr = "Unknown error";
1271 char *password;
1272 size_t password_len;
1273 const char *cp;
1274 int i;
1275 int bad_cookie=0, bad_password=0;
1276 smartlist_t *sl = NULL;
1278 if (!len) {
1279 password = tor_strdup("");
1280 password_len = 0;
1281 } else if (TOR_ISXDIGIT(body[0])) {
1282 cp = body;
1283 while (TOR_ISXDIGIT(*cp))
1284 ++cp;
1285 i = (int)(cp - body);
1286 tor_assert(i>0);
1287 password_len = i/2;
1288 password = tor_malloc(password_len + 1);
1289 if (base16_decode(password, password_len+1, body, i)
1290 != (int) password_len) {
1291 connection_write_str_to_buf(
1292 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1293 "password? If so, the standard requires that you put it in "
1294 "double quotes.\r\n", conn);
1295 connection_mark_for_close(TO_CONN(conn));
1296 tor_free(password);
1297 return 0;
1299 } else {
1300 if (!decode_escaped_string(body, len, &password, &password_len)) {
1301 connection_write_str_to_buf("551 Invalid quoted string. You need "
1302 "to put the password in double quotes.\r\n", conn);
1303 connection_mark_for_close(TO_CONN(conn));
1304 return 0;
1306 used_quoted_string = 1;
1309 if (conn->safecookie_client_hash != NULL) {
1310 /* The controller has chosen safe cookie authentication; the only
1311 * acceptable authentication value is the controller-to-server
1312 * response. */
1314 tor_assert(authentication_cookie_is_set);
1316 if (password_len != DIGEST256_LEN) {
1317 log_warn(LD_CONTROL,
1318 "Got safe cookie authentication response with wrong length "
1319 "(%d)", (int)password_len);
1320 errstr = "Wrong length for safe cookie response.";
1321 goto err;
1324 if (tor_memneq(conn->safecookie_client_hash, password, DIGEST256_LEN)) {
1325 log_warn(LD_CONTROL,
1326 "Got incorrect safe cookie authentication response");
1327 errstr = "Safe cookie response did not match expected value.";
1328 goto err;
1331 tor_free(conn->safecookie_client_hash);
1332 goto ok;
1335 if (!options->CookieAuthentication && !options->HashedControlPassword &&
1336 !options->HashedControlSessionPassword) {
1337 /* if Tor doesn't demand any stronger authentication, then
1338 * the controller can get in with anything. */
1339 goto ok;
1342 if (options->CookieAuthentication) {
1343 int also_password = options->HashedControlPassword != NULL ||
1344 options->HashedControlSessionPassword != NULL;
1345 if (password_len != AUTHENTICATION_COOKIE_LEN) {
1346 if (!also_password) {
1347 log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
1348 "(%d)", (int)password_len);
1349 errstr = "Wrong length on authentication cookie.";
1350 goto err;
1352 bad_cookie = 1;
1353 } else if (tor_memneq(authentication_cookie, password, password_len)) {
1354 if (!also_password) {
1355 log_warn(LD_CONTROL, "Got mismatched authentication cookie");
1356 errstr = "Authentication cookie did not match expected value.";
1357 goto err;
1359 bad_cookie = 1;
1360 } else {
1361 goto ok;
1365 if (options->HashedControlPassword ||
1366 options->HashedControlSessionPassword) {
1367 int bad = 0;
1368 smartlist_t *sl_tmp;
1369 char received[DIGEST_LEN];
1370 int also_cookie = options->CookieAuthentication;
1371 sl = smartlist_new();
1372 if (options->HashedControlPassword) {
1373 sl_tmp = decode_hashed_passwords(options->HashedControlPassword);
1374 if (!sl_tmp)
1375 bad = 1;
1376 else {
1377 smartlist_add_all(sl, sl_tmp);
1378 smartlist_free(sl_tmp);
1381 if (options->HashedControlSessionPassword) {
1382 sl_tmp = decode_hashed_passwords(options->HashedControlSessionPassword);
1383 if (!sl_tmp)
1384 bad = 1;
1385 else {
1386 smartlist_add_all(sl, sl_tmp);
1387 smartlist_free(sl_tmp);
1390 if (bad) {
1391 if (!also_cookie) {
1392 log_warn(LD_BUG,
1393 "Couldn't decode HashedControlPassword: invalid base16");
1394 errstr="Couldn't decode HashedControlPassword value in configuration.";
1395 goto err;
1397 bad_password = 1;
1398 SMARTLIST_FOREACH(sl, char *, str, tor_free(str));
1399 smartlist_free(sl);
1400 sl = NULL;
1401 } else {
1402 SMARTLIST_FOREACH(sl, char *, expected,
1404 secret_to_key_rfc2440(received,DIGEST_LEN,
1405 password,password_len,expected);
1406 if (tor_memeq(expected + S2K_RFC2440_SPECIFIER_LEN,
1407 received, DIGEST_LEN))
1408 goto ok;
1410 SMARTLIST_FOREACH(sl, char *, str, tor_free(str));
1411 smartlist_free(sl);
1412 sl = NULL;
1414 if (used_quoted_string)
1415 errstr = "Password did not match HashedControlPassword value from "
1416 "configuration";
1417 else
1418 errstr = "Password did not match HashedControlPassword value from "
1419 "configuration. Maybe you tried a plain text password? "
1420 "If so, the standard requires that you put it in double quotes.";
1421 bad_password = 1;
1422 if (!also_cookie)
1423 goto err;
1427 /** We only get here if both kinds of authentication failed. */
1428 tor_assert(bad_password && bad_cookie);
1429 log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
1430 errstr = "Password did not match HashedControlPassword *or* authentication "
1431 "cookie.";
1433 err:
1434 tor_free(password);
1435 connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n", errstr);
1436 connection_mark_for_close(TO_CONN(conn));
1437 if (sl) { /* clean up */
1438 SMARTLIST_FOREACH(sl, char *, str, tor_free(str));
1439 smartlist_free(sl);
1441 return 0;
1443 log_info(LD_CONTROL, "Authenticated control connection ("TOR_SOCKET_T_FORMAT
1444 ")", conn->base_.s);
1445 send_control_done(conn);
1446 conn->base_.state = CONTROL_CONN_STATE_OPEN;
1447 tor_free(password);
1448 if (sl) { /* clean up */
1449 SMARTLIST_FOREACH(sl, char *, str, tor_free(str));
1450 smartlist_free(sl);
1452 return 0;
1455 /** Called when we get a SAVECONF command. Try to flush the current options to
1456 * disk, and report success or failure. */
1457 static int
1458 handle_control_saveconf(control_connection_t *conn, uint32_t len,
1459 const char *body)
1461 (void) len;
1462 (void) body;
1463 if (options_save_current()<0) {
1464 connection_write_str_to_buf(
1465 "551 Unable to write configuration to disk.\r\n", conn);
1466 } else {
1467 send_control_done(conn);
1469 return 0;
1472 struct signal_t {
1473 int sig;
1474 const char *signal_name;
1477 static const struct signal_t signal_table[] = {
1478 { SIGHUP, "RELOAD" },
1479 { SIGHUP, "HUP" },
1480 { SIGINT, "SHUTDOWN" },
1481 { SIGUSR1, "DUMP" },
1482 { SIGUSR1, "USR1" },
1483 { SIGUSR2, "DEBUG" },
1484 { SIGUSR2, "USR2" },
1485 { SIGTERM, "HALT" },
1486 { SIGTERM, "TERM" },
1487 { SIGTERM, "INT" },
1488 { SIGNEWNYM, "NEWNYM" },
1489 { SIGCLEARDNSCACHE, "CLEARDNSCACHE"},
1490 { SIGHEARTBEAT, "HEARTBEAT"},
1491 { 0, NULL },
1494 /** Called when we get a SIGNAL command. React to the provided signal, and
1495 * report success or failure. (If the signal results in a shutdown, success
1496 * may not be reported.) */
1497 static int
1498 handle_control_signal(control_connection_t *conn, uint32_t len,
1499 const char *body)
1501 int sig = -1;
1502 int i;
1503 int n = 0;
1504 char *s;
1506 (void) len;
1508 while (body[n] && ! TOR_ISSPACE(body[n]))
1509 ++n;
1510 s = tor_strndup(body, n);
1512 for (i = 0; signal_table[i].signal_name != NULL; ++i) {
1513 if (!strcasecmp(s, signal_table[i].signal_name)) {
1514 sig = signal_table[i].sig;
1515 break;
1519 if (sig < 0)
1520 connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
1522 tor_free(s);
1523 if (sig < 0)
1524 return 0;
1526 send_control_done(conn);
1527 /* Flush the "done" first if the signal might make us shut down. */
1528 if (sig == SIGTERM || sig == SIGINT)
1529 connection_flush(TO_CONN(conn));
1531 activate_signal(sig);
1533 return 0;
1536 /** Called when we get a TAKEOWNERSHIP command. Mark this connection
1537 * as an owning connection, so that we will exit if the connection
1538 * closes. */
1539 static int
1540 handle_control_takeownership(control_connection_t *conn, uint32_t len,
1541 const char *body)
1543 (void)len;
1544 (void)body;
1546 conn->is_owning_control_connection = 1;
1548 log_info(LD_CONTROL, "Control connection %d has taken ownership of this "
1549 "Tor instance.",
1550 (int)(conn->base_.s));
1552 send_control_done(conn);
1553 return 0;
1556 /** Return true iff <b>addr</b> is unusable as a mapaddress target because of
1557 * containing funny characters. */
1558 static int
1559 address_is_invalid_mapaddress_target(const char *addr)
1561 if (!strcmpstart(addr, "*."))
1562 return address_is_invalid_destination(addr+2, 1);
1563 else
1564 return address_is_invalid_destination(addr, 1);
1567 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1568 * and report success or failure. */
1569 static int
1570 handle_control_mapaddress(control_connection_t *conn, uint32_t len,
1571 const char *body)
1573 smartlist_t *elts;
1574 smartlist_t *lines;
1575 smartlist_t *reply;
1576 char *r;
1577 size_t sz;
1578 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
1580 lines = smartlist_new();
1581 elts = smartlist_new();
1582 reply = smartlist_new();
1583 smartlist_split_string(lines, body, " ",
1584 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1585 SMARTLIST_FOREACH_BEGIN(lines, char *, line) {
1586 tor_strlower(line);
1587 smartlist_split_string(elts, line, "=", 0, 2);
1588 if (smartlist_len(elts) == 2) {
1589 const char *from = smartlist_get(elts,0);
1590 const char *to = smartlist_get(elts,1);
1591 if (address_is_invalid_mapaddress_target(to)) {
1592 smartlist_add_asprintf(reply,
1593 "512-syntax error: invalid address '%s'", to);
1594 log_warn(LD_CONTROL,
1595 "Skipping invalid argument '%s' in MapAddress msg", to);
1596 } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0") ||
1597 !strcmp(from, "::")) {
1598 const char type =
1599 !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME :
1600 (!strcmp(from, "0.0.0.0") ? RESOLVED_TYPE_IPV4 : RESOLVED_TYPE_IPV6);
1601 const char *address = addressmap_register_virtual_address(
1602 type, tor_strdup(to));
1603 if (!address) {
1604 smartlist_add_asprintf(reply,
1605 "451-resource exhausted: skipping '%s'", line);
1606 log_warn(LD_CONTROL,
1607 "Unable to allocate address for '%s' in MapAddress msg",
1608 safe_str_client(line));
1609 } else {
1610 smartlist_add_asprintf(reply, "250-%s=%s", address, to);
1612 } else {
1613 const char *msg;
1614 if (addressmap_register_auto(from, to, 1,
1615 ADDRMAPSRC_CONTROLLER, &msg) < 0) {
1616 smartlist_add_asprintf(reply,
1617 "512-syntax error: invalid address mapping "
1618 " '%s': %s", line, msg);
1619 log_warn(LD_CONTROL,
1620 "Skipping invalid argument '%s' in MapAddress msg: %s",
1621 line, msg);
1622 } else {
1623 smartlist_add_asprintf(reply, "250-%s", line);
1626 } else {
1627 smartlist_add_asprintf(reply, "512-syntax error: mapping '%s' is "
1628 "not of expected form 'foo=bar'.", line);
1629 log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
1630 "number of items.",
1631 safe_str_client(line));
1633 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
1634 smartlist_clear(elts);
1635 } SMARTLIST_FOREACH_END(line);
1636 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1637 smartlist_free(lines);
1638 smartlist_free(elts);
1640 if (smartlist_len(reply)) {
1641 ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
1642 r = smartlist_join_strings(reply, "\r\n", 1, &sz);
1643 connection_write_to_buf(r, sz, TO_CONN(conn));
1644 tor_free(r);
1645 } else {
1646 const char *response =
1647 "512 syntax error: not enough arguments to mapaddress.\r\n";
1648 connection_write_to_buf(response, strlen(response), TO_CONN(conn));
1651 SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
1652 smartlist_free(reply);
1653 return 0;
1656 /** Implementation helper for GETINFO: knows the answers for various
1657 * trivial-to-implement questions. */
1658 static int
1659 getinfo_helper_misc(control_connection_t *conn, const char *question,
1660 char **answer, const char **errmsg)
1662 (void) conn;
1663 if (!strcmp(question, "version")) {
1664 *answer = tor_strdup(get_version());
1665 } else if (!strcmp(question, "bw-event-cache")) {
1666 *answer = get_bw_samples();
1667 } else if (!strcmp(question, "config-file")) {
1668 const char *a = get_torrc_fname(0);
1669 if (a)
1670 *answer = tor_strdup(a);
1671 } else if (!strcmp(question, "config-defaults-file")) {
1672 const char *a = get_torrc_fname(1);
1673 if (a)
1674 *answer = tor_strdup(a);
1675 } else if (!strcmp(question, "config-text")) {
1676 *answer = options_dump(get_options(), OPTIONS_DUMP_MINIMAL);
1677 } else if (!strcmp(question, "info/names")) {
1678 *answer = list_getinfo_options();
1679 } else if (!strcmp(question, "dormant")) {
1680 int dormant = rep_hist_circbuilding_dormant(time(NULL));
1681 *answer = tor_strdup(dormant ? "1" : "0");
1682 } else if (!strcmp(question, "events/names")) {
1683 int i;
1684 smartlist_t *event_names = smartlist_new();
1686 for (i = 0; control_event_table[i].event_name != NULL; ++i) {
1687 smartlist_add(event_names, (char *)control_event_table[i].event_name);
1690 *answer = smartlist_join_strings(event_names, " ", 0, NULL);
1692 smartlist_free(event_names);
1693 } else if (!strcmp(question, "signal/names")) {
1694 smartlist_t *signal_names = smartlist_new();
1695 int j;
1696 for (j = 0; signal_table[j].signal_name != NULL; ++j) {
1697 smartlist_add(signal_names, (char*)signal_table[j].signal_name);
1700 *answer = smartlist_join_strings(signal_names, " ", 0, NULL);
1702 smartlist_free(signal_names);
1703 } else if (!strcmp(question, "features/names")) {
1704 *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1705 } else if (!strcmp(question, "address")) {
1706 uint32_t addr;
1707 if (router_pick_published_address(get_options(), &addr, 0) < 0) {
1708 *errmsg = "Address unknown";
1709 return -1;
1711 *answer = tor_dup_ip(addr);
1712 } else if (!strcmp(question, "traffic/read")) {
1713 tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_read()));
1714 } else if (!strcmp(question, "traffic/written")) {
1715 tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_written()));
1716 } else if (!strcmp(question, "process/pid")) {
1717 int myPid = -1;
1719 #ifdef _WIN32
1720 myPid = _getpid();
1721 #else
1722 myPid = getpid();
1723 #endif
1725 tor_asprintf(answer, "%d", myPid);
1726 } else if (!strcmp(question, "process/uid")) {
1727 #ifdef _WIN32
1728 *answer = tor_strdup("-1");
1729 #else
1730 int myUid = geteuid();
1731 tor_asprintf(answer, "%d", myUid);
1732 #endif
1733 } else if (!strcmp(question, "process/user")) {
1734 #ifdef _WIN32
1735 *answer = tor_strdup("");
1736 #else
1737 int myUid = geteuid();
1738 const struct passwd *myPwEntry = tor_getpwuid(myUid);
1740 if (myPwEntry) {
1741 *answer = tor_strdup(myPwEntry->pw_name);
1742 } else {
1743 *answer = tor_strdup("");
1745 #endif
1746 } else if (!strcmp(question, "process/descriptor-limit")) {
1747 int max_fds = get_max_sockets();
1748 tor_asprintf(answer, "%d", max_fds);
1749 } else if (!strcmp(question, "limits/max-mem-in-queues")) {
1750 tor_asprintf(answer, U64_FORMAT,
1751 U64_PRINTF_ARG(get_options()->MaxMemInQueues));
1752 } else if (!strcmp(question, "fingerprint")) {
1753 crypto_pk_t *server_key;
1754 if (!server_mode(get_options())) {
1755 *errmsg = "Not running in server mode";
1756 return -1;
1758 server_key = get_server_identity_key();
1759 *answer = tor_malloc(HEX_DIGEST_LEN+1);
1760 crypto_pk_get_fingerprint(server_key, *answer, 0);
1762 return 0;
1765 /** Awful hack: return a newly allocated string based on a routerinfo and
1766 * (possibly) an extrainfo, sticking the read-history and write-history from
1767 * <b>ei</b> into the resulting string. The thing you get back won't
1768 * necessarily have a valid signature.
1770 * New code should never use this; it's for backward compatibility.
1772 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1773 * not be NUL-terminated. */
1774 static char *
1775 munge_extrainfo_into_routerinfo(const char *ri_body,
1776 const signed_descriptor_t *ri,
1777 const signed_descriptor_t *ei)
1779 char *out = NULL, *outp;
1780 int i;
1781 const char *router_sig;
1782 const char *ei_body = signed_descriptor_get_body(ei);
1783 size_t ri_len = ri->signed_descriptor_len;
1784 size_t ei_len = ei->signed_descriptor_len;
1785 if (!ei_body)
1786 goto bail;
1788 outp = out = tor_malloc(ri_len+ei_len+1);
1789 if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
1790 goto bail;
1791 ++router_sig;
1792 memcpy(out, ri_body, router_sig-ri_body);
1793 outp += router_sig-ri_body;
1795 for (i=0; i < 2; ++i) {
1796 const char *kwd = i ? "\nwrite-history " : "\nread-history ";
1797 const char *cp, *eol;
1798 if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
1799 continue;
1800 ++cp;
1801 if (!(eol = memchr(cp, '\n', ei_len - (cp-ei_body))))
1802 continue;
1803 memcpy(outp, cp, eol-cp+1);
1804 outp += eol-cp+1;
1806 memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
1807 *outp++ = '\0';
1808 tor_assert(outp-out < (int)(ri_len+ei_len+1));
1810 return out;
1811 bail:
1812 tor_free(out);
1813 return tor_strndup(ri_body, ri->signed_descriptor_len);
1816 /** Implementation helper for GETINFO: answers requests for information about
1817 * which ports are bound. */
1818 static int
1819 getinfo_helper_listeners(control_connection_t *control_conn,
1820 const char *question,
1821 char **answer, const char **errmsg)
1823 int type;
1824 smartlist_t *res;
1826 (void)control_conn;
1827 (void)errmsg;
1829 if (!strcmp(question, "net/listeners/or"))
1830 type = CONN_TYPE_OR_LISTENER;
1831 else if (!strcmp(question, "net/listeners/dir"))
1832 type = CONN_TYPE_DIR_LISTENER;
1833 else if (!strcmp(question, "net/listeners/socks"))
1834 type = CONN_TYPE_AP_LISTENER;
1835 else if (!strcmp(question, "net/listeners/trans"))
1836 type = CONN_TYPE_AP_TRANS_LISTENER;
1837 else if (!strcmp(question, "net/listeners/natd"))
1838 type = CONN_TYPE_AP_NATD_LISTENER;
1839 else if (!strcmp(question, "net/listeners/dns"))
1840 type = CONN_TYPE_AP_DNS_LISTENER;
1841 else if (!strcmp(question, "net/listeners/control"))
1842 type = CONN_TYPE_CONTROL_LISTENER;
1843 else
1844 return 0; /* unknown key */
1846 res = smartlist_new();
1847 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
1848 struct sockaddr_storage ss;
1849 socklen_t ss_len = sizeof(ss);
1851 if (conn->type != type || conn->marked_for_close || !SOCKET_OK(conn->s))
1852 continue;
1854 if (getsockname(conn->s, (struct sockaddr *)&ss, &ss_len) < 0) {
1855 smartlist_add_asprintf(res, "%s:%d", conn->address, (int)conn->port);
1856 } else {
1857 char *tmp = tor_sockaddr_to_str((struct sockaddr *)&ss);
1858 smartlist_add(res, esc_for_log(tmp));
1859 tor_free(tmp);
1862 } SMARTLIST_FOREACH_END(conn);
1864 *answer = smartlist_join_strings(res, " ", 0, NULL);
1866 SMARTLIST_FOREACH(res, char *, cp, tor_free(cp));
1867 smartlist_free(res);
1868 return 0;
1871 /** Implementation helper for GETINFO: knows the answers for questions about
1872 * directory information. */
1873 static int
1874 getinfo_helper_dir(control_connection_t *control_conn,
1875 const char *question, char **answer,
1876 const char **errmsg)
1878 (void) control_conn;
1879 if (!strcmpstart(question, "desc/id/")) {
1880 const routerinfo_t *ri = NULL;
1881 const node_t *node = node_get_by_hex_id(question+strlen("desc/id/"));
1882 if (node)
1883 ri = node->ri;
1884 if (ri) {
1885 const char *body = signed_descriptor_get_body(&ri->cache_info);
1886 if (body)
1887 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1889 } else if (!strcmpstart(question, "desc/name/")) {
1890 const routerinfo_t *ri = NULL;
1891 /* XXX Setting 'warn_if_unnamed' here is a bit silly -- the
1892 * warning goes to the user, not to the controller. */
1893 const node_t *node =
1894 node_get_by_nickname(question+strlen("desc/name/"), 1);
1895 if (node)
1896 ri = node->ri;
1897 if (ri) {
1898 const char *body = signed_descriptor_get_body(&ri->cache_info);
1899 if (body)
1900 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1902 } else if (!strcmp(question, "desc/all-recent")) {
1903 routerlist_t *routerlist = router_get_routerlist();
1904 smartlist_t *sl = smartlist_new();
1905 if (routerlist && routerlist->routers) {
1906 SMARTLIST_FOREACH(routerlist->routers, const routerinfo_t *, ri,
1908 const char *body = signed_descriptor_get_body(&ri->cache_info);
1909 if (body)
1910 smartlist_add(sl,
1911 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1914 *answer = smartlist_join_strings(sl, "", 0, NULL);
1915 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1916 smartlist_free(sl);
1917 } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
1918 /* XXXX Remove this once Torstat asks for extrainfos. */
1919 routerlist_t *routerlist = router_get_routerlist();
1920 smartlist_t *sl = smartlist_new();
1921 if (routerlist && routerlist->routers) {
1922 SMARTLIST_FOREACH_BEGIN(routerlist->routers, const routerinfo_t *, ri) {
1923 const char *body = signed_descriptor_get_body(&ri->cache_info);
1924 signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
1925 ri->cache_info.extra_info_digest);
1926 if (ei && body) {
1927 smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
1928 &ri->cache_info, ei));
1929 } else if (body) {
1930 smartlist_add(sl,
1931 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1933 } SMARTLIST_FOREACH_END(ri);
1935 *answer = smartlist_join_strings(sl, "", 0, NULL);
1936 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1937 smartlist_free(sl);
1938 } else if (!strcmpstart(question, "hs/client/desc/id/")) {
1939 rend_cache_entry_t *e = NULL;
1941 question += strlen("hs/client/desc/id/");
1942 if (strlen(question) != REND_SERVICE_ID_LEN_BASE32) {
1943 *errmsg = "Invalid address";
1944 return -1;
1947 if (!rend_cache_lookup_entry(question, -1, &e)) {
1948 /* Descriptor found in cache */
1949 *answer = tor_strdup(e->desc);
1950 } else {
1951 *errmsg = "Not found in cache";
1952 return -1;
1954 } else if (!strcmpstart(question, "hs/service/desc/id/")) {
1955 rend_cache_entry_t *e = NULL;
1957 question += strlen("hs/service/desc/id/");
1958 if (strlen(question) != REND_SERVICE_ID_LEN_BASE32) {
1959 *errmsg = "Invalid address";
1960 return -1;
1963 if (!rend_cache_lookup_v2_desc_as_service(question, &e)) {
1964 /* Descriptor found in cache */
1965 *answer = tor_strdup(e->desc);
1966 } else {
1967 *errmsg = "Not found in cache";
1968 return -1;
1970 } else if (!strcmpstart(question, "md/id/")) {
1971 const node_t *node = node_get_by_hex_id(question+strlen("md/id/"));
1972 const microdesc_t *md = NULL;
1973 if (node) md = node->md;
1974 if (md && md->body) {
1975 *answer = tor_strndup(md->body, md->bodylen);
1977 } else if (!strcmpstart(question, "md/name/")) {
1978 /* XXX Setting 'warn_if_unnamed' here is a bit silly -- the
1979 * warning goes to the user, not to the controller. */
1980 const node_t *node = node_get_by_nickname(question+strlen("md/name/"), 1);
1981 /* XXXX duplicated code */
1982 const microdesc_t *md = NULL;
1983 if (node) md = node->md;
1984 if (md && md->body) {
1985 *answer = tor_strndup(md->body, md->bodylen);
1987 } else if (!strcmpstart(question, "desc-annotations/id/")) {
1988 const routerinfo_t *ri = NULL;
1989 const node_t *node =
1990 node_get_by_hex_id(question+strlen("desc-annotations/id/"));
1991 if (node)
1992 ri = node->ri;
1993 if (ri) {
1994 const char *annotations =
1995 signed_descriptor_get_annotations(&ri->cache_info);
1996 if (annotations)
1997 *answer = tor_strndup(annotations,
1998 ri->cache_info.annotations_len);
2000 } else if (!strcmpstart(question, "dir/server/")) {
2001 size_t answer_len = 0;
2002 char *url = NULL;
2003 smartlist_t *descs = smartlist_new();
2004 const char *msg;
2005 int res;
2006 char *cp;
2007 tor_asprintf(&url, "/tor/%s", question+4);
2008 res = dirserv_get_routerdescs(descs, url, &msg);
2009 if (res) {
2010 log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
2011 smartlist_free(descs);
2012 tor_free(url);
2013 *errmsg = msg;
2014 return -1;
2016 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
2017 answer_len += sd->signed_descriptor_len);
2018 cp = *answer = tor_malloc(answer_len+1);
2019 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
2021 memcpy(cp, signed_descriptor_get_body(sd),
2022 sd->signed_descriptor_len);
2023 cp += sd->signed_descriptor_len;
2025 *cp = '\0';
2026 tor_free(url);
2027 smartlist_free(descs);
2028 } else if (!strcmpstart(question, "dir/status/")) {
2029 *answer = tor_strdup("");
2030 } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
2031 if (directory_caches_dir_info(get_options())) {
2032 const cached_dir_t *consensus = dirserv_get_consensus("ns");
2033 if (consensus)
2034 *answer = tor_strdup(consensus->dir);
2036 if (!*answer) { /* try loading it from disk */
2037 char *filename = get_datadir_fname("cached-consensus");
2038 *answer = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
2039 tor_free(filename);
2040 if (!*answer) { /* generate an error */
2041 *errmsg = "Could not open cached consensus. "
2042 "Make sure FetchUselessDescriptors is set to 1.";
2043 return -1;
2046 } else if (!strcmp(question, "network-status")) { /* v1 */
2047 routerlist_t *routerlist = router_get_routerlist();
2048 if (!routerlist || !routerlist->routers ||
2049 list_server_status_v1(routerlist->routers, answer, 1) < 0) {
2050 return -1;
2052 } else if (!strcmpstart(question, "extra-info/digest/")) {
2053 question += strlen("extra-info/digest/");
2054 if (strlen(question) == HEX_DIGEST_LEN) {
2055 char d[DIGEST_LEN];
2056 signed_descriptor_t *sd = NULL;
2057 if (base16_decode(d, sizeof(d), question, strlen(question))
2058 != sizeof(d)) {
2059 /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
2060 * but I don't want to risk affecting other parts of the code,
2061 * especially since the rules for using our own extrainfo (including
2062 * when it might be freed) are different from those for using one
2063 * we have downloaded. */
2064 if (router_extrainfo_digest_is_me(d))
2065 sd = &(router_get_my_extrainfo()->cache_info);
2066 else
2067 sd = extrainfo_get_by_descriptor_digest(d);
2069 if (sd) {
2070 const char *body = signed_descriptor_get_body(sd);
2071 if (body)
2072 *answer = tor_strndup(body, sd->signed_descriptor_len);
2077 return 0;
2080 /** Given a smartlist of 20-byte digests, return a newly allocated string
2081 * containing each of those digests in order, formatted in HEX, and terminated
2082 * with a newline. */
2083 static char *
2084 digest_list_to_string(const smartlist_t *sl)
2086 int len;
2087 char *result, *s;
2089 /* Allow for newlines, and a \0 at the end */
2090 len = smartlist_len(sl) * (HEX_DIGEST_LEN + 1) + 1;
2091 result = tor_malloc_zero(len);
2093 s = result;
2094 SMARTLIST_FOREACH_BEGIN(sl, const char *, digest) {
2095 base16_encode(s, HEX_DIGEST_LEN + 1, digest, DIGEST_LEN);
2096 s[HEX_DIGEST_LEN] = '\n';
2097 s += HEX_DIGEST_LEN + 1;
2098 } SMARTLIST_FOREACH_END(digest);
2099 *s = '\0';
2101 return result;
2104 /** Turn a download_status_t into a human-readable description in a newly
2105 * allocated string. The format is specified in control-spec.txt, under
2106 * the documentation for "GETINFO download/..." . */
2107 static char *
2108 download_status_to_string(const download_status_t *dl)
2110 char *rv = NULL, *tmp;
2111 char tbuf[ISO_TIME_LEN+1];
2112 const char *schedule_str, *want_authority_str;
2113 const char *increment_on_str, *backoff_str;
2115 if (dl) {
2116 /* Get some substrings of the eventual output ready */
2117 format_iso_time(tbuf, dl->next_attempt_at);
2119 switch (dl->schedule) {
2120 case DL_SCHED_GENERIC:
2121 schedule_str = "DL_SCHED_GENERIC";
2122 break;
2123 case DL_SCHED_CONSENSUS:
2124 schedule_str = "DL_SCHED_CONSENSUS";
2125 break;
2126 case DL_SCHED_BRIDGE:
2127 schedule_str = "DL_SCHED_BRIDGE";
2128 break;
2129 default:
2130 schedule_str = "unknown";
2131 break;
2134 switch (dl->want_authority) {
2135 case DL_WANT_ANY_DIRSERVER:
2136 want_authority_str = "DL_WANT_ANY_DIRSERVER";
2137 break;
2138 case DL_WANT_AUTHORITY:
2139 want_authority_str = "DL_WANT_AUTHORITY";
2140 break;
2141 default:
2142 want_authority_str = "unknown";
2143 break;
2146 switch (dl->increment_on) {
2147 case DL_SCHED_INCREMENT_FAILURE:
2148 increment_on_str = "DL_SCHED_INCREMENT_FAILURE";
2149 break;
2150 case DL_SCHED_INCREMENT_ATTEMPT:
2151 increment_on_str = "DL_SCHED_INCREMENT_ATTEMPT";
2152 break;
2153 default:
2154 increment_on_str = "unknown";
2155 break;
2158 switch (dl->backoff) {
2159 case DL_SCHED_DETERMINISTIC:
2160 backoff_str = "DL_SCHED_DETERMINISTIC";
2161 break;
2162 case DL_SCHED_RANDOM_EXPONENTIAL:
2163 backoff_str = "DL_SCHED_RANDOM_EXPONENTIAL";
2164 break;
2165 default:
2166 backoff_str = "unknown";
2167 break;
2170 /* Now assemble them */
2171 tor_asprintf(&tmp,
2172 "next-attempt-at %s\n"
2173 "n-download-failures %u\n"
2174 "n-download-attempts %u\n"
2175 "schedule %s\n"
2176 "want-authority %s\n"
2177 "increment-on %s\n"
2178 "backoff %s\n",
2179 tbuf,
2180 dl->n_download_failures,
2181 dl->n_download_attempts,
2182 schedule_str,
2183 want_authority_str,
2184 increment_on_str,
2185 backoff_str);
2187 if (dl->backoff == DL_SCHED_RANDOM_EXPONENTIAL) {
2188 /* Additional fields become relevant in random-exponential mode */
2189 tor_asprintf(&rv,
2190 "%s"
2191 "last-backoff-position %u\n"
2192 "last-delay-used %d\n",
2193 tmp,
2194 dl->last_backoff_position,
2195 dl->last_delay_used);
2196 tor_free(tmp);
2197 } else {
2198 /* That was it */
2199 rv = tmp;
2203 return rv;
2206 /** Handle the consensus download cases for getinfo_helper_downloads() */
2207 STATIC void
2208 getinfo_helper_downloads_networkstatus(const char *flavor,
2209 download_status_t **dl_to_emit,
2210 const char **errmsg)
2213 * We get the one for the current bootstrapped status by default, or
2214 * take an extra /bootstrap or /running suffix
2216 if (strcmp(flavor, "ns") == 0) {
2217 *dl_to_emit = networkstatus_get_dl_status_by_flavor(FLAV_NS);
2218 } else if (strcmp(flavor, "ns/bootstrap") == 0) {
2219 *dl_to_emit = networkstatus_get_dl_status_by_flavor_bootstrap(FLAV_NS);
2220 } else if (strcmp(flavor, "ns/running") == 0 ) {
2221 *dl_to_emit = networkstatus_get_dl_status_by_flavor_running(FLAV_NS);
2222 } else if (strcmp(flavor, "microdesc") == 0) {
2223 *dl_to_emit = networkstatus_get_dl_status_by_flavor(FLAV_MICRODESC);
2224 } else if (strcmp(flavor, "microdesc/bootstrap") == 0) {
2225 *dl_to_emit =
2226 networkstatus_get_dl_status_by_flavor_bootstrap(FLAV_MICRODESC);
2227 } else if (strcmp(flavor, "microdesc/running") == 0) {
2228 *dl_to_emit =
2229 networkstatus_get_dl_status_by_flavor_running(FLAV_MICRODESC);
2230 } else {
2231 *errmsg = "Unknown flavor";
2235 /** Handle the cert download cases for getinfo_helper_downloads() */
2236 STATIC void
2237 getinfo_helper_downloads_cert(const char *fp_sk_req,
2238 download_status_t **dl_to_emit,
2239 smartlist_t **digest_list,
2240 const char **errmsg)
2242 const char *sk_req;
2243 char id_digest[DIGEST_LEN];
2244 char sk_digest[DIGEST_LEN];
2247 * We have to handle four cases; fp_sk_req is the request with
2248 * a prefix of "downloads/cert/" snipped off.
2250 * Case 1: fp_sk_req = "fps"
2251 * - We should emit a digest_list with a list of all the identity
2252 * fingerprints that can be queried for certificate download status;
2253 * get it by calling list_authority_ids_with_downloads().
2255 * Case 2: fp_sk_req = "fp/<fp>" for some fingerprint fp
2256 * - We want the default certificate for this identity fingerprint's
2257 * download status; this is the download we get from URLs starting
2258 * in /fp/ on the directory server. We can get it with
2259 * id_only_download_status_for_authority_id().
2261 * Case 3: fp_sk_req = "fp/<fp>/sks" for some fingerprint fp
2262 * - We want a list of all signing key digests for this identity
2263 * fingerprint which can be queried for certificate download status.
2264 * Get it with list_sk_digests_for_authority_id().
2266 * Case 4: fp_sk_req = "fp/<fp>/<sk>" for some fingerprint fp and
2267 * signing key digest sk
2268 * - We want the download status for the certificate for this specific
2269 * signing key and fingerprint. These correspond to the ones we get
2270 * from URLs starting in /fp-sk/ on the directory server. Get it with
2271 * list_sk_digests_for_authority_id().
2274 if (strcmp(fp_sk_req, "fps") == 0) {
2275 *digest_list = list_authority_ids_with_downloads();
2276 if (!(*digest_list)) {
2277 *errmsg = "Failed to get list of authority identity digests (!)";
2279 } else if (!strcmpstart(fp_sk_req, "fp/")) {
2280 fp_sk_req += strlen("fp/");
2281 /* Okay, look for another / to tell the fp from fp-sk cases */
2282 sk_req = strchr(fp_sk_req, '/');
2283 if (sk_req) {
2284 /* okay, split it here and try to parse <fp> */
2285 if (base16_decode(id_digest, DIGEST_LEN,
2286 fp_sk_req, sk_req - fp_sk_req) == DIGEST_LEN) {
2287 /* Skip past the '/' */
2288 ++sk_req;
2289 if (strcmp(sk_req, "sks") == 0) {
2290 /* We're asking for the list of signing key fingerprints */
2291 *digest_list = list_sk_digests_for_authority_id(id_digest);
2292 if (!(*digest_list)) {
2293 *errmsg = "Failed to get list of signing key digests for this "
2294 "authority identity digest";
2296 } else {
2297 /* We've got a signing key digest */
2298 if (base16_decode(sk_digest, DIGEST_LEN,
2299 sk_req, strlen(sk_req)) == DIGEST_LEN) {
2300 *dl_to_emit =
2301 download_status_for_authority_id_and_sk(id_digest, sk_digest);
2302 if (!(*dl_to_emit)) {
2303 *errmsg = "Failed to get download status for this identity/"
2304 "signing key digest pair";
2306 } else {
2307 *errmsg = "That didn't look like a signing key digest";
2310 } else {
2311 *errmsg = "That didn't look like an identity digest";
2313 } else {
2314 /* We're either in downloads/certs/fp/<fp>, or we can't parse <fp> */
2315 if (strlen(fp_sk_req) == HEX_DIGEST_LEN) {
2316 if (base16_decode(id_digest, DIGEST_LEN,
2317 fp_sk_req, strlen(fp_sk_req)) == DIGEST_LEN) {
2318 *dl_to_emit = id_only_download_status_for_authority_id(id_digest);
2319 if (!(*dl_to_emit)) {
2320 *errmsg = "Failed to get download status for this authority "
2321 "identity digest";
2323 } else {
2324 *errmsg = "That didn't look like a digest";
2326 } else {
2327 *errmsg = "That didn't look like a digest";
2330 } else {
2331 *errmsg = "Unknown certificate download status query";
2335 /** Handle the routerdesc download cases for getinfo_helper_downloads() */
2336 STATIC void
2337 getinfo_helper_downloads_desc(const char *desc_req,
2338 download_status_t **dl_to_emit,
2339 smartlist_t **digest_list,
2340 const char **errmsg)
2342 char desc_digest[DIGEST_LEN];
2344 * Two cases to handle here:
2346 * Case 1: desc_req = "descs"
2347 * - Emit a list of all router descriptor digests, which we get by
2348 * calling router_get_descriptor_digests(); this can return NULL
2349 * if we have no current ns-flavor consensus.
2351 * Case 2: desc_req = <fp>
2352 * - Check on the specified fingerprint and emit its download_status_t
2353 * using router_get_dl_status_by_descriptor_digest().
2356 if (strcmp(desc_req, "descs") == 0) {
2357 *digest_list = router_get_descriptor_digests();
2358 if (!(*digest_list)) {
2359 *errmsg = "We don't seem to have a networkstatus-flavored consensus";
2362 * Microdescs don't use the download_status_t mechanism, so we don't
2363 * answer queries about their downloads here; see microdesc.c.
2365 } else if (strlen(desc_req) == HEX_DIGEST_LEN) {
2366 if (base16_decode(desc_digest, DIGEST_LEN,
2367 desc_req, strlen(desc_req)) == DIGEST_LEN) {
2368 /* Okay we got a digest-shaped thing; try asking for it */
2369 *dl_to_emit = router_get_dl_status_by_descriptor_digest(desc_digest);
2370 if (!(*dl_to_emit)) {
2371 *errmsg = "No such descriptor digest found";
2373 } else {
2374 *errmsg = "That didn't look like a digest";
2376 } else {
2377 *errmsg = "Unknown router descriptor download status query";
2381 /** Handle the bridge download cases for getinfo_helper_downloads() */
2382 STATIC void
2383 getinfo_helper_downloads_bridge(const char *bridge_req,
2384 download_status_t **dl_to_emit,
2385 smartlist_t **digest_list,
2386 const char **errmsg)
2388 char bridge_digest[DIGEST_LEN];
2390 * Two cases to handle here:
2392 * Case 1: bridge_req = "bridges"
2393 * - Emit a list of all bridge identity digests, which we get by
2394 * calling list_bridge_identities(); this can return NULL if we are
2395 * not using bridges.
2397 * Case 2: bridge_req = <fp>
2398 * - Check on the specified fingerprint and emit its download_status_t
2399 * using get_bridge_dl_status_by_id().
2402 if (strcmp(bridge_req, "bridges") == 0) {
2403 *digest_list = list_bridge_identities();
2404 if (!(*digest_list)) {
2405 *errmsg = "We don't seem to be using bridges";
2407 } else if (strlen(bridge_req) == HEX_DIGEST_LEN) {
2408 if (base16_decode(bridge_digest, DIGEST_LEN,
2409 bridge_req, strlen(bridge_req)) == DIGEST_LEN) {
2410 /* Okay we got a digest-shaped thing; try asking for it */
2411 *dl_to_emit = get_bridge_dl_status_by_id(bridge_digest);
2412 if (!(*dl_to_emit)) {
2413 *errmsg = "No such bridge identity digest found";
2415 } else {
2416 *errmsg = "That didn't look like a digest";
2418 } else {
2419 *errmsg = "Unknown bridge descriptor download status query";
2423 /** Implementation helper for GETINFO: knows the answers for questions about
2424 * download status information. */
2425 STATIC int
2426 getinfo_helper_downloads(control_connection_t *control_conn,
2427 const char *question, char **answer,
2428 const char **errmsg)
2430 download_status_t *dl_to_emit = NULL;
2431 smartlist_t *digest_list = NULL;
2433 /* Assert args are sane */
2434 tor_assert(control_conn != NULL);
2435 tor_assert(question != NULL);
2436 tor_assert(answer != NULL);
2437 tor_assert(errmsg != NULL);
2439 /* We check for this later to see if we should supply a default */
2440 *errmsg = NULL;
2442 /* Are we after networkstatus downloads? */
2443 if (!strcmpstart(question, "downloads/networkstatus/")) {
2444 getinfo_helper_downloads_networkstatus(
2445 question + strlen("downloads/networkstatus/"),
2446 &dl_to_emit, errmsg);
2447 /* Certificates? */
2448 } else if (!strcmpstart(question, "downloads/cert/")) {
2449 getinfo_helper_downloads_cert(
2450 question + strlen("downloads/cert/"),
2451 &dl_to_emit, &digest_list, errmsg);
2452 /* Router descriptors? */
2453 } else if (!strcmpstart(question, "downloads/desc/")) {
2454 getinfo_helper_downloads_desc(
2455 question + strlen("downloads/desc/"),
2456 &dl_to_emit, &digest_list, errmsg);
2457 /* Bridge descriptors? */
2458 } else if (!strcmpstart(question, "downloads/bridge/")) {
2459 getinfo_helper_downloads_bridge(
2460 question + strlen("downloads/bridge/"),
2461 &dl_to_emit, &digest_list, errmsg);
2462 } else {
2463 *errmsg = "Unknown download status query";
2466 if (dl_to_emit) {
2467 *answer = download_status_to_string(dl_to_emit);
2469 return 0;
2470 } else if (digest_list) {
2471 *answer = digest_list_to_string(digest_list);
2472 SMARTLIST_FOREACH(digest_list, void *, s, tor_free(s));
2473 smartlist_free(digest_list);
2475 return 0;
2476 } else {
2477 if (!(*errmsg)) {
2478 *errmsg = "Unknown error";
2481 return -1;
2485 /** Allocate and return a description of <b>circ</b>'s current status,
2486 * including its path (if any). */
2487 static char *
2488 circuit_describe_status_for_controller(origin_circuit_t *circ)
2490 char *rv;
2491 smartlist_t *descparts = smartlist_new();
2494 char *vpath = circuit_list_path_for_controller(circ);
2495 if (*vpath) {
2496 smartlist_add(descparts, vpath);
2497 } else {
2498 tor_free(vpath); /* empty path; don't put an extra space in the result */
2503 cpath_build_state_t *build_state = circ->build_state;
2504 smartlist_t *flaglist = smartlist_new();
2505 char *flaglist_joined;
2507 if (build_state->onehop_tunnel)
2508 smartlist_add(flaglist, (void *)"ONEHOP_TUNNEL");
2509 if (build_state->is_internal)
2510 smartlist_add(flaglist, (void *)"IS_INTERNAL");
2511 if (build_state->need_capacity)
2512 smartlist_add(flaglist, (void *)"NEED_CAPACITY");
2513 if (build_state->need_uptime)
2514 smartlist_add(flaglist, (void *)"NEED_UPTIME");
2516 /* Only emit a BUILD_FLAGS argument if it will have a non-empty value. */
2517 if (smartlist_len(flaglist)) {
2518 flaglist_joined = smartlist_join_strings(flaglist, ",", 0, NULL);
2520 smartlist_add_asprintf(descparts, "BUILD_FLAGS=%s", flaglist_joined);
2522 tor_free(flaglist_joined);
2525 smartlist_free(flaglist);
2528 smartlist_add_asprintf(descparts, "PURPOSE=%s",
2529 circuit_purpose_to_controller_string(circ->base_.purpose));
2532 const char *hs_state =
2533 circuit_purpose_to_controller_hs_state_string(circ->base_.purpose);
2535 if (hs_state != NULL) {
2536 smartlist_add_asprintf(descparts, "HS_STATE=%s", hs_state);
2540 if (circ->rend_data != NULL) {
2541 smartlist_add_asprintf(descparts, "REND_QUERY=%s",
2542 circ->rend_data->onion_address);
2546 char tbuf[ISO_TIME_USEC_LEN+1];
2547 format_iso_time_nospace_usec(tbuf, &circ->base_.timestamp_created);
2549 smartlist_add_asprintf(descparts, "TIME_CREATED=%s", tbuf);
2552 // Show username and/or password if available.
2553 if (circ->socks_username_len > 0) {
2554 char* socks_username_escaped = esc_for_log_len(circ->socks_username,
2555 (size_t) circ->socks_username_len);
2556 smartlist_add_asprintf(descparts, "SOCKS_USERNAME=%s",
2557 socks_username_escaped);
2558 tor_free(socks_username_escaped);
2560 if (circ->socks_password_len > 0) {
2561 char* socks_password_escaped = esc_for_log_len(circ->socks_password,
2562 (size_t) circ->socks_password_len);
2563 smartlist_add_asprintf(descparts, "SOCKS_PASSWORD=%s",
2564 socks_password_escaped);
2565 tor_free(socks_password_escaped);
2568 rv = smartlist_join_strings(descparts, " ", 0, NULL);
2570 SMARTLIST_FOREACH(descparts, char *, cp, tor_free(cp));
2571 smartlist_free(descparts);
2573 return rv;
2576 /** Implementation helper for GETINFO: knows how to generate summaries of the
2577 * current states of things we send events about. */
2578 static int
2579 getinfo_helper_events(control_connection_t *control_conn,
2580 const char *question, char **answer,
2581 const char **errmsg)
2583 const or_options_t *options = get_options();
2584 (void) control_conn;
2585 if (!strcmp(question, "circuit-status")) {
2586 smartlist_t *status = smartlist_new();
2587 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ_) {
2588 origin_circuit_t *circ;
2589 char *circdesc;
2590 const char *state;
2591 if (! CIRCUIT_IS_ORIGIN(circ_) || circ_->marked_for_close)
2592 continue;
2593 circ = TO_ORIGIN_CIRCUIT(circ_);
2595 if (circ->base_.state == CIRCUIT_STATE_OPEN)
2596 state = "BUILT";
2597 else if (circ->cpath)
2598 state = "EXTENDED";
2599 else
2600 state = "LAUNCHED";
2602 circdesc = circuit_describe_status_for_controller(circ);
2604 smartlist_add_asprintf(status, "%lu %s%s%s",
2605 (unsigned long)circ->global_identifier,
2606 state, *circdesc ? " " : "", circdesc);
2607 tor_free(circdesc);
2609 SMARTLIST_FOREACH_END(circ_);
2610 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
2611 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
2612 smartlist_free(status);
2613 } else if (!strcmp(question, "stream-status")) {
2614 smartlist_t *conns = get_connection_array();
2615 smartlist_t *status = smartlist_new();
2616 char buf[256];
2617 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
2618 const char *state;
2619 entry_connection_t *conn;
2620 circuit_t *circ;
2621 origin_circuit_t *origin_circ = NULL;
2622 if (base_conn->type != CONN_TYPE_AP ||
2623 base_conn->marked_for_close ||
2624 base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
2625 base_conn->state == AP_CONN_STATE_NATD_WAIT)
2626 continue;
2627 conn = TO_ENTRY_CONN(base_conn);
2628 switch (base_conn->state)
2630 case AP_CONN_STATE_CONTROLLER_WAIT:
2631 case AP_CONN_STATE_CIRCUIT_WAIT:
2632 if (conn->socks_request &&
2633 SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
2634 state = "NEWRESOLVE";
2635 else
2636 state = "NEW";
2637 break;
2638 case AP_CONN_STATE_RENDDESC_WAIT:
2639 case AP_CONN_STATE_CONNECT_WAIT:
2640 state = "SENTCONNECT"; break;
2641 case AP_CONN_STATE_RESOLVE_WAIT:
2642 state = "SENTRESOLVE"; break;
2643 case AP_CONN_STATE_OPEN:
2644 state = "SUCCEEDED"; break;
2645 default:
2646 log_warn(LD_BUG, "Asked for stream in unknown state %d",
2647 base_conn->state);
2648 continue;
2650 circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
2651 if (circ && CIRCUIT_IS_ORIGIN(circ))
2652 origin_circ = TO_ORIGIN_CIRCUIT(circ);
2653 write_stream_target_to_buf(conn, buf, sizeof(buf));
2654 smartlist_add_asprintf(status, "%lu %s %lu %s",
2655 (unsigned long) base_conn->global_identifier,state,
2656 origin_circ?
2657 (unsigned long)origin_circ->global_identifier : 0ul,
2658 buf);
2659 } SMARTLIST_FOREACH_END(base_conn);
2660 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
2661 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
2662 smartlist_free(status);
2663 } else if (!strcmp(question, "orconn-status")) {
2664 smartlist_t *conns = get_connection_array();
2665 smartlist_t *status = smartlist_new();
2666 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
2667 const char *state;
2668 char name[128];
2669 or_connection_t *conn;
2670 if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
2671 continue;
2672 conn = TO_OR_CONN(base_conn);
2673 if (conn->base_.state == OR_CONN_STATE_OPEN)
2674 state = "CONNECTED";
2675 else if (conn->nickname)
2676 state = "LAUNCHED";
2677 else
2678 state = "NEW";
2679 orconn_target_get_name(name, sizeof(name), conn);
2680 smartlist_add_asprintf(status, "%s %s", name, state);
2681 } SMARTLIST_FOREACH_END(base_conn);
2682 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
2683 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
2684 smartlist_free(status);
2685 } else if (!strcmpstart(question, "address-mappings/")) {
2686 time_t min_e, max_e;
2687 smartlist_t *mappings;
2688 question += strlen("address-mappings/");
2689 if (!strcmp(question, "all")) {
2690 min_e = 0; max_e = TIME_MAX;
2691 } else if (!strcmp(question, "cache")) {
2692 min_e = 2; max_e = TIME_MAX;
2693 } else if (!strcmp(question, "config")) {
2694 min_e = 0; max_e = 0;
2695 } else if (!strcmp(question, "control")) {
2696 min_e = 1; max_e = 1;
2697 } else {
2698 return 0;
2700 mappings = smartlist_new();
2701 addressmap_get_mappings(mappings, min_e, max_e, 1);
2702 *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
2703 SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
2704 smartlist_free(mappings);
2705 } else if (!strcmpstart(question, "status/")) {
2706 /* Note that status/ is not a catch-all for events; there's only supposed
2707 * to be a status GETINFO if there's a corresponding STATUS event. */
2708 if (!strcmp(question, "status/circuit-established")) {
2709 *answer = tor_strdup(have_completed_a_circuit() ? "1" : "0");
2710 } else if (!strcmp(question, "status/enough-dir-info")) {
2711 *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
2712 } else if (!strcmp(question, "status/good-server-descriptor") ||
2713 !strcmp(question, "status/accepted-server-descriptor")) {
2714 /* They're equivalent for now, until we can figure out how to make
2715 * good-server-descriptor be what we want. See comment in
2716 * control-spec.txt. */
2717 *answer = tor_strdup(directories_have_accepted_server_descriptor()
2718 ? "1" : "0");
2719 } else if (!strcmp(question, "status/reachability-succeeded/or")) {
2720 *answer = tor_strdup(check_whether_orport_reachable(options) ?
2721 "1" : "0");
2722 } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
2723 *answer = tor_strdup(check_whether_dirport_reachable(options) ?
2724 "1" : "0");
2725 } else if (!strcmp(question, "status/reachability-succeeded")) {
2726 tor_asprintf(answer, "OR=%d DIR=%d",
2727 check_whether_orport_reachable(options) ? 1 : 0,
2728 check_whether_dirport_reachable(options) ? 1 : 0);
2729 } else if (!strcmp(question, "status/bootstrap-phase")) {
2730 *answer = tor_strdup(last_sent_bootstrap_message);
2731 } else if (!strcmpstart(question, "status/version/")) {
2732 int is_server = server_mode(options);
2733 networkstatus_t *c = networkstatus_get_latest_consensus();
2734 version_status_t status;
2735 const char *recommended;
2736 if (c) {
2737 recommended = is_server ? c->server_versions : c->client_versions;
2738 status = tor_version_is_obsolete(VERSION, recommended);
2739 } else {
2740 recommended = "?";
2741 status = VS_UNKNOWN;
2744 if (!strcmp(question, "status/version/recommended")) {
2745 *answer = tor_strdup(recommended);
2746 return 0;
2748 if (!strcmp(question, "status/version/current")) {
2749 switch (status)
2751 case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
2752 case VS_OLD: *answer = tor_strdup("obsolete"); break;
2753 case VS_NEW: *answer = tor_strdup("new"); break;
2754 case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
2755 case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
2756 case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
2757 case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
2758 default: tor_fragile_assert();
2760 } else if (!strcmp(question, "status/version/num-versioning") ||
2761 !strcmp(question, "status/version/num-concurring")) {
2762 tor_asprintf(answer, "%d", get_n_authorities(V3_DIRINFO));
2763 log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
2764 "information", question);
2766 } else if (!strcmp(question, "status/clients-seen")) {
2767 char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
2768 if (!bridge_stats) {
2769 *errmsg = "No bridge-client stats available";
2770 return -1;
2772 *answer = bridge_stats;
2773 } else if (!strcmp(question, "status/fresh-relay-descs")) {
2774 if (!server_mode(options)) {
2775 *errmsg = "Only relays have descriptors";
2776 return -1;
2778 routerinfo_t *r;
2779 extrainfo_t *e;
2780 if (router_build_fresh_descriptor(&r, &e) < 0) {
2781 *errmsg = "Error generating descriptor";
2782 return -1;
2784 size_t size = r->cache_info.signed_descriptor_len + 1;
2785 if (e) {
2786 size += e->cache_info.signed_descriptor_len + 1;
2788 tor_assert(r->cache_info.signed_descriptor_len);
2789 char *descs = tor_malloc(size);
2790 char *cp = descs;
2791 memcpy(cp, signed_descriptor_get_body(&r->cache_info),
2792 r->cache_info.signed_descriptor_len);
2793 cp += r->cache_info.signed_descriptor_len - 1;
2794 if (e) {
2795 if (cp[0] == '\0') {
2796 cp[0] = '\n';
2797 } else if (cp[0] != '\n') {
2798 cp[1] = '\n';
2799 cp++;
2801 memcpy(cp, signed_descriptor_get_body(&e->cache_info),
2802 e->cache_info.signed_descriptor_len);
2803 cp += e->cache_info.signed_descriptor_len - 1;
2805 if (cp[0] == '\n') {
2806 cp[0] = '\0';
2807 } else if (cp[0] != '\0') {
2808 cp[1] = '\0';
2810 *answer = descs;
2811 routerinfo_free(r);
2812 extrainfo_free(e);
2813 } else {
2814 return 0;
2817 return 0;
2820 /** Implementation helper for GETINFO: knows how to enumerate hidden services
2821 * created via the control port. */
2822 static int
2823 getinfo_helper_onions(control_connection_t *control_conn,
2824 const char *question, char **answer,
2825 const char **errmsg)
2827 smartlist_t *onion_list = NULL;
2829 if (control_conn && !strcmp(question, "onions/current")) {
2830 onion_list = control_conn->ephemeral_onion_services;
2831 } else if (!strcmp(question, "onions/detached")) {
2832 onion_list = detached_onion_services;
2833 } else {
2834 return 0;
2836 if (!onion_list || smartlist_len(onion_list) == 0) {
2837 if (errmsg) {
2838 *errmsg = "No onion services of the specified type.";
2840 return -1;
2842 if (answer) {
2843 *answer = smartlist_join_strings(onion_list, "\r\n", 0, NULL);
2846 return 0;
2849 /** Implementation helper for GETINFO: answers queries about network
2850 * liveness. */
2851 static int
2852 getinfo_helper_liveness(control_connection_t *control_conn,
2853 const char *question, char **answer,
2854 const char **errmsg)
2856 (void)control_conn;
2857 (void)errmsg;
2858 if (strcmp(question, "network-liveness") == 0) {
2859 if (get_cached_network_liveness()) {
2860 *answer = tor_strdup("up");
2861 } else {
2862 *answer = tor_strdup("down");
2866 return 0;
2869 /** Callback function for GETINFO: on a given control connection, try to
2870 * answer the question <b>q</b> and store the newly-allocated answer in
2871 * *<b>a</b>. If an internal error occurs, return -1 and optionally set
2872 * *<b>error_out</b> to point to an error message to be delivered to the
2873 * controller. On success, _or if the key is not recognized_, return 0. Do not
2874 * set <b>a</b> if the key is not recognized.
2876 typedef int (*getinfo_helper_t)(control_connection_t *,
2877 const char *q, char **a,
2878 const char **error_out);
2880 /** A single item for the GETINFO question-to-answer-function table. */
2881 typedef struct getinfo_item_t {
2882 const char *varname; /**< The value (or prefix) of the question. */
2883 getinfo_helper_t fn; /**< The function that knows the answer: NULL if
2884 * this entry is documentation-only. */
2885 const char *desc; /**< Description of the variable. */
2886 int is_prefix; /** Must varname match exactly, or must it be a prefix? */
2887 } getinfo_item_t;
2889 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
2890 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
2891 #define DOC(name, desc) { name, NULL, desc, 0 }
2893 /** Table mapping questions accepted by GETINFO to the functions that know how
2894 * to answer them. */
2895 static const getinfo_item_t getinfo_items[] = {
2896 ITEM("version", misc, "The current version of Tor."),
2897 ITEM("bw-event-cache", misc, "Cached BW events for a short interval."),
2898 ITEM("config-file", misc, "Current location of the \"torrc\" file."),
2899 ITEM("config-defaults-file", misc, "Current location of the defaults file."),
2900 ITEM("config-text", misc,
2901 "Return the string that would be written by a saveconf command."),
2902 ITEM("accounting/bytes", accounting,
2903 "Number of bytes read/written so far in the accounting interval."),
2904 ITEM("accounting/bytes-left", accounting,
2905 "Number of bytes left to write/read so far in the accounting interval."),
2906 ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
2907 ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
2908 ITEM("accounting/interval-start", accounting,
2909 "Time when the accounting period starts."),
2910 ITEM("accounting/interval-end", accounting,
2911 "Time when the accounting period ends."),
2912 ITEM("accounting/interval-wake", accounting,
2913 "Time to wake up in this accounting period."),
2914 ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
2915 ITEM("entry-guards", entry_guards,
2916 "Which nodes are we using as entry guards?"),
2917 ITEM("fingerprint", misc, NULL),
2918 PREFIX("config/", config, "Current configuration values."),
2919 DOC("config/names",
2920 "List of configuration options, types, and documentation."),
2921 DOC("config/defaults",
2922 "List of default values for configuration options. "
2923 "See also config/names"),
2924 PREFIX("downloads/networkstatus/", downloads,
2925 "Download statuses for networkstatus objects"),
2926 DOC("downloads/networkstatus/ns",
2927 "Download status for current-mode networkstatus download"),
2928 DOC("downloads/networkstatus/ns/bootstrap",
2929 "Download status for bootstrap-time networkstatus download"),
2930 DOC("downloads/networkstatus/ns/running",
2931 "Download status for run-time networkstatus download"),
2932 DOC("downloads/networkstatus/microdesc",
2933 "Download status for current-mode microdesc download"),
2934 DOC("downloads/networkstatus/microdesc/bootstrap",
2935 "Download status for bootstrap-time microdesc download"),
2936 DOC("downloads/networkstatus/microdesc/running",
2937 "Download status for run-time microdesc download"),
2938 PREFIX("downloads/cert/", downloads,
2939 "Download statuses for certificates, by id fingerprint and "
2940 "signing key"),
2941 DOC("downloads/cert/fps",
2942 "List of authority fingerprints for which any download statuses "
2943 "exist"),
2944 DOC("downloads/cert/fp/<fp>",
2945 "Download status for <fp> with the default signing key; corresponds "
2946 "to /fp/ URLs on directory server."),
2947 DOC("downloads/cert/fp/<fp>/sks",
2948 "List of signing keys for which specific download statuses are "
2949 "available for this id fingerprint"),
2950 DOC("downloads/cert/fp/<fp>/<sk>",
2951 "Download status for <fp> with signing key <sk>; corresponds "
2952 "to /fp-sk/ URLs on directory server."),
2953 PREFIX("downloads/desc/", downloads,
2954 "Download statuses for router descriptors, by descriptor digest"),
2955 DOC("downloads/desc/descs",
2956 "Return a list of known router descriptor digests"),
2957 DOC("downloads/desc/<desc>",
2958 "Return a download status for a given descriptor digest"),
2959 PREFIX("downloads/bridge/", downloads,
2960 "Download statuses for bridge descriptors, by bridge identity "
2961 "digest"),
2962 DOC("downloads/bridge/bridges",
2963 "Return a list of configured bridge identity digests with download "
2964 "statuses"),
2965 DOC("downloads/bridge/<desc>",
2966 "Return a download status for a given bridge identity digest"),
2967 ITEM("info/names", misc,
2968 "List of GETINFO options, types, and documentation."),
2969 ITEM("events/names", misc,
2970 "Events that the controller can ask for with SETEVENTS."),
2971 ITEM("signal/names", misc, "Signal names recognized by the SIGNAL command"),
2972 ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
2973 PREFIX("desc/id/", dir, "Router descriptors by ID."),
2974 PREFIX("desc/name/", dir, "Router descriptors by nickname."),
2975 ITEM("desc/all-recent", dir,
2976 "All non-expired, non-superseded router descriptors."),
2977 ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
2978 PREFIX("md/id/", dir, "Microdescriptors by ID"),
2979 PREFIX("md/name/", dir, "Microdescriptors by name"),
2980 PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
2981 PREFIX("hs/client/desc/id", dir,
2982 "Hidden Service descriptor in client's cache by onion."),
2983 PREFIX("hs/service/desc/id/", dir,
2984 "Hidden Service descriptor in services's cache by onion."),
2985 PREFIX("net/listeners/", listeners, "Bound addresses by type"),
2986 ITEM("ns/all", networkstatus,
2987 "Brief summary of router status (v2 directory format)"),
2988 PREFIX("ns/id/", networkstatus,
2989 "Brief summary of router status by ID (v2 directory format)."),
2990 PREFIX("ns/name/", networkstatus,
2991 "Brief summary of router status by nickname (v2 directory format)."),
2992 PREFIX("ns/purpose/", networkstatus,
2993 "Brief summary of router status by purpose (v2 directory format)."),
2994 PREFIX("consensus/", networkstatus,
2995 "Information about and from the ns consensus."),
2996 ITEM("network-status", dir,
2997 "Brief summary of router status (v1 directory format)"),
2998 ITEM("network-liveness", liveness,
2999 "Current opinion on whether the network is live"),
3000 ITEM("circuit-status", events, "List of current circuits originating here."),
3001 ITEM("stream-status", events,"List of current streams."),
3002 ITEM("orconn-status", events, "A list of current OR connections."),
3003 ITEM("dormant", misc,
3004 "Is Tor dormant (not building circuits because it's idle)?"),
3005 PREFIX("address-mappings/", events, NULL),
3006 DOC("address-mappings/all", "Current address mappings."),
3007 DOC("address-mappings/cache", "Current cached DNS replies."),
3008 DOC("address-mappings/config",
3009 "Current address mappings from configuration."),
3010 DOC("address-mappings/control", "Current address mappings from controller."),
3011 PREFIX("status/", events, NULL),
3012 DOC("status/circuit-established",
3013 "Whether we think client functionality is working."),
3014 DOC("status/enough-dir-info",
3015 "Whether we have enough up-to-date directory information to build "
3016 "circuits."),
3017 DOC("status/bootstrap-phase",
3018 "The last bootstrap phase status event that Tor sent."),
3019 DOC("status/clients-seen",
3020 "Breakdown of client countries seen by a bridge."),
3021 DOC("status/fresh-relay-descs",
3022 "A fresh relay/ei descriptor pair for Tor's current state. Not stored."),
3023 DOC("status/version/recommended", "List of currently recommended versions."),
3024 DOC("status/version/current", "Status of the current version."),
3025 DOC("status/version/num-versioning", "Number of versioning authorities."),
3026 DOC("status/version/num-concurring",
3027 "Number of versioning authorities agreeing on the status of the "
3028 "current version"),
3029 ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
3030 ITEM("traffic/read", misc,"Bytes read since the process was started."),
3031 ITEM("traffic/written", misc,
3032 "Bytes written since the process was started."),
3033 ITEM("process/pid", misc, "Process id belonging to the main tor process."),
3034 ITEM("process/uid", misc, "User id running the tor process."),
3035 ITEM("process/user", misc,
3036 "Username under which the tor process is running."),
3037 ITEM("process/descriptor-limit", misc, "File descriptor limit."),
3038 ITEM("limits/max-mem-in-queues", misc, "Actual limit on memory in queues"),
3039 PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
3040 PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
3041 PREFIX("dir/status/", dir,
3042 "v2 networkstatus docs as retrieved from a DirPort."),
3043 ITEM("dir/status-vote/current/consensus", dir,
3044 "v3 Networkstatus consensus as retrieved from a DirPort."),
3045 ITEM("exit-policy/default", policies,
3046 "The default value appended to the configured exit policy."),
3047 ITEM("exit-policy/reject-private/default", policies,
3048 "The default rules appended to the configured exit policy by"
3049 " ExitPolicyRejectPrivate."),
3050 ITEM("exit-policy/reject-private/relay", policies,
3051 "The relay-specific rules appended to the configured exit policy by"
3052 " ExitPolicyRejectPrivate and/or ExitPolicyRejectLocalInterfaces."),
3053 ITEM("exit-policy/full", policies, "The entire exit policy of onion router"),
3054 ITEM("exit-policy/ipv4", policies, "IPv4 parts of exit policy"),
3055 ITEM("exit-policy/ipv6", policies, "IPv6 parts of exit policy"),
3056 PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
3057 ITEM("onions/current", onions,
3058 "Onion services owned by the current control connection."),
3059 ITEM("onions/detached", onions,
3060 "Onion services detached from the control connection."),
3061 { NULL, NULL, NULL, 0 }
3064 /** Allocate and return a list of recognized GETINFO options. */
3065 static char *
3066 list_getinfo_options(void)
3068 int i;
3069 smartlist_t *lines = smartlist_new();
3070 char *ans;
3071 for (i = 0; getinfo_items[i].varname; ++i) {
3072 if (!getinfo_items[i].desc)
3073 continue;
3075 smartlist_add_asprintf(lines, "%s%s -- %s\n",
3076 getinfo_items[i].varname,
3077 getinfo_items[i].is_prefix ? "*" : "",
3078 getinfo_items[i].desc);
3080 smartlist_sort_strings(lines);
3082 ans = smartlist_join_strings(lines, "", 0, NULL);
3083 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
3084 smartlist_free(lines);
3086 return ans;
3089 /** Lookup the 'getinfo' entry <b>question</b>, and return
3090 * the answer in <b>*answer</b> (or NULL if key not recognized).
3091 * Return 0 if success or unrecognized, or -1 if recognized but
3092 * internal error. */
3093 static int
3094 handle_getinfo_helper(control_connection_t *control_conn,
3095 const char *question, char **answer,
3096 const char **err_out)
3098 int i;
3099 *answer = NULL; /* unrecognized key by default */
3101 for (i = 0; getinfo_items[i].varname; ++i) {
3102 int match;
3103 if (getinfo_items[i].is_prefix)
3104 match = !strcmpstart(question, getinfo_items[i].varname);
3105 else
3106 match = !strcmp(question, getinfo_items[i].varname);
3107 if (match) {
3108 tor_assert(getinfo_items[i].fn);
3109 return getinfo_items[i].fn(control_conn, question, answer, err_out);
3113 return 0; /* unrecognized */
3116 /** Called when we receive a GETINFO command. Try to fetch all requested
3117 * information, and reply with information or error message. */
3118 static int
3119 handle_control_getinfo(control_connection_t *conn, uint32_t len,
3120 const char *body)
3122 smartlist_t *questions = smartlist_new();
3123 smartlist_t *answers = smartlist_new();
3124 smartlist_t *unrecognized = smartlist_new();
3125 char *msg = NULL, *ans = NULL;
3126 int i;
3127 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
3129 smartlist_split_string(questions, body, " ",
3130 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3131 SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
3132 const char *errmsg = NULL;
3133 if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
3134 if (!errmsg)
3135 errmsg = "Internal error";
3136 connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
3137 goto done;
3139 if (!ans) {
3140 smartlist_add(unrecognized, (char*)q);
3141 } else {
3142 smartlist_add(answers, tor_strdup(q));
3143 smartlist_add(answers, ans);
3145 } SMARTLIST_FOREACH_END(q);
3146 if (smartlist_len(unrecognized)) {
3147 for (i=0; i < smartlist_len(unrecognized)-1; ++i)
3148 connection_printf_to_buf(conn,
3149 "552-Unrecognized key \"%s\"\r\n",
3150 (char*)smartlist_get(unrecognized, i));
3151 connection_printf_to_buf(conn,
3152 "552 Unrecognized key \"%s\"\r\n",
3153 (char*)smartlist_get(unrecognized, i));
3154 goto done;
3157 for (i = 0; i < smartlist_len(answers); i += 2) {
3158 char *k = smartlist_get(answers, i);
3159 char *v = smartlist_get(answers, i+1);
3160 if (!strchr(v, '\n') && !strchr(v, '\r')) {
3161 connection_printf_to_buf(conn, "250-%s=", k);
3162 connection_write_str_to_buf(v, conn);
3163 connection_write_str_to_buf("\r\n", conn);
3164 } else {
3165 char *esc = NULL;
3166 size_t esc_len;
3167 esc_len = write_escaped_data(v, strlen(v), &esc);
3168 connection_printf_to_buf(conn, "250+%s=\r\n", k);
3169 connection_write_to_buf(esc, esc_len, TO_CONN(conn));
3170 tor_free(esc);
3173 connection_write_str_to_buf("250 OK\r\n", conn);
3175 done:
3176 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
3177 smartlist_free(answers);
3178 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
3179 smartlist_free(questions);
3180 smartlist_free(unrecognized);
3181 tor_free(msg);
3183 return 0;
3186 /** Given a string, convert it to a circuit purpose. */
3187 static uint8_t
3188 circuit_purpose_from_string(const char *string)
3190 if (!strcasecmpstart(string, "purpose="))
3191 string += strlen("purpose=");
3193 if (!strcasecmp(string, "general"))
3194 return CIRCUIT_PURPOSE_C_GENERAL;
3195 else if (!strcasecmp(string, "controller"))
3196 return CIRCUIT_PURPOSE_CONTROLLER;
3197 else
3198 return CIRCUIT_PURPOSE_UNKNOWN;
3201 /** Return a newly allocated smartlist containing the arguments to the command
3202 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
3203 * or if <b>max_args</b> is nonnegative and there are more than
3204 * <b>max_args</b> arguments, send a 512 error to the controller, using
3205 * <b>command</b> as the command name in the error message. */
3206 static smartlist_t *
3207 getargs_helper(const char *command, control_connection_t *conn,
3208 const char *body, int min_args, int max_args)
3210 smartlist_t *args = smartlist_new();
3211 smartlist_split_string(args, body, " ",
3212 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3213 if (smartlist_len(args) < min_args) {
3214 connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
3215 goto err;
3216 } else if (max_args >= 0 && smartlist_len(args) > max_args) {
3217 connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
3218 goto err;
3220 return args;
3221 err:
3222 SMARTLIST_FOREACH(args, char *, s, tor_free(s));
3223 smartlist_free(args);
3224 return NULL;
3227 /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
3228 * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
3229 * such element exists. */
3230 static const char *
3231 find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
3233 int i;
3234 for (i = start_at; i < smartlist_len(sl); ++i) {
3235 const char *elt = smartlist_get(sl, i);
3236 if (!strcasecmpstart(elt, prefix))
3237 return elt;
3239 return NULL;
3242 /** Helper. Return true iff s is an argument that we should treat as a
3243 * key-value pair. */
3244 static int
3245 is_keyval_pair(const char *s)
3247 /* An argument is a key-value pair if it has an =, and it isn't of the form
3248 * $fingeprint=name */
3249 return strchr(s, '=') && s[0] != '$';
3252 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
3253 * circuit, and report success or failure. */
3254 static int
3255 handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
3256 const char *body)
3258 smartlist_t *router_nicknames=NULL, *nodes=NULL;
3259 origin_circuit_t *circ = NULL;
3260 int zero_circ;
3261 uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
3262 smartlist_t *args;
3263 (void) len;
3265 router_nicknames = smartlist_new();
3267 args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
3268 if (!args)
3269 goto done;
3271 zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
3273 if (zero_circ) {
3274 const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
3276 if (purp) {
3277 intended_purpose = circuit_purpose_from_string(purp);
3278 if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
3279 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
3280 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3281 smartlist_free(args);
3282 goto done;
3286 if ((smartlist_len(args) == 1) ||
3287 (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
3288 // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
3289 circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
3290 if (!circ) {
3291 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
3292 } else {
3293 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
3294 (unsigned long)circ->global_identifier);
3296 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3297 smartlist_free(args);
3298 goto done;
3300 // "EXTENDCIRCUIT 0 router1,router2" ||
3301 // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
3304 if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
3305 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
3306 (char*)smartlist_get(args, 0));
3307 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3308 smartlist_free(args);
3309 goto done;
3312 if (smartlist_len(args) < 2) {
3313 connection_printf_to_buf(conn,
3314 "512 syntax error: not enough arguments.\r\n");
3315 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3316 smartlist_free(args);
3317 goto done;
3320 smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
3322 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3323 smartlist_free(args);
3325 nodes = smartlist_new();
3326 SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
3327 const node_t *node = node_get_by_nickname(n, 1);
3328 if (!node) {
3329 connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
3330 goto done;
3332 if (!node_has_descriptor(node)) {
3333 connection_printf_to_buf(conn, "552 No descriptor for \"%s\"\r\n", n);
3334 goto done;
3336 smartlist_add(nodes, (void*)node);
3337 } SMARTLIST_FOREACH_END(n);
3338 if (!smartlist_len(nodes)) {
3339 connection_write_str_to_buf("512 No router names provided\r\n", conn);
3340 goto done;
3343 if (zero_circ) {
3344 /* start a new circuit */
3345 circ = origin_circuit_init(intended_purpose, 0);
3348 /* now circ refers to something that is ready to be extended */
3349 int first_node = zero_circ;
3350 SMARTLIST_FOREACH(nodes, const node_t *, node,
3352 extend_info_t *info = extend_info_from_node(node, first_node);
3353 if (first_node && !info) {
3354 log_warn(LD_CONTROL,
3355 "controller tried to connect to a node that doesn't have any "
3356 "addresses that are allowed by the firewall configuration; "
3357 "circuit marked for closing.");
3358 circuit_mark_for_close(TO_CIRCUIT(circ), -END_CIRC_REASON_CONNECTFAILED);
3359 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
3360 goto done;
3361 } else {
3362 /* True, since node_has_descriptor(node) == true and we are extending
3363 * to the node's primary address */
3364 tor_assert(info);
3366 circuit_append_new_exit(circ, info);
3367 extend_info_free(info);
3368 first_node = 0;
3371 /* now that we've populated the cpath, start extending */
3372 if (zero_circ) {
3373 int err_reason = 0;
3374 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
3375 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
3376 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
3377 goto done;
3379 } else {
3380 if (circ->base_.state == CIRCUIT_STATE_OPEN) {
3381 int err_reason = 0;
3382 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
3383 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
3384 log_info(LD_CONTROL,
3385 "send_next_onion_skin failed; circuit marked for closing.");
3386 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
3387 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
3388 goto done;
3393 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
3394 (unsigned long)circ->global_identifier);
3395 if (zero_circ) /* send a 'launched' event, for completeness */
3396 control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
3397 done:
3398 SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
3399 smartlist_free(router_nicknames);
3400 smartlist_free(nodes);
3401 return 0;
3404 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
3405 * circuit and it's a valid purpose, change it. */
3406 static int
3407 handle_control_setcircuitpurpose(control_connection_t *conn,
3408 uint32_t len, const char *body)
3410 origin_circuit_t *circ = NULL;
3411 uint8_t new_purpose;
3412 smartlist_t *args;
3413 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
3415 args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
3416 if (!args)
3417 goto done;
3419 if (!(circ = get_circ(smartlist_get(args,0)))) {
3420 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
3421 (char*)smartlist_get(args, 0));
3422 goto done;
3426 const char *purp = find_element_starting_with(args,1,"PURPOSE=");
3427 if (!purp) {
3428 connection_write_str_to_buf("552 No purpose given\r\n", conn);
3429 goto done;
3431 new_purpose = circuit_purpose_from_string(purp);
3432 if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
3433 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
3434 goto done;
3438 circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
3439 connection_write_str_to_buf("250 OK\r\n", conn);
3441 done:
3442 if (args) {
3443 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3444 smartlist_free(args);
3446 return 0;
3449 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
3450 * stream, and report success or failure. */
3451 static int
3452 handle_control_attachstream(control_connection_t *conn, uint32_t len,
3453 const char *body)
3455 entry_connection_t *ap_conn = NULL;
3456 origin_circuit_t *circ = NULL;
3457 int zero_circ;
3458 smartlist_t *args;
3459 crypt_path_t *cpath=NULL;
3460 int hop=0, hop_line_ok=1;
3461 (void) len;
3463 args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
3464 if (!args)
3465 return 0;
3467 zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
3469 if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
3470 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
3471 (char*)smartlist_get(args, 0));
3472 } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
3473 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
3474 (char*)smartlist_get(args, 1));
3475 } else if (circ) {
3476 const char *hopstring = find_element_starting_with(args,2,"HOP=");
3477 if (hopstring) {
3478 hopstring += strlen("HOP=");
3479 hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
3480 &hop_line_ok, NULL);
3481 if (!hop_line_ok) { /* broken hop line */
3482 connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
3486 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3487 smartlist_free(args);
3488 if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
3489 return 0;
3491 if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
3492 ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
3493 ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
3494 connection_write_str_to_buf(
3495 "555 Connection is not managed by controller.\r\n",
3496 conn);
3497 return 0;
3500 /* Do we need to detach it first? */
3501 if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
3502 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
3503 circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
3504 connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
3505 /* Un-mark it as ending, since we're going to reuse it. */
3506 edge_conn->edge_has_sent_end = 0;
3507 edge_conn->end_reason = 0;
3508 if (tmpcirc)
3509 circuit_detach_stream(tmpcirc, edge_conn);
3510 CONNECTION_AP_EXPECT_NONPENDING(ap_conn);
3511 TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
3514 if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
3515 connection_write_str_to_buf(
3516 "551 Can't attach stream to non-open origin circuit\r\n",
3517 conn);
3518 return 0;
3520 /* Is this a single hop circuit? */
3521 if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
3522 const node_t *node = NULL;
3523 char *exit_digest = NULL;
3524 if (circ->build_state &&
3525 circ->build_state->chosen_exit &&
3526 !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
3527 exit_digest = circ->build_state->chosen_exit->identity_digest;
3528 node = node_get_by_id(exit_digest);
3530 /* Do both the client and relay allow one-hop exit circuits? */
3531 if (!node ||
3532 !node_allows_single_hop_exits(node) ||
3533 !get_options()->AllowSingleHopCircuits) {
3534 connection_write_str_to_buf(
3535 "551 Can't attach stream to this one-hop circuit.\r\n", conn);
3536 return 0;
3538 tor_assert(exit_digest);
3539 ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
3542 if (circ && hop>0) {
3543 /* find this hop in the circuit, and set cpath */
3544 cpath = circuit_get_cpath_hop(circ, hop);
3545 if (!cpath) {
3546 connection_printf_to_buf(conn,
3547 "551 Circuit doesn't have %d hops.\r\n", hop);
3548 return 0;
3551 if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
3552 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
3553 return 0;
3555 send_control_done(conn);
3556 return 0;
3559 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
3560 * descriptor, and report success or failure. */
3561 static int
3562 handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
3563 const char *body)
3565 char *desc;
3566 const char *msg=NULL;
3567 uint8_t purpose = ROUTER_PURPOSE_GENERAL;
3568 int cache = 0; /* eventually, we may switch this to 1 */
3570 const char *cp = memchr(body, '\n', len);
3571 smartlist_t *args = smartlist_new();
3572 tor_assert(cp);
3573 ++cp;
3575 char *cmdline = tor_memdup_nulterm(body, cp-body);
3577 smartlist_split_string(args, cmdline, " ",
3578 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3579 SMARTLIST_FOREACH_BEGIN(args, char *, option) {
3580 if (!strcasecmpstart(option, "purpose=")) {
3581 option += strlen("purpose=");
3582 purpose = router_purpose_from_string(option);
3583 if (purpose == ROUTER_PURPOSE_UNKNOWN) {
3584 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
3585 option);
3586 goto done;
3588 } else if (!strcasecmpstart(option, "cache=")) {
3589 option += strlen("cache=");
3590 if (!strcasecmp(option, "no"))
3591 cache = 0;
3592 else if (!strcasecmp(option, "yes"))
3593 cache = 1;
3594 else {
3595 connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
3596 option);
3597 goto done;
3599 } else { /* unrecognized argument? */
3600 connection_printf_to_buf(conn,
3601 "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
3602 goto done;
3604 } SMARTLIST_FOREACH_END(option);
3606 read_escaped_data(cp, len-(cp-body), &desc);
3608 switch (router_load_single_router(desc, purpose, cache, &msg)) {
3609 case -1:
3610 if (!msg) msg = "Could not parse descriptor";
3611 connection_printf_to_buf(conn, "554 %s\r\n", msg);
3612 break;
3613 case 0:
3614 if (!msg) msg = "Descriptor not added";
3615 connection_printf_to_buf(conn, "251 %s\r\n",msg);
3616 break;
3617 case 1:
3618 send_control_done(conn);
3619 break;
3622 tor_free(desc);
3623 done:
3624 SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
3625 smartlist_free(args);
3626 tor_free(cmdline);
3627 return 0;
3630 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
3631 * address of the named AP stream, and report success or failure. */
3632 static int
3633 handle_control_redirectstream(control_connection_t *conn, uint32_t len,
3634 const char *body)
3636 entry_connection_t *ap_conn = NULL;
3637 char *new_addr = NULL;
3638 uint16_t new_port = 0;
3639 smartlist_t *args;
3640 (void) len;
3642 args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
3643 if (!args)
3644 return 0;
3646 if (!(ap_conn = get_stream(smartlist_get(args, 0)))
3647 || !ap_conn->socks_request) {
3648 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
3649 (char*)smartlist_get(args, 0));
3650 } else {
3651 int ok = 1;
3652 if (smartlist_len(args) > 2) { /* they included a port too */
3653 new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
3654 10, 1, 65535, &ok, NULL);
3656 if (!ok) {
3657 connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
3658 (char*)smartlist_get(args, 2));
3659 } else {
3660 new_addr = tor_strdup(smartlist_get(args, 1));
3664 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3665 smartlist_free(args);
3666 if (!new_addr)
3667 return 0;
3669 strlcpy(ap_conn->socks_request->address, new_addr,
3670 sizeof(ap_conn->socks_request->address));
3671 if (new_port)
3672 ap_conn->socks_request->port = new_port;
3673 tor_free(new_addr);
3674 send_control_done(conn);
3675 return 0;
3678 /** Called when we get a CLOSESTREAM command; try to close the named stream
3679 * and report success or failure. */
3680 static int
3681 handle_control_closestream(control_connection_t *conn, uint32_t len,
3682 const char *body)
3684 entry_connection_t *ap_conn=NULL;
3685 uint8_t reason=0;
3686 smartlist_t *args;
3687 int ok;
3688 (void) len;
3690 args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
3691 if (!args)
3692 return 0;
3694 else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
3695 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
3696 (char*)smartlist_get(args, 0));
3697 else {
3698 reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
3699 &ok, NULL);
3700 if (!ok) {
3701 connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
3702 (char*)smartlist_get(args, 1));
3703 ap_conn = NULL;
3706 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3707 smartlist_free(args);
3708 if (!ap_conn)
3709 return 0;
3711 connection_mark_unattached_ap(ap_conn, reason);
3712 send_control_done(conn);
3713 return 0;
3716 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
3717 * and report success or failure. */
3718 static int
3719 handle_control_closecircuit(control_connection_t *conn, uint32_t len,
3720 const char *body)
3722 origin_circuit_t *circ = NULL;
3723 int safe = 0;
3724 smartlist_t *args;
3725 (void) len;
3727 args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
3728 if (!args)
3729 return 0;
3731 if (!(circ=get_circ(smartlist_get(args, 0))))
3732 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
3733 (char*)smartlist_get(args, 0));
3734 else {
3735 int i;
3736 for (i=1; i < smartlist_len(args); ++i) {
3737 if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
3738 safe = 1;
3739 else
3740 log_info(LD_CONTROL, "Skipping unknown option %s",
3741 (char*)smartlist_get(args,i));
3744 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3745 smartlist_free(args);
3746 if (!circ)
3747 return 0;
3749 if (!safe || !circ->p_streams) {
3750 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
3753 send_control_done(conn);
3754 return 0;
3757 /** Called when we get a RESOLVE command: start trying to resolve
3758 * the listed addresses. */
3759 static int
3760 handle_control_resolve(control_connection_t *conn, uint32_t len,
3761 const char *body)
3763 smartlist_t *args, *failed;
3764 int is_reverse = 0;
3765 (void) len; /* body is nul-terminated; it's safe to ignore the length */
3767 if (!(conn->event_mask & (((event_mask_t)1)<<EVENT_ADDRMAP))) {
3768 log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
3769 "isn't listening for ADDRMAP events. It probably won't see "
3770 "the answer.");
3772 args = smartlist_new();
3773 smartlist_split_string(args, body, " ",
3774 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3776 const char *modearg = find_element_starting_with(args, 0, "mode=");
3777 if (modearg && !strcasecmp(modearg, "mode=reverse"))
3778 is_reverse = 1;
3780 failed = smartlist_new();
3781 SMARTLIST_FOREACH(args, const char *, arg, {
3782 if (!is_keyval_pair(arg)) {
3783 if (dnsserv_launch_request(arg, is_reverse, conn)<0)
3784 smartlist_add(failed, (char*)arg);
3788 send_control_done(conn);
3789 SMARTLIST_FOREACH(failed, const char *, arg, {
3790 control_event_address_mapped(arg, arg, time(NULL),
3791 "internal", 0);
3794 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3795 smartlist_free(args);
3796 smartlist_free(failed);
3797 return 0;
3800 /** Called when we get a PROTOCOLINFO command: send back a reply. */
3801 static int
3802 handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
3803 const char *body)
3805 const char *bad_arg = NULL;
3806 smartlist_t *args;
3807 (void)len;
3809 conn->have_sent_protocolinfo = 1;
3810 args = smartlist_new();
3811 smartlist_split_string(args, body, " ",
3812 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3813 SMARTLIST_FOREACH(args, const char *, arg, {
3814 int ok;
3815 tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
3816 if (!ok) {
3817 bad_arg = arg;
3818 break;
3821 if (bad_arg) {
3822 connection_printf_to_buf(conn, "513 No such version %s\r\n",
3823 escaped(bad_arg));
3824 /* Don't tolerate bad arguments when not authenticated. */
3825 if (!STATE_IS_OPEN(TO_CONN(conn)->state))
3826 connection_mark_for_close(TO_CONN(conn));
3827 goto done;
3828 } else {
3829 const or_options_t *options = get_options();
3830 int cookies = options->CookieAuthentication;
3831 char *cfile = get_controller_cookie_file_name();
3832 char *abs_cfile;
3833 char *esc_cfile;
3834 char *methods;
3835 abs_cfile = make_path_absolute(cfile);
3836 esc_cfile = esc_for_log(abs_cfile);
3838 int passwd = (options->HashedControlPassword != NULL ||
3839 options->HashedControlSessionPassword != NULL);
3840 smartlist_t *mlist = smartlist_new();
3841 if (cookies) {
3842 smartlist_add(mlist, (char*)"COOKIE");
3843 smartlist_add(mlist, (char*)"SAFECOOKIE");
3845 if (passwd)
3846 smartlist_add(mlist, (char*)"HASHEDPASSWORD");
3847 if (!cookies && !passwd)
3848 smartlist_add(mlist, (char*)"NULL");
3849 methods = smartlist_join_strings(mlist, ",", 0, NULL);
3850 smartlist_free(mlist);
3853 connection_printf_to_buf(conn,
3854 "250-PROTOCOLINFO 1\r\n"
3855 "250-AUTH METHODS=%s%s%s\r\n"
3856 "250-VERSION Tor=%s\r\n"
3857 "250 OK\r\n",
3858 methods,
3859 cookies?" COOKIEFILE=":"",
3860 cookies?esc_cfile:"",
3861 escaped(VERSION));
3862 tor_free(methods);
3863 tor_free(cfile);
3864 tor_free(abs_cfile);
3865 tor_free(esc_cfile);
3867 done:
3868 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3869 smartlist_free(args);
3870 return 0;
3873 /** Called when we get an AUTHCHALLENGE command. */
3874 static int
3875 handle_control_authchallenge(control_connection_t *conn, uint32_t len,
3876 const char *body)
3878 const char *cp = body;
3879 char *client_nonce;
3880 size_t client_nonce_len;
3881 char server_hash[DIGEST256_LEN];
3882 char server_hash_encoded[HEX_DIGEST256_LEN+1];
3883 char server_nonce[SAFECOOKIE_SERVER_NONCE_LEN];
3884 char server_nonce_encoded[(2*SAFECOOKIE_SERVER_NONCE_LEN) + 1];
3886 cp += strspn(cp, " \t\n\r");
3887 if (!strcasecmpstart(cp, "SAFECOOKIE")) {
3888 cp += strlen("SAFECOOKIE");
3889 } else {
3890 connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
3891 "authentication\r\n", conn);
3892 connection_mark_for_close(TO_CONN(conn));
3893 return -1;
3896 if (!authentication_cookie_is_set) {
3897 connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
3898 conn);
3899 connection_mark_for_close(TO_CONN(conn));
3900 return -1;
3903 cp += strspn(cp, " \t\n\r");
3904 if (*cp == '"') {
3905 const char *newcp =
3906 decode_escaped_string(cp, len - (cp - body),
3907 &client_nonce, &client_nonce_len);
3908 if (newcp == NULL) {
3909 connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
3910 conn);
3911 connection_mark_for_close(TO_CONN(conn));
3912 return -1;
3914 cp = newcp;
3915 } else {
3916 size_t client_nonce_encoded_len = strspn(cp, "0123456789ABCDEFabcdef");
3918 client_nonce_len = client_nonce_encoded_len / 2;
3919 client_nonce = tor_malloc_zero(client_nonce_len);
3921 if (base16_decode(client_nonce, client_nonce_len,
3922 cp, client_nonce_encoded_len)
3923 != (int) client_nonce_len) {
3924 connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
3925 conn);
3926 connection_mark_for_close(TO_CONN(conn));
3927 tor_free(client_nonce);
3928 return -1;
3931 cp += client_nonce_encoded_len;
3934 cp += strspn(cp, " \t\n\r");
3935 if (*cp != '\0' ||
3936 cp != body + len) {
3937 connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
3938 conn);
3939 connection_mark_for_close(TO_CONN(conn));
3940 tor_free(client_nonce);
3941 return -1;
3943 crypto_rand(server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
3945 /* Now compute and send the server-to-controller response, and the
3946 * server's nonce. */
3947 tor_assert(authentication_cookie != NULL);
3950 size_t tmp_len = (AUTHENTICATION_COOKIE_LEN +
3951 client_nonce_len +
3952 SAFECOOKIE_SERVER_NONCE_LEN);
3953 char *tmp = tor_malloc_zero(tmp_len);
3954 char *client_hash = tor_malloc_zero(DIGEST256_LEN);
3955 memcpy(tmp, authentication_cookie, AUTHENTICATION_COOKIE_LEN);
3956 memcpy(tmp + AUTHENTICATION_COOKIE_LEN, client_nonce, client_nonce_len);
3957 memcpy(tmp + AUTHENTICATION_COOKIE_LEN + client_nonce_len,
3958 server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
3960 crypto_hmac_sha256(server_hash,
3961 SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT,
3962 strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT),
3963 tmp,
3964 tmp_len);
3966 crypto_hmac_sha256(client_hash,
3967 SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT,
3968 strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT),
3969 tmp,
3970 tmp_len);
3972 conn->safecookie_client_hash = client_hash;
3974 tor_free(tmp);
3977 base16_encode(server_hash_encoded, sizeof(server_hash_encoded),
3978 server_hash, sizeof(server_hash));
3979 base16_encode(server_nonce_encoded, sizeof(server_nonce_encoded),
3980 server_nonce, sizeof(server_nonce));
3982 connection_printf_to_buf(conn,
3983 "250 AUTHCHALLENGE SERVERHASH=%s "
3984 "SERVERNONCE=%s\r\n",
3985 server_hash_encoded,
3986 server_nonce_encoded);
3988 tor_free(client_nonce);
3989 return 0;
3992 /** Called when we get a USEFEATURE command: parse the feature list, and
3993 * set up the control_connection's options properly. */
3994 static int
3995 handle_control_usefeature(control_connection_t *conn,
3996 uint32_t len,
3997 const char *body)
3999 smartlist_t *args;
4000 int bad = 0;
4001 (void) len; /* body is nul-terminated; it's safe to ignore the length */
4002 args = smartlist_new();
4003 smartlist_split_string(args, body, " ",
4004 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4005 SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
4006 if (!strcasecmp(arg, "VERBOSE_NAMES"))
4008 else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
4010 else {
4011 connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
4012 arg);
4013 bad = 1;
4014 break;
4016 } SMARTLIST_FOREACH_END(arg);
4018 if (!bad) {
4019 send_control_done(conn);
4022 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
4023 smartlist_free(args);
4024 return 0;
4027 /** Implementation for the DROPGUARDS command. */
4028 static int
4029 handle_control_dropguards(control_connection_t *conn,
4030 uint32_t len,
4031 const char *body)
4033 smartlist_t *args;
4034 (void) len; /* body is nul-terminated; it's safe to ignore the length */
4035 args = smartlist_new();
4036 smartlist_split_string(args, body, " ",
4037 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4039 if (smartlist_len(args)) {
4040 connection_printf_to_buf(conn, "512 Too many arguments to DROPGUARDS\r\n");
4041 } else {
4042 remove_all_entry_guards();
4043 send_control_done(conn);
4046 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
4047 smartlist_free(args);
4048 return 0;
4051 /** Implementation for the HSFETCH command. */
4052 static int
4053 handle_control_hsfetch(control_connection_t *conn, uint32_t len,
4054 const char *body)
4056 int i;
4057 char digest[DIGEST_LEN], *hsaddress = NULL, *arg1 = NULL, *desc_id = NULL;
4058 smartlist_t *args = NULL, *hsdirs = NULL;
4059 (void) len; /* body is nul-terminated; it's safe to ignore the length */
4060 static const char *hsfetch_command = "HSFETCH";
4061 static const char *v2_str = "v2-";
4062 const size_t v2_str_len = strlen(v2_str);
4063 rend_data_t *rend_query = NULL;
4065 /* Make sure we have at least one argument, the HSAddress. */
4066 args = getargs_helper(hsfetch_command, conn, body, 1, -1);
4067 if (!args) {
4068 goto exit;
4071 /* Extract the first argument (either HSAddress or DescID). */
4072 arg1 = smartlist_get(args, 0);
4073 /* Test if it's an HS address without the .onion part. */
4074 if (rend_valid_service_id(arg1)) {
4075 hsaddress = arg1;
4076 } else if (strcmpstart(arg1, v2_str) == 0 &&
4077 rend_valid_descriptor_id(arg1 + v2_str_len) &&
4078 base32_decode(digest, sizeof(digest), arg1 + v2_str_len,
4079 REND_DESC_ID_V2_LEN_BASE32) == 0) {
4080 /* We have a well formed version 2 descriptor ID. Keep the decoded value
4081 * of the id. */
4082 desc_id = digest;
4083 } else {
4084 connection_printf_to_buf(conn, "513 Unrecognized \"%s\"\r\n",
4085 arg1);
4086 goto done;
4089 static const char *opt_server = "SERVER=";
4091 /* Skip first argument because it's the HSAddress or DescID. */
4092 for (i = 1; i < smartlist_len(args); ++i) {
4093 const char *arg = smartlist_get(args, i);
4094 const node_t *node;
4096 if (!strcasecmpstart(arg, opt_server)) {
4097 const char *server;
4099 server = arg + strlen(opt_server);
4100 node = node_get_by_hex_id(server);
4101 if (!node) {
4102 connection_printf_to_buf(conn, "552 Server \"%s\" not found\r\n",
4103 server);
4104 goto done;
4106 if (!hsdirs) {
4107 /* Stores routerstatus_t object for each specified server. */
4108 hsdirs = smartlist_new();
4110 /* Valid server, add it to our local list. */
4111 smartlist_add(hsdirs, node->rs);
4112 } else {
4113 connection_printf_to_buf(conn, "513 Unexpected argument \"%s\"\r\n",
4114 arg);
4115 goto done;
4119 rend_query = rend_data_client_create(hsaddress, desc_id, NULL,
4120 REND_NO_AUTH);
4121 if (rend_query == NULL) {
4122 connection_printf_to_buf(conn, "551 Error creating the HS query\r\n");
4123 goto done;
4126 /* Using a descriptor ID, we force the user to provide at least one
4127 * hsdir server using the SERVER= option. */
4128 if (desc_id && (!hsdirs || !smartlist_len(hsdirs))) {
4129 connection_printf_to_buf(conn, "512 %s option is required\r\n",
4130 opt_server);
4131 goto done;
4134 /* We are about to trigger HSDir fetch so send the OK now because after
4135 * that 650 event(s) are possible so better to have the 250 OK before them
4136 * to avoid out of order replies. */
4137 send_control_done(conn);
4139 /* Trigger the fetch using the built rend query and possibly a list of HS
4140 * directory to use. This function ignores the client cache thus this will
4141 * always send a fetch command. */
4142 rend_client_fetch_v2_desc(rend_query, hsdirs);
4144 done:
4145 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
4146 smartlist_free(args);
4147 /* Contains data pointer that we don't own thus no cleanup. */
4148 smartlist_free(hsdirs);
4149 rend_data_free(rend_query);
4150 exit:
4151 return 0;
4154 /** Implementation for the HSPOST command. */
4155 static int
4156 handle_control_hspost(control_connection_t *conn,
4157 uint32_t len,
4158 const char *body)
4160 static const char *opt_server = "SERVER=";
4161 smartlist_t *args = smartlist_new();
4162 smartlist_t *hs_dirs = NULL;
4163 const char *encoded_desc = body;
4164 size_t encoded_desc_len = len;
4166 char *cp = memchr(body, '\n', len);
4167 char *argline = tor_strndup(body, cp-body);
4169 /* If any SERVER= options were specified, try parse the options line */
4170 if (!strcasecmpstart(argline, opt_server)) {
4171 /* encoded_desc begins after a newline character */
4172 cp = cp + 1;
4173 encoded_desc = cp;
4174 encoded_desc_len = len-(cp-body);
4176 smartlist_split_string(args, argline, " ",
4177 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4178 SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
4179 if (!strcasecmpstart(arg, opt_server)) {
4180 const char *server = arg + strlen(opt_server);
4181 const node_t *node = node_get_by_hex_id(server);
4183 if (!node || !node->rs) {
4184 connection_printf_to_buf(conn, "552 Server \"%s\" not found\r\n",
4185 server);
4186 goto done;
4188 if (!node->rs->is_hs_dir) {
4189 connection_printf_to_buf(conn, "552 Server \"%s\" is not a HSDir"
4190 "\r\n", server);
4191 goto done;
4193 /* Valid server, add it to our local list. */
4194 if (!hs_dirs)
4195 hs_dirs = smartlist_new();
4196 smartlist_add(hs_dirs, node->rs);
4197 } else {
4198 connection_printf_to_buf(conn, "512 Unexpected argument \"%s\"\r\n",
4199 arg);
4200 goto done;
4202 } SMARTLIST_FOREACH_END(arg);
4205 /* Read the dot encoded descriptor, and parse it. */
4206 rend_encoded_v2_service_descriptor_t *desc =
4207 tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
4208 read_escaped_data(encoded_desc, encoded_desc_len, &desc->desc_str);
4210 rend_service_descriptor_t *parsed = NULL;
4211 char *intro_content = NULL;
4212 size_t intro_size;
4213 size_t encoded_size;
4214 const char *next_desc;
4215 if (!rend_parse_v2_service_descriptor(&parsed, desc->desc_id, &intro_content,
4216 &intro_size, &encoded_size,
4217 &next_desc, desc->desc_str, 1)) {
4218 /* Post the descriptor. */
4219 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
4220 if (!rend_get_service_id(parsed->pk, serviceid)) {
4221 smartlist_t *descs = smartlist_new();
4222 smartlist_add(descs, desc);
4224 /* We are about to trigger HS descriptor upload so send the OK now
4225 * because after that 650 event(s) are possible so better to have the
4226 * 250 OK before them to avoid out of order replies. */
4227 send_control_done(conn);
4229 /* Trigger the descriptor upload */
4230 directory_post_to_hs_dir(parsed, descs, hs_dirs, serviceid, 0);
4231 smartlist_free(descs);
4234 rend_service_descriptor_free(parsed);
4235 } else {
4236 connection_printf_to_buf(conn, "554 Invalid descriptor\r\n");
4239 tor_free(intro_content);
4240 rend_encoded_v2_service_descriptor_free(desc);
4241 done:
4242 tor_free(argline);
4243 smartlist_free(hs_dirs); /* Contents belong to the rend service code. */
4244 SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
4245 smartlist_free(args);
4246 return 0;
4249 /** Called when we get a ADD_ONION command; parse the body, and set up
4250 * the new ephemeral Onion Service. */
4251 static int
4252 handle_control_add_onion(control_connection_t *conn,
4253 uint32_t len,
4254 const char *body)
4256 smartlist_t *args;
4257 size_t arg_len;
4258 (void) len; /* body is nul-terminated; it's safe to ignore the length */
4259 args = getargs_helper("ADD_ONION", conn, body, 2, -1);
4260 if (!args)
4261 return 0;
4262 arg_len = smartlist_len(args);
4264 /* Parse all of the arguments that do not involve handling cryptographic
4265 * material first, since there's no reason to touch that at all if any of
4266 * the other arguments are malformed.
4268 smartlist_t *port_cfgs = smartlist_new();
4269 smartlist_t *auth_clients = NULL;
4270 smartlist_t *auth_created_clients = NULL;
4271 int discard_pk = 0;
4272 int detach = 0;
4273 int max_streams = 0;
4274 int max_streams_close_circuit = 0;
4275 rend_auth_type_t auth_type = REND_NO_AUTH;
4276 /* Default to adding an anonymous hidden service if no flag is given */
4277 int non_anonymous = 0;
4278 for (size_t i = 1; i < arg_len; i++) {
4279 static const char *port_prefix = "Port=";
4280 static const char *flags_prefix = "Flags=";
4281 static const char *max_s_prefix = "MaxStreams=";
4282 static const char *auth_prefix = "ClientAuth=";
4284 const char *arg = smartlist_get(args, i);
4285 if (!strcasecmpstart(arg, port_prefix)) {
4286 /* "Port=VIRTPORT[,TARGET]". */
4287 const char *port_str = arg + strlen(port_prefix);
4289 rend_service_port_config_t *cfg =
4290 rend_service_parse_port_config(port_str, ",", NULL);
4291 if (!cfg) {
4292 connection_printf_to_buf(conn, "512 Invalid VIRTPORT/TARGET\r\n");
4293 goto out;
4295 smartlist_add(port_cfgs, cfg);
4296 } else if (!strcasecmpstart(arg, max_s_prefix)) {
4297 /* "MaxStreams=[0..65535]". */
4298 const char *max_s_str = arg + strlen(max_s_prefix);
4299 int ok = 0;
4300 max_streams = (int)tor_parse_long(max_s_str, 10, 0, 65535, &ok, NULL);
4301 if (!ok) {
4302 connection_printf_to_buf(conn, "512 Invalid MaxStreams\r\n");
4303 goto out;
4305 } else if (!strcasecmpstart(arg, flags_prefix)) {
4306 /* "Flags=Flag[,Flag]", where Flag can be:
4307 * * 'DiscardPK' - If tor generates the keypair, do not include it in
4308 * the response.
4309 * * 'Detach' - Do not tie this onion service to any particular control
4310 * connection.
4311 * * 'MaxStreamsCloseCircuit' - Close the circuit if MaxStreams is
4312 * exceeded.
4313 * * 'BasicAuth' - Client authorization using the 'basic' method.
4314 * * 'NonAnonymous' - Add a non-anonymous Single Onion Service. If this
4315 * flag is present, tor must be in non-anonymous
4316 * hidden service mode. If this flag is absent,
4317 * tor must be in anonymous hidden service mode.
4319 static const char *discard_flag = "DiscardPK";
4320 static const char *detach_flag = "Detach";
4321 static const char *max_s_close_flag = "MaxStreamsCloseCircuit";
4322 static const char *basicauth_flag = "BasicAuth";
4323 static const char *non_anonymous_flag = "NonAnonymous";
4325 smartlist_t *flags = smartlist_new();
4326 int bad = 0;
4328 smartlist_split_string(flags, arg + strlen(flags_prefix), ",",
4329 SPLIT_IGNORE_BLANK, 0);
4330 if (smartlist_len(flags) < 1) {
4331 connection_printf_to_buf(conn, "512 Invalid 'Flags' argument\r\n");
4332 bad = 1;
4334 SMARTLIST_FOREACH_BEGIN(flags, const char *, flag)
4336 if (!strcasecmp(flag, discard_flag)) {
4337 discard_pk = 1;
4338 } else if (!strcasecmp(flag, detach_flag)) {
4339 detach = 1;
4340 } else if (!strcasecmp(flag, max_s_close_flag)) {
4341 max_streams_close_circuit = 1;
4342 } else if (!strcasecmp(flag, basicauth_flag)) {
4343 auth_type = REND_BASIC_AUTH;
4344 } else if (!strcasecmp(flag, non_anonymous_flag)) {
4345 non_anonymous = 1;
4346 } else {
4347 connection_printf_to_buf(conn,
4348 "512 Invalid 'Flags' argument: %s\r\n",
4349 escaped(flag));
4350 bad = 1;
4351 break;
4353 } SMARTLIST_FOREACH_END(flag);
4354 SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
4355 smartlist_free(flags);
4356 if (bad)
4357 goto out;
4358 } else if (!strcasecmpstart(arg, auth_prefix)) {
4359 char *err_msg = NULL;
4360 int created = 0;
4361 rend_authorized_client_t *client =
4362 add_onion_helper_clientauth(arg + strlen(auth_prefix),
4363 &created, &err_msg);
4364 if (!client) {
4365 if (err_msg) {
4366 connection_write_str_to_buf(err_msg, conn);
4367 tor_free(err_msg);
4369 goto out;
4372 if (auth_clients != NULL) {
4373 int bad = 0;
4374 SMARTLIST_FOREACH_BEGIN(auth_clients, rend_authorized_client_t *, ac) {
4375 if (strcmp(ac->client_name, client->client_name) == 0) {
4376 bad = 1;
4377 break;
4379 } SMARTLIST_FOREACH_END(ac);
4380 if (bad) {
4381 connection_printf_to_buf(conn,
4382 "512 Duplicate name in ClientAuth\r\n");
4383 rend_authorized_client_free(client);
4384 goto out;
4386 } else {
4387 auth_clients = smartlist_new();
4388 auth_created_clients = smartlist_new();
4390 smartlist_add(auth_clients, client);
4391 if (created) {
4392 smartlist_add(auth_created_clients, client);
4394 } else {
4395 connection_printf_to_buf(conn, "513 Invalid argument\r\n");
4396 goto out;
4399 if (smartlist_len(port_cfgs) == 0) {
4400 connection_printf_to_buf(conn, "512 Missing 'Port' argument\r\n");
4401 goto out;
4402 } else if (auth_type == REND_NO_AUTH && auth_clients != NULL) {
4403 connection_printf_to_buf(conn, "512 No auth type specified\r\n");
4404 goto out;
4405 } else if (auth_type != REND_NO_AUTH && auth_clients == NULL) {
4406 connection_printf_to_buf(conn, "512 No auth clients specified\r\n");
4407 goto out;
4408 } else if ((auth_type == REND_BASIC_AUTH &&
4409 smartlist_len(auth_clients) > 512) ||
4410 (auth_type == REND_STEALTH_AUTH &&
4411 smartlist_len(auth_clients) > 16)) {
4412 connection_printf_to_buf(conn, "512 Too many auth clients\r\n");
4413 goto out;
4414 } else if (non_anonymous != rend_service_non_anonymous_mode_enabled(
4415 get_options())) {
4416 /* If we failed, and the non-anonymous flag is set, Tor must be in
4417 * anonymous hidden service mode.
4418 * The error message changes based on the current Tor config:
4419 * 512 Tor is in anonymous hidden service mode
4420 * 512 Tor is in non-anonymous hidden service mode
4421 * (I've deliberately written them out in full here to aid searchability.)
4423 connection_printf_to_buf(conn, "512 Tor is in %sanonymous hidden service "
4424 "mode\r\n",
4425 non_anonymous ? "" : "non-");
4426 goto out;
4429 /* Parse the "keytype:keyblob" argument. */
4430 crypto_pk_t *pk = NULL;
4431 const char *key_new_alg = NULL;
4432 char *key_new_blob = NULL;
4433 char *err_msg = NULL;
4435 pk = add_onion_helper_keyarg(smartlist_get(args, 0), discard_pk,
4436 &key_new_alg, &key_new_blob,
4437 &err_msg);
4438 if (!pk) {
4439 if (err_msg) {
4440 connection_write_str_to_buf(err_msg, conn);
4441 tor_free(err_msg);
4443 goto out;
4445 tor_assert(!err_msg);
4447 /* Create the HS, using private key pk, client authentication auth_type,
4448 * the list of auth_clients, and port config port_cfg.
4449 * rend_service_add_ephemeral() will take ownership of pk and port_cfg,
4450 * regardless of success/failure.
4452 char *service_id = NULL;
4453 int ret = rend_service_add_ephemeral(pk, port_cfgs, max_streams,
4454 max_streams_close_circuit,
4455 auth_type, auth_clients,
4456 &service_id);
4457 port_cfgs = NULL; /* port_cfgs is now owned by the rendservice code. */
4458 auth_clients = NULL; /* so is auth_clients */
4459 switch (ret) {
4460 case RSAE_OKAY:
4462 if (detach) {
4463 if (!detached_onion_services)
4464 detached_onion_services = smartlist_new();
4465 smartlist_add(detached_onion_services, service_id);
4466 } else {
4467 if (!conn->ephemeral_onion_services)
4468 conn->ephemeral_onion_services = smartlist_new();
4469 smartlist_add(conn->ephemeral_onion_services, service_id);
4472 tor_assert(service_id);
4473 connection_printf_to_buf(conn, "250-ServiceID=%s\r\n", service_id);
4474 if (key_new_alg) {
4475 tor_assert(key_new_blob);
4476 connection_printf_to_buf(conn, "250-PrivateKey=%s:%s\r\n",
4477 key_new_alg, key_new_blob);
4479 if (auth_created_clients) {
4480 SMARTLIST_FOREACH(auth_created_clients, rend_authorized_client_t *, ac, {
4481 char *encoded = rend_auth_encode_cookie(ac->descriptor_cookie,
4482 auth_type);
4483 tor_assert(encoded);
4484 connection_printf_to_buf(conn, "250-ClientAuth=%s:%s\r\n",
4485 ac->client_name, encoded);
4486 memwipe(encoded, 0, strlen(encoded));
4487 tor_free(encoded);
4491 connection_printf_to_buf(conn, "250 OK\r\n");
4492 break;
4494 case RSAE_BADPRIVKEY:
4495 connection_printf_to_buf(conn, "551 Failed to generate onion address\r\n");
4496 break;
4497 case RSAE_ADDREXISTS:
4498 connection_printf_to_buf(conn, "550 Onion address collision\r\n");
4499 break;
4500 case RSAE_BADVIRTPORT:
4501 connection_printf_to_buf(conn, "512 Invalid VIRTPORT/TARGET\r\n");
4502 break;
4503 case RSAE_BADAUTH:
4504 connection_printf_to_buf(conn, "512 Invalid client authorization\r\n");
4505 break;
4506 case RSAE_INTERNAL: /* FALLSTHROUGH */
4507 default:
4508 connection_printf_to_buf(conn, "551 Failed to add Onion Service\r\n");
4510 if (key_new_blob) {
4511 memwipe(key_new_blob, 0, strlen(key_new_blob));
4512 tor_free(key_new_blob);
4515 out:
4516 if (port_cfgs) {
4517 SMARTLIST_FOREACH(port_cfgs, rend_service_port_config_t*, p,
4518 rend_service_port_config_free(p));
4519 smartlist_free(port_cfgs);
4522 if (auth_clients) {
4523 SMARTLIST_FOREACH(auth_clients, rend_authorized_client_t *, ac,
4524 rend_authorized_client_free(ac));
4525 smartlist_free(auth_clients);
4527 if (auth_created_clients) {
4528 // Do not free entries; they are the same as auth_clients
4529 smartlist_free(auth_created_clients);
4532 SMARTLIST_FOREACH(args, char *, cp, {
4533 memwipe(cp, 0, strlen(cp));
4534 tor_free(cp);
4536 smartlist_free(args);
4537 return 0;
4540 /** Helper function to handle parsing the KeyType:KeyBlob argument to the
4541 * ADD_ONION command. Return a new crypto_pk_t and if a new key was generated
4542 * and the private key not discarded, the algorithm and serialized private key,
4543 * or NULL and an optional control protocol error message on failure. The
4544 * caller is responsible for freeing the returned key_new_blob and err_msg.
4546 * Note: The error messages returned are deliberately vague to avoid echoing
4547 * key material.
4549 STATIC crypto_pk_t *
4550 add_onion_helper_keyarg(const char *arg, int discard_pk,
4551 const char **key_new_alg_out, char **key_new_blob_out,
4552 char **err_msg_out)
4554 smartlist_t *key_args = smartlist_new();
4555 crypto_pk_t *pk = NULL;
4556 const char *key_new_alg = NULL;
4557 char *key_new_blob = NULL;
4558 char *err_msg = NULL;
4559 int ok = 0;
4561 smartlist_split_string(key_args, arg, ":", SPLIT_IGNORE_BLANK, 0);
4562 if (smartlist_len(key_args) != 2) {
4563 err_msg = tor_strdup("512 Invalid key type/blob\r\n");
4564 goto err;
4567 /* The format is "KeyType:KeyBlob". */
4568 static const char *key_type_new = "NEW";
4569 static const char *key_type_best = "BEST";
4570 static const char *key_type_rsa1024 = "RSA1024";
4572 const char *key_type = smartlist_get(key_args, 0);
4573 const char *key_blob = smartlist_get(key_args, 1);
4575 if (!strcasecmp(key_type_rsa1024, key_type)) {
4576 /* "RSA:<Base64 Blob>" - Loading a pre-existing RSA1024 key. */
4577 pk = crypto_pk_base64_decode(key_blob, strlen(key_blob));
4578 if (!pk) {
4579 err_msg = tor_strdup("512 Failed to decode RSA key\r\n");
4580 goto err;
4582 if (crypto_pk_num_bits(pk) != PK_BYTES*8) {
4583 err_msg = tor_strdup("512 Invalid RSA key size\r\n");
4584 goto err;
4586 } else if (!strcasecmp(key_type_new, key_type)) {
4587 /* "NEW:<Algorithm>" - Generating a new key, blob as algorithm. */
4588 if (!strcasecmp(key_type_rsa1024, key_blob) ||
4589 !strcasecmp(key_type_best, key_blob)) {
4590 /* "RSA1024", RSA 1024 bit, also currently "BEST" by default. */
4591 pk = crypto_pk_new();
4592 if (crypto_pk_generate_key(pk)) {
4593 tor_asprintf(&err_msg, "551 Failed to generate %s key\r\n",
4594 key_type_rsa1024);
4595 goto err;
4597 if (!discard_pk) {
4598 if (crypto_pk_base64_encode(pk, &key_new_blob)) {
4599 tor_asprintf(&err_msg, "551 Failed to encode %s key\r\n",
4600 key_type_rsa1024);
4601 goto err;
4603 key_new_alg = key_type_rsa1024;
4605 } else {
4606 err_msg = tor_strdup("513 Invalid key type\r\n");
4607 goto err;
4609 } else {
4610 err_msg = tor_strdup("513 Invalid key type\r\n");
4611 goto err;
4614 /* Succeded in loading or generating a private key. */
4615 tor_assert(pk);
4616 ok = 1;
4618 err:
4619 SMARTLIST_FOREACH(key_args, char *, cp, {
4620 memwipe(cp, 0, strlen(cp));
4621 tor_free(cp);
4623 smartlist_free(key_args);
4625 if (!ok) {
4626 crypto_pk_free(pk);
4627 pk = NULL;
4629 if (err_msg_out) {
4630 *err_msg_out = err_msg;
4631 } else {
4632 tor_free(err_msg);
4634 *key_new_alg_out = key_new_alg;
4635 *key_new_blob_out = key_new_blob;
4637 return pk;
4640 /** Helper function to handle parsing a ClientAuth argument to the
4641 * ADD_ONION command. Return a new rend_authorized_client_t, or NULL
4642 * and an optional control protocol error message on failure. The
4643 * caller is responsible for freeing the returned auth_client and err_msg.
4645 * If 'created' is specified, it will be set to 1 when a new cookie has
4646 * been generated.
4648 STATIC rend_authorized_client_t *
4649 add_onion_helper_clientauth(const char *arg, int *created, char **err_msg)
4651 int ok = 0;
4653 tor_assert(arg);
4654 tor_assert(created);
4655 tor_assert(err_msg);
4656 *err_msg = NULL;
4658 smartlist_t *auth_args = smartlist_new();
4659 rend_authorized_client_t *client =
4660 tor_malloc_zero(sizeof(rend_authorized_client_t));
4661 smartlist_split_string(auth_args, arg, ":", 0, 0);
4662 if (smartlist_len(auth_args) < 1 || smartlist_len(auth_args) > 2) {
4663 *err_msg = tor_strdup("512 Invalid ClientAuth syntax\r\n");
4664 goto err;
4666 client->client_name = tor_strdup(smartlist_get(auth_args, 0));
4667 if (smartlist_len(auth_args) == 2) {
4668 char *decode_err_msg = NULL;
4669 if (rend_auth_decode_cookie(smartlist_get(auth_args, 1),
4670 client->descriptor_cookie,
4671 NULL, &decode_err_msg) < 0) {
4672 tor_assert(decode_err_msg);
4673 tor_asprintf(err_msg, "512 %s\r\n", decode_err_msg);
4674 tor_free(decode_err_msg);
4675 goto err;
4677 *created = 0;
4678 } else {
4679 crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
4680 *created = 1;
4683 if (!rend_valid_client_name(client->client_name)) {
4684 *err_msg = tor_strdup("512 Invalid name in ClientAuth\r\n");
4685 goto err;
4688 ok = 1;
4689 err:
4690 SMARTLIST_FOREACH(auth_args, char *, item, tor_free(item));
4691 smartlist_free(auth_args);
4692 if (!ok) {
4693 rend_authorized_client_free(client);
4694 client = NULL;
4696 return client;
4699 /** Called when we get a DEL_ONION command; parse the body, and remove
4700 * the existing ephemeral Onion Service. */
4701 static int
4702 handle_control_del_onion(control_connection_t *conn,
4703 uint32_t len,
4704 const char *body)
4706 smartlist_t *args;
4707 (void) len; /* body is nul-terminated; it's safe to ignore the length */
4708 args = getargs_helper("DEL_ONION", conn, body, 1, 1);
4709 if (!args)
4710 return 0;
4712 const char *service_id = smartlist_get(args, 0);
4713 if (!rend_valid_service_id(service_id)) {
4714 connection_printf_to_buf(conn, "512 Malformed Onion Service id\r\n");
4715 goto out;
4718 /* Determine if the onion service belongs to this particular control
4719 * connection, or if it is in the global list of detached services. If it
4720 * is in neither, either the service ID is invalid in some way, or it
4721 * explicitly belongs to a different control connection, and an error
4722 * should be returned.
4724 smartlist_t *services[2] = {
4725 conn->ephemeral_onion_services,
4726 detached_onion_services
4728 smartlist_t *onion_services = NULL;
4729 int idx = -1;
4730 for (size_t i = 0; i < ARRAY_LENGTH(services); i++) {
4731 idx = smartlist_string_pos(services[i], service_id);
4732 if (idx != -1) {
4733 onion_services = services[i];
4734 break;
4737 if (onion_services == NULL) {
4738 connection_printf_to_buf(conn, "552 Unknown Onion Service id\r\n");
4739 } else {
4740 int ret = rend_service_del_ephemeral(service_id);
4741 if (ret) {
4742 /* This should *NEVER* fail, since the service is on either the
4743 * per-control connection list, or the global one.
4745 log_warn(LD_BUG, "Failed to remove Onion Service %s.",
4746 escaped(service_id));
4747 tor_fragile_assert();
4750 /* Remove/scrub the service_id from the appropriate list. */
4751 char *cp = smartlist_get(onion_services, idx);
4752 smartlist_del(onion_services, idx);
4753 memwipe(cp, 0, strlen(cp));
4754 tor_free(cp);
4756 send_control_done(conn);
4759 out:
4760 SMARTLIST_FOREACH(args, char *, cp, {
4761 memwipe(cp, 0, strlen(cp));
4762 tor_free(cp);
4764 smartlist_free(args);
4765 return 0;
4768 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
4770 connection_control_finished_flushing(control_connection_t *conn)
4772 tor_assert(conn);
4773 return 0;
4776 /** Called when <b>conn</b> has gotten its socket closed. */
4778 connection_control_reached_eof(control_connection_t *conn)
4780 tor_assert(conn);
4782 log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
4783 connection_mark_for_close(TO_CONN(conn));
4784 return 0;
4787 /** Shut down this Tor instance in the same way that SIGINT would, but
4788 * with a log message appropriate for the loss of an owning controller. */
4789 static void
4790 lost_owning_controller(const char *owner_type, const char *loss_manner)
4792 log_notice(LD_CONTROL, "Owning controller %s has %s -- exiting now.",
4793 owner_type, loss_manner);
4795 activate_signal(SIGTERM);
4798 /** Called when <b>conn</b> is being freed. */
4799 void
4800 connection_control_closed(control_connection_t *conn)
4802 tor_assert(conn);
4804 conn->event_mask = 0;
4805 control_update_global_event_mask();
4807 /* Close all ephemeral Onion Services if any.
4808 * The list and it's contents are scrubbed/freed in connection_free_.
4810 if (conn->ephemeral_onion_services) {
4811 SMARTLIST_FOREACH(conn->ephemeral_onion_services, char *, cp, {
4812 rend_service_del_ephemeral(cp);
4816 if (conn->is_owning_control_connection) {
4817 lost_owning_controller("connection", "closed");
4821 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
4822 * stage of the protocol. */
4823 static int
4824 is_valid_initial_command(control_connection_t *conn, const char *cmd)
4826 if (conn->base_.state == CONTROL_CONN_STATE_OPEN)
4827 return 1;
4828 if (!strcasecmp(cmd, "PROTOCOLINFO"))
4829 return (!conn->have_sent_protocolinfo &&
4830 conn->safecookie_client_hash == NULL);
4831 if (!strcasecmp(cmd, "AUTHCHALLENGE"))
4832 return (conn->safecookie_client_hash == NULL);
4833 if (!strcasecmp(cmd, "AUTHENTICATE") ||
4834 !strcasecmp(cmd, "QUIT"))
4835 return 1;
4836 return 0;
4839 /** Do not accept any control command of more than 1MB in length. Anything
4840 * that needs to be anywhere near this long probably means that one of our
4841 * interfaces is broken. */
4842 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
4844 /** Wrapper around peek_buf_has_control0 command: presents the same
4845 * interface as that underlying functions, but takes a connection_t intead of
4846 * a buf_t.
4848 static int
4849 peek_connection_has_control0_command(connection_t *conn)
4851 return peek_buf_has_control0_command(conn->inbuf);
4854 /** Called when data has arrived on a v1 control connection: Try to fetch
4855 * commands from conn->inbuf, and execute them.
4858 connection_control_process_inbuf(control_connection_t *conn)
4860 size_t data_len;
4861 uint32_t cmd_data_len;
4862 int cmd_len;
4863 char *args;
4865 tor_assert(conn);
4866 tor_assert(conn->base_.state == CONTROL_CONN_STATE_OPEN ||
4867 conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH);
4869 if (!conn->incoming_cmd) {
4870 conn->incoming_cmd = tor_malloc(1024);
4871 conn->incoming_cmd_len = 1024;
4872 conn->incoming_cmd_cur_len = 0;
4875 if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
4876 peek_connection_has_control0_command(TO_CONN(conn))) {
4877 /* Detect v0 commands and send a "no more v0" message. */
4878 size_t body_len;
4879 char buf[128];
4880 set_uint16(buf+2, htons(0x0000)); /* type == error */
4881 set_uint16(buf+4, htons(0x0001)); /* code == internal error */
4882 strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
4883 "and later; upgrade your controller.",
4884 sizeof(buf)-6);
4885 body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
4886 set_uint16(buf+0, htons(body_len));
4887 connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
4889 connection_mark_and_flush(TO_CONN(conn));
4890 return 0;
4893 again:
4894 while (1) {
4895 size_t last_idx;
4896 int r;
4897 /* First, fetch a line. */
4898 do {
4899 data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
4900 r = connection_fetch_from_buf_line(TO_CONN(conn),
4901 conn->incoming_cmd+conn->incoming_cmd_cur_len,
4902 &data_len);
4903 if (r == 0)
4904 /* Line not all here yet. Wait. */
4905 return 0;
4906 else if (r == -1) {
4907 if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
4908 connection_write_str_to_buf("500 Line too long.\r\n", conn);
4909 connection_stop_reading(TO_CONN(conn));
4910 connection_mark_and_flush(TO_CONN(conn));
4912 while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
4913 conn->incoming_cmd_len *= 2;
4914 conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
4915 conn->incoming_cmd_len);
4917 } while (r != 1);
4919 tor_assert(data_len);
4921 last_idx = conn->incoming_cmd_cur_len;
4922 conn->incoming_cmd_cur_len += (int)data_len;
4924 /* We have appended a line to incoming_cmd. Is the command done? */
4925 if (last_idx == 0 && *conn->incoming_cmd != '+')
4926 /* One line command, didn't start with '+'. */
4927 break;
4928 /* XXXX this code duplication is kind of dumb. */
4929 if (last_idx+3 == conn->incoming_cmd_cur_len &&
4930 tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
4931 /* Just appended ".\r\n"; we're done. Remove it. */
4932 conn->incoming_cmd[last_idx] = '\0';
4933 conn->incoming_cmd_cur_len -= 3;
4934 break;
4935 } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
4936 tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
4937 /* Just appended ".\n"; we're done. Remove it. */
4938 conn->incoming_cmd[last_idx] = '\0';
4939 conn->incoming_cmd_cur_len -= 2;
4940 break;
4942 /* Otherwise, read another line. */
4944 data_len = conn->incoming_cmd_cur_len;
4945 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
4946 * recognize it.
4948 cmd_len = 0;
4949 while ((size_t)cmd_len < data_len
4950 && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
4951 ++cmd_len;
4953 conn->incoming_cmd[cmd_len]='\0';
4954 args = conn->incoming_cmd+cmd_len+1;
4955 tor_assert(data_len>(size_t)cmd_len);
4956 data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
4957 while (TOR_ISSPACE(*args)) {
4958 ++args;
4959 --data_len;
4962 /* If the connection is already closing, ignore further commands */
4963 if (TO_CONN(conn)->marked_for_close) {
4964 return 0;
4967 /* Otherwise, Quit is always valid. */
4968 if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
4969 connection_write_str_to_buf("250 closing connection\r\n", conn);
4970 connection_mark_and_flush(TO_CONN(conn));
4971 return 0;
4974 if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
4975 !is_valid_initial_command(conn, conn->incoming_cmd)) {
4976 connection_write_str_to_buf("514 Authentication required.\r\n", conn);
4977 connection_mark_for_close(TO_CONN(conn));
4978 return 0;
4981 if (data_len >= UINT32_MAX) {
4982 connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
4983 connection_mark_for_close(TO_CONN(conn));
4984 return 0;
4987 /* XXXX Why is this not implemented as a table like the GETINFO
4988 * items are? Even handling the plus signs at the beginnings of
4989 * commands wouldn't be very hard with proper macros. */
4990 cmd_data_len = (uint32_t)data_len;
4991 if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
4992 if (handle_control_setconf(conn, cmd_data_len, args))
4993 return -1;
4994 } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
4995 if (handle_control_resetconf(conn, cmd_data_len, args))
4996 return -1;
4997 } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
4998 if (handle_control_getconf(conn, cmd_data_len, args))
4999 return -1;
5000 } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
5001 if (handle_control_loadconf(conn, cmd_data_len, args))
5002 return -1;
5003 } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
5004 if (handle_control_setevents(conn, cmd_data_len, args))
5005 return -1;
5006 } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
5007 if (handle_control_authenticate(conn, cmd_data_len, args))
5008 return -1;
5009 } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
5010 if (handle_control_saveconf(conn, cmd_data_len, args))
5011 return -1;
5012 } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
5013 if (handle_control_signal(conn, cmd_data_len, args))
5014 return -1;
5015 } else if (!strcasecmp(conn->incoming_cmd, "TAKEOWNERSHIP")) {
5016 if (handle_control_takeownership(conn, cmd_data_len, args))
5017 return -1;
5018 } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
5019 if (handle_control_mapaddress(conn, cmd_data_len, args))
5020 return -1;
5021 } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
5022 if (handle_control_getinfo(conn, cmd_data_len, args))
5023 return -1;
5024 } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
5025 if (handle_control_extendcircuit(conn, cmd_data_len, args))
5026 return -1;
5027 } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
5028 if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
5029 return -1;
5030 } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
5031 connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
5032 } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
5033 if (handle_control_attachstream(conn, cmd_data_len, args))
5034 return -1;
5035 } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
5036 if (handle_control_postdescriptor(conn, cmd_data_len, args))
5037 return -1;
5038 } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
5039 if (handle_control_redirectstream(conn, cmd_data_len, args))
5040 return -1;
5041 } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
5042 if (handle_control_closestream(conn, cmd_data_len, args))
5043 return -1;
5044 } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
5045 if (handle_control_closecircuit(conn, cmd_data_len, args))
5046 return -1;
5047 } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
5048 if (handle_control_usefeature(conn, cmd_data_len, args))
5049 return -1;
5050 } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
5051 if (handle_control_resolve(conn, cmd_data_len, args))
5052 return -1;
5053 } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
5054 if (handle_control_protocolinfo(conn, cmd_data_len, args))
5055 return -1;
5056 } else if (!strcasecmp(conn->incoming_cmd, "AUTHCHALLENGE")) {
5057 if (handle_control_authchallenge(conn, cmd_data_len, args))
5058 return -1;
5059 } else if (!strcasecmp(conn->incoming_cmd, "DROPGUARDS")) {
5060 if (handle_control_dropguards(conn, cmd_data_len, args))
5061 return -1;
5062 } else if (!strcasecmp(conn->incoming_cmd, "HSFETCH")) {
5063 if (handle_control_hsfetch(conn, cmd_data_len, args))
5064 return -1;
5065 } else if (!strcasecmp(conn->incoming_cmd, "+HSPOST")) {
5066 if (handle_control_hspost(conn, cmd_data_len, args))
5067 return -1;
5068 } else if (!strcasecmp(conn->incoming_cmd, "ADD_ONION")) {
5069 int ret = handle_control_add_onion(conn, cmd_data_len, args);
5070 memwipe(args, 0, cmd_data_len); /* Scrub the private key. */
5071 if (ret)
5072 return -1;
5073 } else if (!strcasecmp(conn->incoming_cmd, "DEL_ONION")) {
5074 int ret = handle_control_del_onion(conn, cmd_data_len, args);
5075 memwipe(args, 0, cmd_data_len); /* Scrub the service id/pk. */
5076 if (ret)
5077 return -1;
5078 } else {
5079 connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
5080 conn->incoming_cmd);
5083 conn->incoming_cmd_cur_len = 0;
5084 goto again;
5087 /** Something major has happened to circuit <b>circ</b>: tell any
5088 * interested control connections. */
5090 control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
5091 int reason_code)
5093 const char *status;
5094 char reasons[64] = "";
5095 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
5096 return 0;
5097 tor_assert(circ);
5099 switch (tp)
5101 case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
5102 case CIRC_EVENT_BUILT: status = "BUILT"; break;
5103 case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
5104 case CIRC_EVENT_FAILED: status = "FAILED"; break;
5105 case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
5106 default:
5107 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
5108 tor_fragile_assert();
5109 return 0;
5112 if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
5113 const char *reason_str = circuit_end_reason_to_control_string(reason_code);
5114 char unk_reason_buf[16];
5115 if (!reason_str) {
5116 tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
5117 reason_str = unk_reason_buf;
5119 if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
5120 tor_snprintf(reasons, sizeof(reasons),
5121 " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
5122 } else {
5123 tor_snprintf(reasons, sizeof(reasons),
5124 " REASON=%s", reason_str);
5129 char *circdesc = circuit_describe_status_for_controller(circ);
5130 const char *sp = strlen(circdesc) ? " " : "";
5131 send_control_event(EVENT_CIRCUIT_STATUS,
5132 "650 CIRC %lu %s%s%s%s\r\n",
5133 (unsigned long)circ->global_identifier,
5134 status, sp,
5135 circdesc,
5136 reasons);
5137 tor_free(circdesc);
5140 return 0;
5143 /** Something minor has happened to circuit <b>circ</b>: tell any
5144 * interested control connections. */
5145 static int
5146 control_event_circuit_status_minor(origin_circuit_t *circ,
5147 circuit_status_minor_event_t e,
5148 int purpose, const struct timeval *tv)
5150 const char *event_desc;
5151 char event_tail[160] = "";
5152 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
5153 return 0;
5154 tor_assert(circ);
5156 switch (e)
5158 case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
5159 event_desc = "PURPOSE_CHANGED";
5162 /* event_tail can currently be up to 68 chars long */
5163 const char *hs_state_str =
5164 circuit_purpose_to_controller_hs_state_string(purpose);
5165 tor_snprintf(event_tail, sizeof(event_tail),
5166 " OLD_PURPOSE=%s%s%s",
5167 circuit_purpose_to_controller_string(purpose),
5168 (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
5169 (hs_state_str != NULL) ? hs_state_str : "");
5172 break;
5173 case CIRC_MINOR_EVENT_CANNIBALIZED:
5174 event_desc = "CANNIBALIZED";
5177 /* event_tail can currently be up to 130 chars long */
5178 const char *hs_state_str =
5179 circuit_purpose_to_controller_hs_state_string(purpose);
5180 const struct timeval *old_timestamp_began = tv;
5181 char tbuf[ISO_TIME_USEC_LEN+1];
5182 format_iso_time_nospace_usec(tbuf, old_timestamp_began);
5184 tor_snprintf(event_tail, sizeof(event_tail),
5185 " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
5186 circuit_purpose_to_controller_string(purpose),
5187 (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
5188 (hs_state_str != NULL) ? hs_state_str : "",
5189 tbuf);
5192 break;
5193 default:
5194 log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
5195 tor_fragile_assert();
5196 return 0;
5200 char *circdesc = circuit_describe_status_for_controller(circ);
5201 const char *sp = strlen(circdesc) ? " " : "";
5202 send_control_event(EVENT_CIRCUIT_STATUS_MINOR,
5203 "650 CIRC_MINOR %lu %s%s%s%s\r\n",
5204 (unsigned long)circ->global_identifier,
5205 event_desc, sp,
5206 circdesc,
5207 event_tail);
5208 tor_free(circdesc);
5211 return 0;
5215 * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
5216 * interested controllers.
5219 control_event_circuit_purpose_changed(origin_circuit_t *circ,
5220 int old_purpose)
5222 return control_event_circuit_status_minor(circ,
5223 CIRC_MINOR_EVENT_PURPOSE_CHANGED,
5224 old_purpose,
5225 NULL);
5229 * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
5230 * created-time from <b>old_tv_created</b>: tell any interested controllers.
5233 control_event_circuit_cannibalized(origin_circuit_t *circ,
5234 int old_purpose,
5235 const struct timeval *old_tv_created)
5237 return control_event_circuit_status_minor(circ,
5238 CIRC_MINOR_EVENT_CANNIBALIZED,
5239 old_purpose,
5240 old_tv_created);
5243 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
5244 * <b>buf</b>, determine the address:port combination requested on
5245 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
5246 * failure. */
5247 static int
5248 write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
5250 char buf2[256];
5251 if (conn->chosen_exit_name)
5252 if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
5253 return -1;
5254 if (!conn->socks_request)
5255 return -1;
5256 if (tor_snprintf(buf, len, "%s%s%s:%d",
5257 conn->socks_request->address,
5258 conn->chosen_exit_name ? buf2 : "",
5259 !conn->chosen_exit_name && connection_edge_is_rendezvous_stream(
5260 ENTRY_TO_EDGE_CONN(conn)) ? ".onion" : "",
5261 conn->socks_request->port)<0)
5262 return -1;
5263 return 0;
5266 /** Something has happened to the stream associated with AP connection
5267 * <b>conn</b>: tell any interested control connections. */
5269 control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
5270 int reason_code)
5272 char reason_buf[64];
5273 char addrport_buf[64];
5274 const char *status;
5275 circuit_t *circ;
5276 origin_circuit_t *origin_circ = NULL;
5277 char buf[256];
5278 const char *purpose = "";
5279 tor_assert(conn->socks_request);
5281 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
5282 return 0;
5284 if (tp == STREAM_EVENT_CLOSED &&
5285 (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
5286 return 0;
5288 write_stream_target_to_buf(conn, buf, sizeof(buf));
5290 reason_buf[0] = '\0';
5291 switch (tp)
5293 case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
5294 case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
5295 case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
5296 case STREAM_EVENT_FAILED: status = "FAILED"; break;
5297 case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
5298 case STREAM_EVENT_NEW: status = "NEW"; break;
5299 case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
5300 case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
5301 case STREAM_EVENT_REMAP: status = "REMAP"; break;
5302 default:
5303 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
5304 return 0;
5306 if (reason_code && (tp == STREAM_EVENT_FAILED ||
5307 tp == STREAM_EVENT_CLOSED ||
5308 tp == STREAM_EVENT_FAILED_RETRIABLE)) {
5309 const char *reason_str = stream_end_reason_to_control_string(reason_code);
5310 char *r = NULL;
5311 if (!reason_str) {
5312 tor_asprintf(&r, " UNKNOWN_%d", reason_code);
5313 reason_str = r;
5315 if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
5316 tor_snprintf(reason_buf, sizeof(reason_buf),
5317 " REASON=END REMOTE_REASON=%s", reason_str);
5318 else
5319 tor_snprintf(reason_buf, sizeof(reason_buf),
5320 " REASON=%s", reason_str);
5321 tor_free(r);
5322 } else if (reason_code && tp == STREAM_EVENT_REMAP) {
5323 switch (reason_code) {
5324 case REMAP_STREAM_SOURCE_CACHE:
5325 strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
5326 break;
5327 case REMAP_STREAM_SOURCE_EXIT:
5328 strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
5329 break;
5330 default:
5331 tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
5332 reason_code);
5333 /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
5334 break;
5338 if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
5340 * When the control conn is an AF_UNIX socket and we have no address,
5341 * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
5342 * dnsserv.c.
5344 if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
5345 tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
5346 ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
5347 } else {
5349 * else leave it blank so control on AF_UNIX doesn't need to make
5350 * something up.
5352 addrport_buf[0] = '\0';
5354 } else {
5355 addrport_buf[0] = '\0';
5358 if (tp == STREAM_EVENT_NEW_RESOLVE) {
5359 purpose = " PURPOSE=DNS_REQUEST";
5360 } else if (tp == STREAM_EVENT_NEW) {
5361 if (conn->use_begindir) {
5362 connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
5363 int linked_dir_purpose = -1;
5364 if (linked && linked->type == CONN_TYPE_DIR)
5365 linked_dir_purpose = linked->purpose;
5366 if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
5367 purpose = " PURPOSE=DIR_UPLOAD";
5368 else
5369 purpose = " PURPOSE=DIR_FETCH";
5370 } else
5371 purpose = " PURPOSE=USER";
5374 circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
5375 if (circ && CIRCUIT_IS_ORIGIN(circ))
5376 origin_circ = TO_ORIGIN_CIRCUIT(circ);
5377 send_control_event(EVENT_STREAM_STATUS,
5378 "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
5379 U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
5380 status,
5381 origin_circ?
5382 (unsigned long)origin_circ->global_identifier : 0ul,
5383 buf, reason_buf, addrport_buf, purpose);
5385 /* XXX need to specify its intended exit, etc? */
5387 return 0;
5390 /** Figure out the best name for the target router of an OR connection
5391 * <b>conn</b>, and write it into the <b>len</b>-character buffer
5392 * <b>name</b>. */
5393 static void
5394 orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
5396 const node_t *node = node_get_by_id(conn->identity_digest);
5397 if (node) {
5398 tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
5399 node_get_verbose_nickname(node, name);
5400 } else if (! tor_digest_is_zero(conn->identity_digest)) {
5401 name[0] = '$';
5402 base16_encode(name+1, len-1, conn->identity_digest,
5403 DIGEST_LEN);
5404 } else {
5405 tor_snprintf(name, len, "%s:%d",
5406 conn->base_.address, conn->base_.port);
5410 /** Called when the status of an OR connection <b>conn</b> changes: tell any
5411 * interested control connections. <b>tp</b> is the new status for the
5412 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
5413 * may be the reason why.
5416 control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
5417 int reason)
5419 int ncircs = 0;
5420 const char *status;
5421 char name[128];
5422 char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
5424 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
5425 return 0;
5427 switch (tp)
5429 case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
5430 case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
5431 case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
5432 case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
5433 case OR_CONN_EVENT_NEW: status = "NEW"; break;
5434 default:
5435 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
5436 return 0;
5438 if (conn->chan) {
5439 ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
5440 } else {
5441 ncircs = 0;
5443 ncircs += connection_or_get_num_circuits(conn);
5444 if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
5445 tor_snprintf(ncircs_buf, sizeof(ncircs_buf), " NCIRCS=%d", ncircs);
5448 orconn_target_get_name(name, sizeof(name), conn);
5449 send_control_event(EVENT_OR_CONN_STATUS,
5450 "650 ORCONN %s %s%s%s%s ID="U64_FORMAT"\r\n",
5451 name, status,
5452 reason ? " REASON=" : "",
5453 orconn_end_reason_to_control_string(reason),
5454 ncircs_buf,
5455 U64_PRINTF_ARG(conn->base_.global_identifier));
5457 return 0;
5461 * Print out STREAM_BW event for a single conn
5464 control_event_stream_bandwidth(edge_connection_t *edge_conn)
5466 circuit_t *circ;
5467 origin_circuit_t *ocirc;
5468 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
5469 if (!edge_conn->n_read && !edge_conn->n_written)
5470 return 0;
5472 send_control_event(EVENT_STREAM_BANDWIDTH_USED,
5473 "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
5474 U64_PRINTF_ARG(edge_conn->base_.global_identifier),
5475 (unsigned long)edge_conn->n_read,
5476 (unsigned long)edge_conn->n_written);
5478 circ = circuit_get_by_edge_conn(edge_conn);
5479 if (circ && CIRCUIT_IS_ORIGIN(circ)) {
5480 ocirc = TO_ORIGIN_CIRCUIT(circ);
5481 ocirc->n_read_circ_bw += edge_conn->n_read;
5482 ocirc->n_written_circ_bw += edge_conn->n_written;
5484 edge_conn->n_written = edge_conn->n_read = 0;
5487 return 0;
5490 /** A second or more has elapsed: tell any interested control
5491 * connections how much bandwidth streams have used. */
5493 control_event_stream_bandwidth_used(void)
5495 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
5496 smartlist_t *conns = get_connection_array();
5497 edge_connection_t *edge_conn;
5499 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
5501 if (conn->type != CONN_TYPE_AP)
5502 continue;
5503 edge_conn = TO_EDGE_CONN(conn);
5504 if (!edge_conn->n_read && !edge_conn->n_written)
5505 continue;
5507 send_control_event(EVENT_STREAM_BANDWIDTH_USED,
5508 "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
5509 U64_PRINTF_ARG(edge_conn->base_.global_identifier),
5510 (unsigned long)edge_conn->n_read,
5511 (unsigned long)edge_conn->n_written);
5513 edge_conn->n_written = edge_conn->n_read = 0;
5515 SMARTLIST_FOREACH_END(conn);
5518 return 0;
5521 /** A second or more has elapsed: tell any interested control connections
5522 * how much bandwidth origin circuits have used. */
5524 control_event_circ_bandwidth_used(void)
5526 origin_circuit_t *ocirc;
5527 if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
5528 return 0;
5530 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
5531 if (!CIRCUIT_IS_ORIGIN(circ))
5532 continue;
5533 ocirc = TO_ORIGIN_CIRCUIT(circ);
5534 if (!ocirc->n_read_circ_bw && !ocirc->n_written_circ_bw)
5535 continue;
5536 send_control_event(EVENT_CIRC_BANDWIDTH_USED,
5537 "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu\r\n",
5538 ocirc->global_identifier,
5539 (unsigned long)ocirc->n_read_circ_bw,
5540 (unsigned long)ocirc->n_written_circ_bw);
5541 ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
5543 SMARTLIST_FOREACH_END(circ);
5545 return 0;
5548 /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
5549 * bandwidth counters. */
5551 control_event_conn_bandwidth(connection_t *conn)
5553 const char *conn_type_str;
5554 if (!get_options()->TestingEnableConnBwEvent ||
5555 !EVENT_IS_INTERESTING(EVENT_CONN_BW))
5556 return 0;
5557 if (!conn->n_read_conn_bw && !conn->n_written_conn_bw)
5558 return 0;
5559 switch (conn->type) {
5560 case CONN_TYPE_OR:
5561 conn_type_str = "OR";
5562 break;
5563 case CONN_TYPE_DIR:
5564 conn_type_str = "DIR";
5565 break;
5566 case CONN_TYPE_EXIT:
5567 conn_type_str = "EXIT";
5568 break;
5569 default:
5570 return 0;
5572 send_control_event(EVENT_CONN_BW,
5573 "650 CONN_BW ID="U64_FORMAT" TYPE=%s "
5574 "READ=%lu WRITTEN=%lu\r\n",
5575 U64_PRINTF_ARG(conn->global_identifier),
5576 conn_type_str,
5577 (unsigned long)conn->n_read_conn_bw,
5578 (unsigned long)conn->n_written_conn_bw);
5579 conn->n_written_conn_bw = conn->n_read_conn_bw = 0;
5580 return 0;
5583 /** A second or more has elapsed: tell any interested control
5584 * connections how much bandwidth connections have used. */
5586 control_event_conn_bandwidth_used(void)
5588 if (get_options()->TestingEnableConnBwEvent &&
5589 EVENT_IS_INTERESTING(EVENT_CONN_BW)) {
5590 SMARTLIST_FOREACH(get_connection_array(), connection_t *, conn,
5591 control_event_conn_bandwidth(conn));
5593 return 0;
5596 /** Helper: iterate over cell statistics of <b>circ</b> and sum up added
5597 * cells, removed cells, and waiting times by cell command and direction.
5598 * Store results in <b>cell_stats</b>. Free cell statistics of the
5599 * circuit afterwards. */
5600 void
5601 sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
5603 memset(cell_stats, 0, sizeof(cell_stats_t));
5604 SMARTLIST_FOREACH_BEGIN(circ->testing_cell_stats,
5605 const testing_cell_stats_entry_t *, ent) {
5606 tor_assert(ent->command <= CELL_COMMAND_MAX_);
5607 if (!ent->removed && !ent->exitward) {
5608 cell_stats->added_cells_appward[ent->command] += 1;
5609 } else if (!ent->removed && ent->exitward) {
5610 cell_stats->added_cells_exitward[ent->command] += 1;
5611 } else if (!ent->exitward) {
5612 cell_stats->removed_cells_appward[ent->command] += 1;
5613 cell_stats->total_time_appward[ent->command] += ent->waiting_time * 10;
5614 } else {
5615 cell_stats->removed_cells_exitward[ent->command] += 1;
5616 cell_stats->total_time_exitward[ent->command] += ent->waiting_time * 10;
5618 } SMARTLIST_FOREACH_END(ent);
5619 circuit_clear_testing_cell_stats(circ);
5622 /** Helper: append a cell statistics string to <code>event_parts</code>,
5623 * prefixed with <code>key</code>=. Statistics consist of comma-separated
5624 * key:value pairs with lower-case command strings as keys and cell
5625 * numbers or total waiting times as values. A key:value pair is included
5626 * if the entry in <code>include_if_non_zero</code> is not zero, but with
5627 * the (possibly zero) entry from <code>number_to_include</code>. Both
5628 * arrays are expected to have a length of CELL_COMMAND_MAX_ + 1. If no
5629 * entry in <code>include_if_non_zero</code> is positive, no string will
5630 * be added to <code>event_parts</code>. */
5631 void
5632 append_cell_stats_by_command(smartlist_t *event_parts, const char *key,
5633 const uint64_t *include_if_non_zero,
5634 const uint64_t *number_to_include)
5636 smartlist_t *key_value_strings = smartlist_new();
5637 int i;
5638 for (i = 0; i <= CELL_COMMAND_MAX_; i++) {
5639 if (include_if_non_zero[i] > 0) {
5640 smartlist_add_asprintf(key_value_strings, "%s:"U64_FORMAT,
5641 cell_command_to_string(i),
5642 U64_PRINTF_ARG(number_to_include[i]));
5645 if (smartlist_len(key_value_strings) > 0) {
5646 char *joined = smartlist_join_strings(key_value_strings, ",", 0, NULL);
5647 smartlist_add_asprintf(event_parts, "%s=%s", key, joined);
5648 SMARTLIST_FOREACH(key_value_strings, char *, cp, tor_free(cp));
5649 tor_free(joined);
5651 smartlist_free(key_value_strings);
5654 /** Helper: format <b>cell_stats</b> for <b>circ</b> for inclusion in a
5655 * CELL_STATS event and write result string to <b>event_string</b>. */
5656 void
5657 format_cell_stats(char **event_string, circuit_t *circ,
5658 cell_stats_t *cell_stats)
5660 smartlist_t *event_parts = smartlist_new();
5661 if (CIRCUIT_IS_ORIGIN(circ)) {
5662 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
5663 smartlist_add_asprintf(event_parts, "ID=%lu",
5664 (unsigned long)ocirc->global_identifier);
5665 } else if (TO_OR_CIRCUIT(circ)->p_chan) {
5666 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
5667 smartlist_add_asprintf(event_parts, "InboundQueue=%lu",
5668 (unsigned long)or_circ->p_circ_id);
5669 smartlist_add_asprintf(event_parts, "InboundConn="U64_FORMAT,
5670 U64_PRINTF_ARG(or_circ->p_chan->global_identifier));
5671 append_cell_stats_by_command(event_parts, "InboundAdded",
5672 cell_stats->added_cells_appward,
5673 cell_stats->added_cells_appward);
5674 append_cell_stats_by_command(event_parts, "InboundRemoved",
5675 cell_stats->removed_cells_appward,
5676 cell_stats->removed_cells_appward);
5677 append_cell_stats_by_command(event_parts, "InboundTime",
5678 cell_stats->removed_cells_appward,
5679 cell_stats->total_time_appward);
5681 if (circ->n_chan) {
5682 smartlist_add_asprintf(event_parts, "OutboundQueue=%lu",
5683 (unsigned long)circ->n_circ_id);
5684 smartlist_add_asprintf(event_parts, "OutboundConn="U64_FORMAT,
5685 U64_PRINTF_ARG(circ->n_chan->global_identifier));
5686 append_cell_stats_by_command(event_parts, "OutboundAdded",
5687 cell_stats->added_cells_exitward,
5688 cell_stats->added_cells_exitward);
5689 append_cell_stats_by_command(event_parts, "OutboundRemoved",
5690 cell_stats->removed_cells_exitward,
5691 cell_stats->removed_cells_exitward);
5692 append_cell_stats_by_command(event_parts, "OutboundTime",
5693 cell_stats->removed_cells_exitward,
5694 cell_stats->total_time_exitward);
5696 *event_string = smartlist_join_strings(event_parts, " ", 0, NULL);
5697 SMARTLIST_FOREACH(event_parts, char *, cp, tor_free(cp));
5698 smartlist_free(event_parts);
5701 /** A second or more has elapsed: tell any interested control connection
5702 * how many cells have been processed for a given circuit. */
5704 control_event_circuit_cell_stats(void)
5706 cell_stats_t *cell_stats;
5707 char *event_string;
5708 if (!get_options()->TestingEnableCellStatsEvent ||
5709 !EVENT_IS_INTERESTING(EVENT_CELL_STATS))
5710 return 0;
5711 cell_stats = tor_malloc(sizeof(cell_stats_t));;
5712 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
5713 if (!circ->testing_cell_stats)
5714 continue;
5715 sum_up_cell_stats_by_command(circ, cell_stats);
5716 format_cell_stats(&event_string, circ, cell_stats);
5717 send_control_event(EVENT_CELL_STATS,
5718 "650 CELL_STATS %s\r\n", event_string);
5719 tor_free(event_string);
5721 SMARTLIST_FOREACH_END(circ);
5722 tor_free(cell_stats);
5723 return 0;
5726 /** Tokens in <b>bucket</b> have been refilled: the read bucket was empty
5727 * for <b>read_empty_time</b> millis, the write bucket was empty for
5728 * <b>write_empty_time</b> millis, and buckets were last refilled
5729 * <b>milliseconds_elapsed</b> millis ago. Only emit TB_EMPTY event if
5730 * either read or write bucket have been empty before. */
5732 control_event_tb_empty(const char *bucket, uint32_t read_empty_time,
5733 uint32_t write_empty_time,
5734 int milliseconds_elapsed)
5736 if (get_options()->TestingEnableTbEmptyEvent &&
5737 EVENT_IS_INTERESTING(EVENT_TB_EMPTY) &&
5738 (read_empty_time > 0 || write_empty_time > 0)) {
5739 send_control_event(EVENT_TB_EMPTY,
5740 "650 TB_EMPTY %s READ=%d WRITTEN=%d "
5741 "LAST=%d\r\n",
5742 bucket, read_empty_time, write_empty_time,
5743 milliseconds_elapsed);
5745 return 0;
5748 /* about 5 minutes worth. */
5749 #define N_BW_EVENTS_TO_CACHE 300
5750 /* Index into cached_bw_events to next write. */
5751 static int next_measurement_idx = 0;
5752 /* number of entries set in n_measurements */
5753 static int n_measurements = 0;
5754 static struct cached_bw_event_s {
5755 uint32_t n_read;
5756 uint32_t n_written;
5757 } cached_bw_events[N_BW_EVENTS_TO_CACHE];
5759 /** A second or more has elapsed: tell any interested control
5760 * connections how much bandwidth we used. */
5762 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
5764 cached_bw_events[next_measurement_idx].n_read = n_read;
5765 cached_bw_events[next_measurement_idx].n_written = n_written;
5766 if (++next_measurement_idx == N_BW_EVENTS_TO_CACHE)
5767 next_measurement_idx = 0;
5768 if (n_measurements < N_BW_EVENTS_TO_CACHE)
5769 ++n_measurements;
5771 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
5772 send_control_event(EVENT_BANDWIDTH_USED,
5773 "650 BW %lu %lu\r\n",
5774 (unsigned long)n_read,
5775 (unsigned long)n_written);
5778 return 0;
5781 STATIC char *
5782 get_bw_samples(void)
5784 int i;
5785 int idx = (next_measurement_idx + N_BW_EVENTS_TO_CACHE - n_measurements)
5786 % N_BW_EVENTS_TO_CACHE;
5787 tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
5789 smartlist_t *elements = smartlist_new();
5791 for (i = 0; i < n_measurements; ++i) {
5792 tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
5793 const struct cached_bw_event_s *bwe = &cached_bw_events[idx];
5795 smartlist_add_asprintf(elements, "%u,%u",
5796 (unsigned)bwe->n_read,
5797 (unsigned)bwe->n_written);
5799 idx = (idx + 1) % N_BW_EVENTS_TO_CACHE;
5802 char *result = smartlist_join_strings(elements, " ", 0, NULL);
5804 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
5805 smartlist_free(elements);
5807 return result;
5810 /** Called when we are sending a log message to the controllers: suspend
5811 * sending further log messages to the controllers until we're done. Used by
5812 * CONN_LOG_PROTECT. */
5813 void
5814 disable_control_logging(void)
5816 ++disable_log_messages;
5819 /** We're done sending a log message to the controllers: re-enable controller
5820 * logging. Used by CONN_LOG_PROTECT. */
5821 void
5822 enable_control_logging(void)
5824 if (--disable_log_messages < 0)
5825 tor_assert(0);
5828 /** We got a log message: tell any interested control connections. */
5829 void
5830 control_event_logmsg(int severity, uint32_t domain, const char *msg)
5832 int event;
5834 /* Don't even think of trying to add stuff to a buffer from a cpuworker
5835 * thread. */
5836 if (! in_main_thread())
5837 return;
5839 if (disable_log_messages)
5840 return;
5842 if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
5843 severity <= LOG_NOTICE) {
5844 char *esc = esc_for_log(msg);
5845 ++disable_log_messages;
5846 control_event_general_status(severity, "BUG REASON=%s", esc);
5847 --disable_log_messages;
5848 tor_free(esc);
5851 event = log_severity_to_event(severity);
5852 if (event >= 0 && EVENT_IS_INTERESTING(event)) {
5853 char *b = NULL;
5854 const char *s;
5855 if (strchr(msg, '\n')) {
5856 char *cp;
5857 b = tor_strdup(msg);
5858 for (cp = b; *cp; ++cp)
5859 if (*cp == '\r' || *cp == '\n')
5860 *cp = ' ';
5862 switch (severity) {
5863 case LOG_DEBUG: s = "DEBUG"; break;
5864 case LOG_INFO: s = "INFO"; break;
5865 case LOG_NOTICE: s = "NOTICE"; break;
5866 case LOG_WARN: s = "WARN"; break;
5867 case LOG_ERR: s = "ERR"; break;
5868 default: s = "UnknownLogSeverity"; break;
5870 ++disable_log_messages;
5871 send_control_event(event, "650 %s %s\r\n", s, b?b:msg);
5872 if (severity == LOG_ERR) {
5873 /* Force a flush, since we may be about to die horribly */
5874 queued_events_flush_all(1);
5876 --disable_log_messages;
5877 tor_free(b);
5881 /** Called whenever we receive new router descriptors: tell any
5882 * interested control connections. <b>routers</b> is a list of
5883 * routerinfo_t's.
5886 control_event_descriptors_changed(smartlist_t *routers)
5888 char *msg;
5890 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
5891 return 0;
5894 smartlist_t *names = smartlist_new();
5895 char *ids;
5896 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
5897 char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
5898 router_get_verbose_nickname(b, ri);
5899 smartlist_add(names, b);
5901 ids = smartlist_join_strings(names, " ", 0, NULL);
5902 tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
5903 send_control_event_string(EVENT_NEW_DESC, msg);
5904 tor_free(ids);
5905 tor_free(msg);
5906 SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
5907 smartlist_free(names);
5909 return 0;
5912 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
5913 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
5914 * <b>error</b> is non-NULL, it is an error code describing the failure
5915 * mode of the mapping.
5918 control_event_address_mapped(const char *from, const char *to, time_t expires,
5919 const char *error, const int cached)
5921 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
5922 return 0;
5924 if (expires < 3 || expires == TIME_MAX)
5925 send_control_event(EVENT_ADDRMAP,
5926 "650 ADDRMAP %s %s NEVER %s%s"
5927 "CACHED=\"%s\"\r\n",
5928 from, to, error?error:"", error?" ":"",
5929 cached?"YES":"NO");
5930 else {
5931 char buf[ISO_TIME_LEN+1];
5932 char buf2[ISO_TIME_LEN+1];
5933 format_local_iso_time(buf,expires);
5934 format_iso_time(buf2,expires);
5935 send_control_event(EVENT_ADDRMAP,
5936 "650 ADDRMAP %s %s \"%s\""
5937 " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
5938 from, to, buf,
5939 error?error:"", error?" ":"",
5940 buf2, cached?"YES":"NO");
5943 return 0;
5946 /** The authoritative dirserver has received a new descriptor that
5947 * has passed basic syntax checks and is properly self-signed.
5949 * Notify any interested party of the new descriptor and what has
5950 * been done with it, and also optionally give an explanation/reason. */
5952 control_event_or_authdir_new_descriptor(const char *action,
5953 const char *desc, size_t desclen,
5954 const char *msg)
5956 char firstline[1024];
5957 char *buf;
5958 size_t totallen;
5959 char *esc = NULL;
5960 size_t esclen;
5962 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
5963 return 0;
5965 tor_snprintf(firstline, sizeof(firstline),
5966 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
5967 action,
5968 msg ? msg : "");
5970 /* Escape the server descriptor properly */
5971 esclen = write_escaped_data(desc, desclen, &esc);
5973 totallen = strlen(firstline) + esclen + 1;
5974 buf = tor_malloc(totallen);
5975 strlcpy(buf, firstline, totallen);
5976 strlcpy(buf+strlen(firstline), esc, totallen);
5977 send_control_event_string(EVENT_AUTHDIR_NEWDESCS,
5978 buf);
5979 send_control_event_string(EVENT_AUTHDIR_NEWDESCS,
5980 "650 OK\r\n");
5981 tor_free(esc);
5982 tor_free(buf);
5984 return 0;
5987 /** Cached liveness for network liveness events and GETINFO
5990 static int network_is_live = 0;
5992 static int
5993 get_cached_network_liveness(void)
5995 return network_is_live;
5998 static void
5999 set_cached_network_liveness(int liveness)
6001 network_is_live = liveness;
6004 /** The network liveness has changed; this is called from circuitstats.c
6005 * whenever we receive a cell, or when timeout expires and we assume the
6006 * network is down. */
6008 control_event_network_liveness_update(int liveness)
6010 if (liveness > 0) {
6011 if (get_cached_network_liveness() <= 0) {
6012 /* Update cached liveness */
6013 set_cached_network_liveness(1);
6014 log_debug(LD_CONTROL, "Sending NETWORK_LIVENESS UP");
6015 send_control_event_string(EVENT_NETWORK_LIVENESS,
6016 "650 NETWORK_LIVENESS UP\r\n");
6018 /* else was already live, no-op */
6019 } else {
6020 if (get_cached_network_liveness() > 0) {
6021 /* Update cached liveness */
6022 set_cached_network_liveness(0);
6023 log_debug(LD_CONTROL, "Sending NETWORK_LIVENESS DOWN");
6024 send_control_event_string(EVENT_NETWORK_LIVENESS,
6025 "650 NETWORK_LIVENESS DOWN\r\n");
6027 /* else was already dead, no-op */
6030 return 0;
6033 /** Helper function for NS-style events. Constructs and sends an event
6034 * of type <b>event</b> with string <b>event_string</b> out of the set of
6035 * networkstatuses <b>statuses</b>. Currently it is used for NS events
6036 * and NEWCONSENSUS events. */
6037 static int
6038 control_event_networkstatus_changed_helper(smartlist_t *statuses,
6039 uint16_t event,
6040 const char *event_string)
6042 smartlist_t *strs;
6043 char *s, *esc = NULL;
6044 if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
6045 return 0;
6047 strs = smartlist_new();
6048 smartlist_add(strs, tor_strdup("650+"));
6049 smartlist_add(strs, tor_strdup(event_string));
6050 smartlist_add(strs, tor_strdup("\r\n"));
6051 SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
6053 s = networkstatus_getinfo_helper_single(rs);
6054 if (!s) continue;
6055 smartlist_add(strs, s);
6058 s = smartlist_join_strings(strs, "", 0, NULL);
6059 write_escaped_data(s, strlen(s), &esc);
6060 SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
6061 smartlist_free(strs);
6062 tor_free(s);
6063 send_control_event_string(event, esc);
6064 send_control_event_string(event,
6065 "650 OK\r\n");
6067 tor_free(esc);
6068 return 0;
6071 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
6072 * an NS event to any controller that cares. */
6074 control_event_networkstatus_changed(smartlist_t *statuses)
6076 return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
6079 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
6080 * event consisting of an NS-style line for each relay in the consensus. */
6082 control_event_newconsensus(const networkstatus_t *consensus)
6084 if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
6085 return 0;
6086 return control_event_networkstatus_changed_helper(
6087 consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
6090 /** Called when we compute a new circuitbuildtimeout */
6092 control_event_buildtimeout_set(buildtimeout_set_event_t type,
6093 const char *args)
6095 const char *type_string = NULL;
6097 if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
6098 return 0;
6100 switch (type) {
6101 case BUILDTIMEOUT_SET_EVENT_COMPUTED:
6102 type_string = "COMPUTED";
6103 break;
6104 case BUILDTIMEOUT_SET_EVENT_RESET:
6105 type_string = "RESET";
6106 break;
6107 case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
6108 type_string = "SUSPENDED";
6109 break;
6110 case BUILDTIMEOUT_SET_EVENT_DISCARD:
6111 type_string = "DISCARD";
6112 break;
6113 case BUILDTIMEOUT_SET_EVENT_RESUME:
6114 type_string = "RESUME";
6115 break;
6116 default:
6117 type_string = "UNKNOWN";
6118 break;
6121 send_control_event(EVENT_BUILDTIMEOUT_SET,
6122 "650 BUILDTIMEOUT_SET %s %s\r\n",
6123 type_string, args);
6125 return 0;
6128 /** Called when a signal has been processed from signal_callback */
6130 control_event_signal(uintptr_t signal_num)
6132 const char *signal_string = NULL;
6134 if (!control_event_is_interesting(EVENT_GOT_SIGNAL))
6135 return 0;
6137 switch (signal_num) {
6138 case SIGHUP:
6139 signal_string = "RELOAD";
6140 break;
6141 case SIGUSR1:
6142 signal_string = "DUMP";
6143 break;
6144 case SIGUSR2:
6145 signal_string = "DEBUG";
6146 break;
6147 case SIGNEWNYM:
6148 signal_string = "NEWNYM";
6149 break;
6150 case SIGCLEARDNSCACHE:
6151 signal_string = "CLEARDNSCACHE";
6152 break;
6153 case SIGHEARTBEAT:
6154 signal_string = "HEARTBEAT";
6155 break;
6156 default:
6157 log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
6158 (unsigned long)signal_num);
6159 return -1;
6162 send_control_event(EVENT_GOT_SIGNAL, "650 SIGNAL %s\r\n",
6163 signal_string);
6164 return 0;
6167 /** Called when a single local_routerstatus_t has changed: Sends an NS event
6168 * to any controller that cares. */
6170 control_event_networkstatus_changed_single(const routerstatus_t *rs)
6172 smartlist_t *statuses;
6173 int r;
6175 if (!EVENT_IS_INTERESTING(EVENT_NS))
6176 return 0;
6178 statuses = smartlist_new();
6179 smartlist_add(statuses, (void*)rs);
6180 r = control_event_networkstatus_changed(statuses);
6181 smartlist_free(statuses);
6182 return r;
6185 /** Our own router descriptor has changed; tell any controllers that care.
6188 control_event_my_descriptor_changed(void)
6190 send_control_event(EVENT_DESCCHANGED, "650 DESCCHANGED\r\n");
6191 return 0;
6194 /** Helper: sends a status event where <b>type</b> is one of
6195 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
6196 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
6197 * string corresponding to <b>args</b>. */
6198 static int
6199 control_event_status(int type, int severity, const char *format, va_list args)
6201 char *user_buf = NULL;
6202 char format_buf[160];
6203 const char *status, *sev;
6205 switch (type) {
6206 case EVENT_STATUS_GENERAL:
6207 status = "STATUS_GENERAL";
6208 break;
6209 case EVENT_STATUS_CLIENT:
6210 status = "STATUS_CLIENT";
6211 break;
6212 case EVENT_STATUS_SERVER:
6213 status = "STATUS_SERVER";
6214 break;
6215 default:
6216 log_warn(LD_BUG, "Unrecognized status type %d", type);
6217 return -1;
6219 switch (severity) {
6220 case LOG_NOTICE:
6221 sev = "NOTICE";
6222 break;
6223 case LOG_WARN:
6224 sev = "WARN";
6225 break;
6226 case LOG_ERR:
6227 sev = "ERR";
6228 break;
6229 default:
6230 log_warn(LD_BUG, "Unrecognized status severity %d", severity);
6231 return -1;
6233 if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
6234 status, sev)<0) {
6235 log_warn(LD_BUG, "Format string too long.");
6236 return -1;
6238 tor_vasprintf(&user_buf, format, args);
6240 send_control_event(type, "%s %s\r\n", format_buf, user_buf);
6241 tor_free(user_buf);
6242 return 0;
6245 #define CONTROL_EVENT_STATUS_BODY(event, sev) \
6246 int r; \
6247 do { \
6248 va_list ap; \
6249 if (!EVENT_IS_INTERESTING(event)) \
6250 return 0; \
6252 va_start(ap, format); \
6253 r = control_event_status((event), (sev), format, ap); \
6254 va_end(ap); \
6255 } while (0)
6257 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
6258 * by formatting the arguments using the printf-style <b>format</b>. */
6260 control_event_general_status(int severity, const char *format, ...)
6262 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, severity);
6263 return r;
6266 /** Format and send an EVENT_STATUS_GENERAL LOG_ERR event, and flush it to the
6267 * controller(s) immediately. */
6269 control_event_general_error(const char *format, ...)
6271 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, LOG_ERR);
6272 /* Force a flush, since we may be about to die horribly */
6273 queued_events_flush_all(1);
6274 return r;
6277 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
6278 * by formatting the arguments using the printf-style <b>format</b>. */
6280 control_event_client_status(int severity, const char *format, ...)
6282 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, severity);
6283 return r;
6286 /** Format and send an EVENT_STATUS_CLIENT LOG_ERR event, and flush it to the
6287 * controller(s) immediately. */
6289 control_event_client_error(const char *format, ...)
6291 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, LOG_ERR);
6292 /* Force a flush, since we may be about to die horribly */
6293 queued_events_flush_all(1);
6294 return r;
6297 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
6298 * by formatting the arguments using the printf-style <b>format</b>. */
6300 control_event_server_status(int severity, const char *format, ...)
6302 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, severity);
6303 return r;
6306 /** Format and send an EVENT_STATUS_SERVER LOG_ERR event, and flush it to the
6307 * controller(s) immediately. */
6309 control_event_server_error(const char *format, ...)
6311 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, LOG_ERR);
6312 /* Force a flush, since we may be about to die horribly */
6313 queued_events_flush_all(1);
6314 return r;
6317 /** Called when the status of an entry guard with the given <b>nickname</b>
6318 * and identity <b>digest</b> has changed to <b>status</b>: tells any
6319 * controllers that care. */
6321 control_event_guard(const char *nickname, const char *digest,
6322 const char *status)
6324 char hbuf[HEX_DIGEST_LEN+1];
6325 base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
6326 if (!EVENT_IS_INTERESTING(EVENT_GUARD))
6327 return 0;
6330 char buf[MAX_VERBOSE_NICKNAME_LEN+1];
6331 const node_t *node = node_get_by_id(digest);
6332 if (node) {
6333 node_get_verbose_nickname(node, buf);
6334 } else {
6335 tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
6337 send_control_event(EVENT_GUARD,
6338 "650 GUARD ENTRY %s %s\r\n", buf, status);
6340 return 0;
6343 /** Called when a configuration option changes. This is generally triggered
6344 * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
6345 * a smartlist_t containing (key, value, ...) pairs in sequence.
6346 * <b>value</b> can be NULL. */
6348 control_event_conf_changed(const smartlist_t *elements)
6350 int i;
6351 char *result;
6352 smartlist_t *lines;
6353 if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) ||
6354 smartlist_len(elements) == 0) {
6355 return 0;
6357 lines = smartlist_new();
6358 for (i = 0; i < smartlist_len(elements); i += 2) {
6359 char *k = smartlist_get(elements, i);
6360 char *v = smartlist_get(elements, i+1);
6361 if (v == NULL) {
6362 smartlist_add_asprintf(lines, "650-%s", k);
6363 } else {
6364 smartlist_add_asprintf(lines, "650-%s=%s", k, v);
6367 result = smartlist_join_strings(lines, "\r\n", 0, NULL);
6368 send_control_event(EVENT_CONF_CHANGED,
6369 "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
6370 tor_free(result);
6371 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
6372 smartlist_free(lines);
6373 return 0;
6376 /** Helper: Return a newly allocated string containing a path to the
6377 * file where we store our authentication cookie. */
6378 char *
6379 get_controller_cookie_file_name(void)
6381 const or_options_t *options = get_options();
6382 if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
6383 return tor_strdup(options->CookieAuthFile);
6384 } else {
6385 return get_datadir_fname("control_auth_cookie");
6389 /* Initialize the cookie-based authentication system of the
6390 * ControlPort. If <b>enabled</b> is 0, then disable the cookie
6391 * authentication system. */
6393 init_control_cookie_authentication(int enabled)
6395 char *fname = NULL;
6396 int retval;
6398 if (!enabled) {
6399 authentication_cookie_is_set = 0;
6400 return 0;
6403 fname = get_controller_cookie_file_name();
6404 retval = init_cookie_authentication(fname, "", /* no header */
6405 AUTHENTICATION_COOKIE_LEN,
6406 get_options()->CookieAuthFileGroupReadable,
6407 &authentication_cookie,
6408 &authentication_cookie_is_set);
6409 tor_free(fname);
6410 return retval;
6413 /** A copy of the process specifier of Tor's owning controller, or
6414 * NULL if this Tor instance is not currently owned by a process. */
6415 static char *owning_controller_process_spec = NULL;
6417 /** A process-termination monitor for Tor's owning controller, or NULL
6418 * if this Tor instance is not currently owned by a process. */
6419 static tor_process_monitor_t *owning_controller_process_monitor = NULL;
6421 /** Process-termination monitor callback for Tor's owning controller
6422 * process. */
6423 static void
6424 owning_controller_procmon_cb(void *unused)
6426 (void)unused;
6428 lost_owning_controller("process", "vanished");
6431 /** Set <b>process_spec</b> as Tor's owning controller process.
6432 * Exit on failure. */
6433 void
6434 monitor_owning_controller_process(const char *process_spec)
6436 const char *msg;
6438 tor_assert((owning_controller_process_spec == NULL) ==
6439 (owning_controller_process_monitor == NULL));
6441 if (owning_controller_process_spec != NULL) {
6442 if ((process_spec != NULL) && !strcmp(process_spec,
6443 owning_controller_process_spec)) {
6444 /* Same process -- return now, instead of disposing of and
6445 * recreating the process-termination monitor. */
6446 return;
6449 /* We are currently owned by a process, and we should no longer be
6450 * owned by it. Free the process-termination monitor. */
6451 tor_process_monitor_free(owning_controller_process_monitor);
6452 owning_controller_process_monitor = NULL;
6454 tor_free(owning_controller_process_spec);
6455 owning_controller_process_spec = NULL;
6458 tor_assert((owning_controller_process_spec == NULL) &&
6459 (owning_controller_process_monitor == NULL));
6461 if (process_spec == NULL)
6462 return;
6464 owning_controller_process_spec = tor_strdup(process_spec);
6465 owning_controller_process_monitor =
6466 tor_process_monitor_new(tor_libevent_get_base(),
6467 owning_controller_process_spec,
6468 LD_CONTROL,
6469 owning_controller_procmon_cb, NULL,
6470 &msg);
6472 if (owning_controller_process_monitor == NULL) {
6473 log_err(LD_BUG, "Couldn't create process-termination monitor for "
6474 "owning controller: %s. Exiting.",
6475 msg);
6476 owning_controller_process_spec = NULL;
6477 tor_cleanup();
6478 exit(0);
6482 /** Convert the name of a bootstrapping phase <b>s</b> into strings
6483 * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
6484 static int
6485 bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
6486 const char **summary)
6488 switch (s) {
6489 case BOOTSTRAP_STATUS_UNDEF:
6490 *tag = "undef";
6491 *summary = "Undefined";
6492 break;
6493 case BOOTSTRAP_STATUS_STARTING:
6494 *tag = "starting";
6495 *summary = "Starting";
6496 break;
6497 case BOOTSTRAP_STATUS_CONN_DIR:
6498 *tag = "conn_dir";
6499 *summary = "Connecting to directory server";
6500 break;
6501 case BOOTSTRAP_STATUS_HANDSHAKE:
6502 *tag = "status_handshake";
6503 *summary = "Finishing handshake";
6504 break;
6505 case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
6506 *tag = "handshake_dir";
6507 *summary = "Finishing handshake with directory server";
6508 break;
6509 case BOOTSTRAP_STATUS_ONEHOP_CREATE:
6510 *tag = "onehop_create";
6511 *summary = "Establishing an encrypted directory connection";
6512 break;
6513 case BOOTSTRAP_STATUS_REQUESTING_STATUS:
6514 *tag = "requesting_status";
6515 *summary = "Asking for networkstatus consensus";
6516 break;
6517 case BOOTSTRAP_STATUS_LOADING_STATUS:
6518 *tag = "loading_status";
6519 *summary = "Loading networkstatus consensus";
6520 break;
6521 case BOOTSTRAP_STATUS_LOADING_KEYS:
6522 *tag = "loading_keys";
6523 *summary = "Loading authority key certs";
6524 break;
6525 case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
6526 *tag = "requesting_descriptors";
6527 /* XXXX this appears to incorrectly report internal on most loads */
6528 *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
6529 "Asking for relay descriptors for internal paths" :
6530 "Asking for relay descriptors";
6531 break;
6532 /* If we're sure there are no exits in the consensus,
6533 * inform the controller by adding "internal"
6534 * to the status summaries.
6535 * (We only check this while loading descriptors,
6536 * so we may not know in the earlier stages.)
6537 * But if there are exits, we can't be sure whether
6538 * we're creating internal or exit paths/circuits.
6539 * XXXX Or should be use different tags or statuses
6540 * for internal and exit/all? */
6541 case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
6542 *tag = "loading_descriptors";
6543 *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
6544 "Loading relay descriptors for internal paths" :
6545 "Loading relay descriptors";
6546 break;
6547 case BOOTSTRAP_STATUS_CONN_OR:
6548 *tag = "conn_or";
6549 *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
6550 "Connecting to the Tor network internally" :
6551 "Connecting to the Tor network";
6552 break;
6553 case BOOTSTRAP_STATUS_HANDSHAKE_OR:
6554 *tag = "handshake_or";
6555 *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
6556 "Finishing handshake with first hop of internal circuit" :
6557 "Finishing handshake with first hop";
6558 break;
6559 case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
6560 *tag = "circuit_create";
6561 *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
6562 "Establishing an internal Tor circuit" :
6563 "Establishing a Tor circuit";
6564 break;
6565 case BOOTSTRAP_STATUS_DONE:
6566 *tag = "done";
6567 *summary = "Done";
6568 break;
6569 default:
6570 // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
6571 *tag = *summary = "unknown";
6572 return -1;
6574 return 0;
6577 /** What percentage through the bootstrap process are we? We remember
6578 * this so we can avoid sending redundant bootstrap status events, and
6579 * so we can guess context for the bootstrap messages which are
6580 * ambiguous. It starts at 'undef', but gets set to 'starting' while
6581 * Tor initializes. */
6582 static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
6584 /** As bootstrap_percent, but holds the bootstrapping level at which we last
6585 * logged a NOTICE-level message. We use this, plus BOOTSTRAP_PCT_INCREMENT,
6586 * to avoid flooding the log with a new message every time we get a few more
6587 * microdescriptors */
6588 static int notice_bootstrap_percent = 0;
6590 /** How many problems have we had getting to the next bootstrapping phase?
6591 * These include failure to establish a connection to a Tor relay,
6592 * failures to finish the TLS handshake, failures to validate the
6593 * consensus document, etc. */
6594 static int bootstrap_problems = 0;
6596 /** We only tell the controller once we've hit a threshold of problems
6597 * for the current phase. */
6598 #define BOOTSTRAP_PROBLEM_THRESHOLD 10
6600 /** When our bootstrapping progress level changes, but our bootstrapping
6601 * status has not advanced, we only log at NOTICE when we have made at least
6602 * this much progress.
6604 #define BOOTSTRAP_PCT_INCREMENT 5
6606 /** Called when Tor has made progress at bootstrapping its directory
6607 * information and initial circuits.
6609 * <b>status</b> is the new status, that is, what task we will be doing
6610 * next. <b>progress</b> is zero if we just started this task, else it
6611 * represents progress on the task.
6613 * Return true if we logged a message at level NOTICE, and false otherwise.
6616 control_event_bootstrap(bootstrap_status_t status, int progress)
6618 const char *tag, *summary;
6619 char buf[BOOTSTRAP_MSG_LEN];
6621 if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
6622 return 0; /* already bootstrapped; nothing to be done here. */
6624 /* special case for handshaking status, since our TLS handshaking code
6625 * can't distinguish what the connection is going to be for. */
6626 if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
6627 if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
6628 status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
6629 } else {
6630 status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
6634 if (status > bootstrap_percent ||
6635 (progress && progress > bootstrap_percent)) {
6636 int loglevel = LOG_NOTICE;
6637 bootstrap_status_to_string(status, &tag, &summary);
6639 if (status <= bootstrap_percent &&
6640 (progress < notice_bootstrap_percent + BOOTSTRAP_PCT_INCREMENT)) {
6641 /* We log the message at info if the status hasn't advanced, and if less
6642 * than BOOTSTRAP_PCT_INCREMENT progress has been made.
6644 loglevel = LOG_INFO;
6647 tor_log(loglevel, LD_CONTROL,
6648 "Bootstrapped %d%%: %s", progress ? progress : status, summary);
6649 tor_snprintf(buf, sizeof(buf),
6650 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
6651 progress ? progress : status, tag, summary);
6652 tor_snprintf(last_sent_bootstrap_message,
6653 sizeof(last_sent_bootstrap_message),
6654 "NOTICE %s", buf);
6655 control_event_client_status(LOG_NOTICE, "%s", buf);
6656 if (status > bootstrap_percent) {
6657 bootstrap_percent = status; /* new milestone reached */
6659 if (progress > bootstrap_percent) {
6660 /* incremental progress within a milestone */
6661 bootstrap_percent = progress;
6662 bootstrap_problems = 0; /* Progress! Reset our problem counter. */
6664 if (loglevel == LOG_NOTICE &&
6665 bootstrap_percent > notice_bootstrap_percent) {
6666 /* Remember that we gave a notice at this level. */
6667 notice_bootstrap_percent = bootstrap_percent;
6669 return loglevel == LOG_NOTICE;
6672 return 0;
6675 /** Called when Tor has failed to make bootstrapping progress in a way
6676 * that indicates a problem. <b>warn</b> gives a hint as to why, and
6677 * <b>reason</b> provides an "or_conn_end_reason" tag. <b>or_conn</b>
6678 * is the connection that caused this problem.
6680 MOCK_IMPL(void,
6681 control_event_bootstrap_problem, (const char *warn, int reason,
6682 or_connection_t *or_conn))
6684 int status = bootstrap_percent;
6685 const char *tag = "", *summary = "";
6686 char buf[BOOTSTRAP_MSG_LEN];
6687 const char *recommendation = "ignore";
6688 int severity;
6690 /* bootstrap_percent must not be in "undefined" state here. */
6691 tor_assert(status >= 0);
6693 if (or_conn->have_noted_bootstrap_problem)
6694 return;
6696 or_conn->have_noted_bootstrap_problem = 1;
6698 if (bootstrap_percent == 100)
6699 return; /* already bootstrapped; nothing to be done here. */
6701 bootstrap_problems++;
6703 if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
6704 recommendation = "warn";
6706 if (reason == END_OR_CONN_REASON_NO_ROUTE)
6707 recommendation = "warn";
6709 /* If we are using bridges and all our OR connections are now
6710 closed, it means that we totally failed to connect to our
6711 bridges. Throw a warning. */
6712 if (get_options()->UseBridges && !any_other_active_or_conns(or_conn))
6713 recommendation = "warn";
6715 if (we_are_hibernating())
6716 recommendation = "ignore";
6718 while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
6719 status--; /* find a recognized status string based on current progress */
6720 status = bootstrap_percent; /* set status back to the actual number */
6722 severity = !strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO;
6724 log_fn(severity,
6725 LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
6726 "count %d; recommendation %s; host %s at %s:%d)",
6727 status, summary, warn,
6728 orconn_end_reason_to_control_string(reason),
6729 bootstrap_problems, recommendation,
6730 hex_str(or_conn->identity_digest, DIGEST_LEN),
6731 or_conn->base_.address,
6732 or_conn->base_.port);
6734 connection_or_report_broken_states(severity, LD_HANDSHAKE);
6736 tor_snprintf(buf, sizeof(buf),
6737 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
6738 "COUNT=%d RECOMMENDATION=%s HOSTID=\"%s\" HOSTADDR=\"%s:%d\"",
6739 bootstrap_percent, tag, summary, warn,
6740 orconn_end_reason_to_control_string(reason), bootstrap_problems,
6741 recommendation,
6742 hex_str(or_conn->identity_digest, DIGEST_LEN),
6743 or_conn->base_.address,
6744 (int)or_conn->base_.port);
6746 tor_snprintf(last_sent_bootstrap_message,
6747 sizeof(last_sent_bootstrap_message),
6748 "WARN %s", buf);
6749 control_event_client_status(LOG_WARN, "%s", buf);
6752 /** We just generated a new summary of which countries we've seen clients
6753 * from recently. Send a copy to the controller in case it wants to
6754 * display it for the user. */
6755 void
6756 control_event_clients_seen(const char *controller_str)
6758 send_control_event(EVENT_CLIENTS_SEEN,
6759 "650 CLIENTS_SEEN %s\r\n", controller_str);
6762 /** A new pluggable transport called <b>transport_name</b> was
6763 * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
6764 * "server" or "client" depending on the mode of the pluggable
6765 * transport.
6766 * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
6768 void
6769 control_event_transport_launched(const char *mode, const char *transport_name,
6770 tor_addr_t *addr, uint16_t port)
6772 send_control_event(EVENT_TRANSPORT_LAUNCHED,
6773 "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
6774 mode, transport_name, fmt_addr(addr), port);
6777 /** Convert rendezvous auth type to string for HS_DESC control events
6779 const char *
6780 rend_auth_type_to_string(rend_auth_type_t auth_type)
6782 const char *str;
6784 switch (auth_type) {
6785 case REND_NO_AUTH:
6786 str = "NO_AUTH";
6787 break;
6788 case REND_BASIC_AUTH:
6789 str = "BASIC_AUTH";
6790 break;
6791 case REND_STEALTH_AUTH:
6792 str = "STEALTH_AUTH";
6793 break;
6794 default:
6795 str = "UNKNOWN";
6798 return str;
6801 /** Return a longname the node whose identity is <b>id_digest</b>. If
6802 * node_get_by_id() returns NULL, base 16 encoding of <b>id_digest</b> is
6803 * returned instead.
6805 * This function is not thread-safe. Each call to this function invalidates
6806 * previous values returned by this function.
6808 MOCK_IMPL(const char *,
6809 node_describe_longname_by_id,(const char *id_digest))
6811 static char longname[MAX_VERBOSE_NICKNAME_LEN+1];
6812 node_get_verbose_nickname_by_id(id_digest, longname);
6813 return longname;
6816 /** Return either the onion address if the given pointer is a non empty
6817 * string else the unknown string. */
6818 static const char *
6819 rend_hsaddress_str_or_unknown(const char *onion_address)
6821 static const char *str_unknown = "UNKNOWN";
6822 const char *str_ret = str_unknown;
6824 /* No valid pointer, unknown it is. */
6825 if (!onion_address) {
6826 goto end;
6828 /* Empty onion address thus we don't know, unknown it is. */
6829 if (onion_address[0] == '\0') {
6830 goto end;
6832 /* All checks are good so return the given onion address. */
6833 str_ret = onion_address;
6835 end:
6836 return str_ret;
6839 /** send HS_DESC requested event.
6841 * <b>rend_query</b> is used to fetch requested onion address and auth type.
6842 * <b>hs_dir</b> is the description of contacting hs directory.
6843 * <b>desc_id_base32</b> is the ID of requested hs descriptor.
6845 void
6846 control_event_hs_descriptor_requested(const rend_data_t *rend_query,
6847 const char *id_digest,
6848 const char *desc_id_base32)
6850 if (!id_digest || !rend_query || !desc_id_base32) {
6851 log_warn(LD_BUG, "Called with rend_query==%p, "
6852 "id_digest==%p, desc_id_base32==%p",
6853 rend_query, id_digest, desc_id_base32);
6854 return;
6857 send_control_event(EVENT_HS_DESC,
6858 "650 HS_DESC REQUESTED %s %s %s %s\r\n",
6859 rend_hsaddress_str_or_unknown(rend_query->onion_address),
6860 rend_auth_type_to_string(rend_query->auth_type),
6861 node_describe_longname_by_id(id_digest),
6862 desc_id_base32);
6865 /** For an HS descriptor query <b>rend_data</b>, using the
6866 * <b>onion_address</b> and HSDir fingerprint <b>hsdir_fp</b>, find out
6867 * which descriptor ID in the query is the right one.
6869 * Return a pointer of the binary descriptor ID found in the query's object
6870 * or NULL if not found. */
6871 static const char *
6872 get_desc_id_from_query(const rend_data_t *rend_data, const char *hsdir_fp)
6874 int replica;
6875 const char *desc_id = NULL;
6877 /* Possible if the fetch was done using a descriptor ID. This means that
6878 * the HSFETCH command was used. */
6879 if (!tor_digest_is_zero(rend_data->desc_id_fetch)) {
6880 desc_id = rend_data->desc_id_fetch;
6881 goto end;
6884 /* OK, we have an onion address so now let's find which descriptor ID
6885 * is the one associated with the HSDir fingerprint. */
6886 for (replica = 0; replica < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
6887 replica++) {
6888 const char *digest = rend_data->descriptor_id[replica];
6890 SMARTLIST_FOREACH_BEGIN(rend_data->hsdirs_fp, char *, fingerprint) {
6891 if (tor_memcmp(fingerprint, hsdir_fp, DIGEST_LEN) == 0) {
6892 /* Found it! This descriptor ID is the right one. */
6893 desc_id = digest;
6894 goto end;
6896 } SMARTLIST_FOREACH_END(fingerprint);
6899 end:
6900 return desc_id;
6903 /** send HS_DESC CREATED event when a local service generates a descriptor.
6905 * <b>service_id</b> is the descriptor onion address.
6906 * <b>desc_id_base32</b> is the descriptor ID.
6907 * <b>replica</b> is the the descriptor replica number.
6909 void
6910 control_event_hs_descriptor_created(const char *service_id,
6911 const char *desc_id_base32,
6912 int replica)
6914 if (!service_id || !desc_id_base32) {
6915 log_warn(LD_BUG, "Called with service_digest==%p, "
6916 "desc_id_base32==%p", service_id, desc_id_base32);
6917 return;
6920 send_control_event(EVENT_HS_DESC,
6921 "650 HS_DESC CREATED %s UNKNOWN UNKNOWN %s "
6922 "REPLICA=%d\r\n",
6923 service_id,
6924 desc_id_base32,
6925 replica);
6928 /** send HS_DESC upload event.
6930 * <b>service_id</b> is the descriptor onion address.
6931 * <b>hs_dir</b> is the description of contacting hs directory.
6932 * <b>desc_id_base32</b> is the ID of requested hs descriptor.
6934 void
6935 control_event_hs_descriptor_upload(const char *service_id,
6936 const char *id_digest,
6937 const char *desc_id_base32)
6939 if (!service_id || !id_digest || !desc_id_base32) {
6940 log_warn(LD_BUG, "Called with service_digest==%p, "
6941 "desc_id_base32==%p, id_digest==%p", service_id,
6942 desc_id_base32, id_digest);
6943 return;
6946 send_control_event(EVENT_HS_DESC,
6947 "650 HS_DESC UPLOAD %s UNKNOWN %s %s\r\n",
6948 service_id,
6949 node_describe_longname_by_id(id_digest),
6950 desc_id_base32);
6953 /** send HS_DESC event after got response from hs directory.
6955 * NOTE: this is an internal function used by following functions:
6956 * control_event_hs_descriptor_received
6957 * control_event_hs_descriptor_failed
6959 * So do not call this function directly.
6961 void
6962 control_event_hs_descriptor_receive_end(const char *action,
6963 const char *onion_address,
6964 const rend_data_t *rend_data,
6965 const char *id_digest,
6966 const char *reason)
6968 char *desc_id_field = NULL;
6969 char *reason_field = NULL;
6970 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
6971 const char *desc_id = NULL;
6973 if (!action || !id_digest || !rend_data || !onion_address) {
6974 log_warn(LD_BUG, "Called with action==%p, id_digest==%p, "
6975 "rend_data==%p, onion_address==%p", action, id_digest,
6976 rend_data, onion_address);
6977 return;
6980 desc_id = get_desc_id_from_query(rend_data, id_digest);
6981 if (desc_id != NULL) {
6982 /* Set the descriptor ID digest to base32 so we can send it. */
6983 base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_id,
6984 DIGEST_LEN);
6985 /* Extra whitespace is needed before the value. */
6986 tor_asprintf(&desc_id_field, " %s", desc_id_base32);
6989 if (reason) {
6990 tor_asprintf(&reason_field, " REASON=%s", reason);
6993 send_control_event(EVENT_HS_DESC,
6994 "650 HS_DESC %s %s %s %s%s%s\r\n",
6995 action,
6996 rend_hsaddress_str_or_unknown(onion_address),
6997 rend_auth_type_to_string(rend_data->auth_type),
6998 node_describe_longname_by_id(id_digest),
6999 desc_id_field ? desc_id_field : "",
7000 reason_field ? reason_field : "");
7002 tor_free(desc_id_field);
7003 tor_free(reason_field);
7006 /** send HS_DESC event after got response from hs directory.
7008 * NOTE: this is an internal function used by following functions:
7009 * control_event_hs_descriptor_uploaded
7010 * control_event_hs_descriptor_upload_failed
7012 * So do not call this function directly.
7014 void
7015 control_event_hs_descriptor_upload_end(const char *action,
7016 const char *onion_address,
7017 const char *id_digest,
7018 const char *reason)
7020 char *reason_field = NULL;
7022 if (!action || !id_digest) {
7023 log_warn(LD_BUG, "Called with action==%p, id_digest==%p", action,
7024 id_digest);
7025 return;
7028 if (reason) {
7029 tor_asprintf(&reason_field, " REASON=%s", reason);
7032 send_control_event(EVENT_HS_DESC,
7033 "650 HS_DESC %s %s UNKNOWN %s%s\r\n",
7034 action,
7035 rend_hsaddress_str_or_unknown(onion_address),
7036 node_describe_longname_by_id(id_digest),
7037 reason_field ? reason_field : "");
7039 tor_free(reason_field);
7042 /** send HS_DESC RECEIVED event
7044 * called when we successfully received a hidden service descriptor.
7046 void
7047 control_event_hs_descriptor_received(const char *onion_address,
7048 const rend_data_t *rend_data,
7049 const char *id_digest)
7051 if (!rend_data || !id_digest || !onion_address) {
7052 log_warn(LD_BUG, "Called with rend_data==%p, id_digest==%p, "
7053 "onion_address==%p", rend_data, id_digest, onion_address);
7054 return;
7056 control_event_hs_descriptor_receive_end("RECEIVED", onion_address,
7057 rend_data, id_digest, NULL);
7060 /** send HS_DESC UPLOADED event
7062 * called when we successfully uploaded a hidden service descriptor.
7064 void
7065 control_event_hs_descriptor_uploaded(const char *id_digest,
7066 const char *onion_address)
7068 if (!id_digest) {
7069 log_warn(LD_BUG, "Called with id_digest==%p",
7070 id_digest);
7071 return;
7074 control_event_hs_descriptor_upload_end("UPLOADED", onion_address,
7075 id_digest, NULL);
7078 /** Send HS_DESC event to inform controller that query <b>rend_query</b>
7079 * failed to retrieve hidden service descriptor identified by
7080 * <b>id_digest</b>. If <b>reason</b> is not NULL, add it to REASON=
7081 * field.
7083 void
7084 control_event_hs_descriptor_failed(const rend_data_t *rend_data,
7085 const char *id_digest,
7086 const char *reason)
7088 if (!rend_data || !id_digest) {
7089 log_warn(LD_BUG, "Called with rend_data==%p, id_digest==%p",
7090 rend_data, id_digest);
7091 return;
7093 control_event_hs_descriptor_receive_end("FAILED",
7094 rend_data->onion_address,
7095 rend_data, id_digest, reason);
7098 /** send HS_DESC_CONTENT event after completion of a successful fetch from
7099 * hs directory. */
7100 void
7101 control_event_hs_descriptor_content(const char *onion_address,
7102 const char *desc_id,
7103 const char *hsdir_id_digest,
7104 const char *content)
7106 static const char *event_name = "HS_DESC_CONTENT";
7107 char *esc_content = NULL;
7109 if (!onion_address || !desc_id || !hsdir_id_digest) {
7110 log_warn(LD_BUG, "Called with onion_address==%p, desc_id==%p, "
7111 "hsdir_id_digest==%p", onion_address, desc_id, hsdir_id_digest);
7112 return;
7115 if (content == NULL) {
7116 /* Point it to empty content so it can still be escaped. */
7117 content = "";
7119 write_escaped_data(content, strlen(content), &esc_content);
7121 send_control_event(EVENT_HS_DESC_CONTENT,
7122 "650+%s %s %s %s\r\n%s650 OK\r\n",
7123 event_name,
7124 rend_hsaddress_str_or_unknown(onion_address),
7125 desc_id,
7126 node_describe_longname_by_id(hsdir_id_digest),
7127 esc_content);
7128 tor_free(esc_content);
7131 /** Send HS_DESC event to inform controller upload of hidden service
7132 * descriptor identified by <b>id_digest</b> failed. If <b>reason</b>
7133 * is not NULL, add it to REASON= field.
7135 void
7136 control_event_hs_descriptor_upload_failed(const char *id_digest,
7137 const char *onion_address,
7138 const char *reason)
7140 if (!id_digest) {
7141 log_warn(LD_BUG, "Called with id_digest==%p",
7142 id_digest);
7143 return;
7145 control_event_hs_descriptor_upload_end("UPLOAD_FAILED", onion_address,
7146 id_digest, reason);
7149 /** Free any leftover allocated memory of the control.c subsystem. */
7150 void
7151 control_free_all(void)
7153 if (authentication_cookie) /* Free the auth cookie */
7154 tor_free(authentication_cookie);
7155 if (detached_onion_services) { /* Free the detached onion services */
7156 SMARTLIST_FOREACH(detached_onion_services, char *, cp, tor_free(cp));
7157 smartlist_free(detached_onion_services);
7159 if (queued_control_events) {
7160 SMARTLIST_FOREACH(queued_control_events, queued_event_t *, ev,
7161 queued_event_free(ev));
7162 smartlist_free(queued_control_events);
7163 queued_control_events = NULL;
7165 if (flush_queued_events_event) {
7166 tor_event_free(flush_queued_events_event);
7167 flush_queued_events_event = NULL;
7171 #ifdef TOR_UNIT_TESTS
7172 /* For testing: change the value of global_event_mask */
7173 void
7174 control_testing_set_global_event_mask(uint64_t mask)
7176 global_event_mask = mask;
7178 #endif