Add new CIRC_BW event.
[tor.git] / src / or / control.c
blobd3b968cde4ccc48c4cb90703042b9fd14d482faf
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2013, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file control.c
7 * \brief Implementation for Tor's control-socket interface.
8 * See doc/spec/control-spec.txt for full details on protocol.
9 **/
11 #define CONTROL_PRIVATE
13 #include "or.h"
14 #include "addressmap.h"
15 #include "buffers.h"
16 #include "channel.h"
17 #include "channeltls.h"
18 #include "circuitbuild.h"
19 #include "circuitlist.h"
20 #include "circuitstats.h"
21 #include "circuituse.h"
22 #include "config.h"
23 #include "confparse.h"
24 #include "connection.h"
25 #include "connection_edge.h"
26 #include "connection_or.h"
27 #include "control.h"
28 #include "directory.h"
29 #include "dirserv.h"
30 #include "dnsserv.h"
31 #include "entrynodes.h"
32 #include "geoip.h"
33 #include "hibernate.h"
34 #include "main.h"
35 #include "networkstatus.h"
36 #include "nodelist.h"
37 #include "policies.h"
38 #include "reasons.h"
39 #include "rephist.h"
40 #include "router.h"
41 #include "routerlist.h"
42 #include "routerparse.h"
44 #ifndef _WIN32
45 #include <pwd.h>
46 #include <sys/resource.h>
47 #endif
49 extern circuit_t *global_circuitlist; /* from circuitlist.c */
51 #include "procmon.h"
53 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
54 * finished authentication and is accepting commands. */
55 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
57 /* Recognized asynchronous event types. It's okay to expand this list
58 * because it is used both as a list of v0 event types, and as indices
59 * into the bitfield to determine which controllers want which events.
61 #define EVENT_MIN_ 0x0001
62 #define EVENT_CIRCUIT_STATUS 0x0001
63 #define EVENT_STREAM_STATUS 0x0002
64 #define EVENT_OR_CONN_STATUS 0x0003
65 #define EVENT_BANDWIDTH_USED 0x0004
66 #define EVENT_CIRCUIT_STATUS_MINOR 0x0005
67 #define EVENT_NEW_DESC 0x0006
68 #define EVENT_DEBUG_MSG 0x0007
69 #define EVENT_INFO_MSG 0x0008
70 #define EVENT_NOTICE_MSG 0x0009
71 #define EVENT_WARN_MSG 0x000A
72 #define EVENT_ERR_MSG 0x000B
73 #define EVENT_ADDRMAP 0x000C
74 // #define EVENT_AUTHDIR_NEWDESCS 0x000D
75 #define EVENT_DESCCHANGED 0x000E
76 // #define EVENT_NS 0x000F
77 #define EVENT_STATUS_CLIENT 0x0010
78 #define EVENT_STATUS_SERVER 0x0011
79 #define EVENT_STATUS_GENERAL 0x0012
80 #define EVENT_GUARD 0x0013
81 #define EVENT_STREAM_BANDWIDTH_USED 0x0014
82 #define EVENT_CLIENTS_SEEN 0x0015
83 #define EVENT_NEWCONSENSUS 0x0016
84 #define EVENT_BUILDTIMEOUT_SET 0x0017
85 #define EVENT_SIGNAL 0x0018
86 #define EVENT_CONF_CHANGED 0x0019
87 #define EVENT_CONN_BW 0x001A
88 #define EVENT_CELL_STATS 0x001B
89 #define EVENT_TB_EMPTY 0x001C
90 #define EVENT_CIRC_BANDWIDTH_USED 0x001D
91 #define EVENT_MAX_ 0x001D
92 /* If EVENT_MAX_ ever hits 0x0020, we need to make the mask wider. */
94 /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
95 * connection is interested in events of type <b>e</b>. We use this
96 * so that we can decide to skip generating event messages that nobody
97 * has interest in without having to walk over the global connection
98 * list to find out.
99 **/
100 typedef uint32_t event_mask_t;
102 /** An event mask of all the events that any controller is interested in
103 * receiving. */
104 static event_mask_t global_event_mask = 0;
106 /** True iff we have disabled log messages from being sent to the controller */
107 static int disable_log_messages = 0;
109 /** Macro: true if any control connection is interested in events of type
110 * <b>e</b>. */
111 #define EVENT_IS_INTERESTING(e) \
112 (global_event_mask & (1<<(e)))
114 /** If we're using cookie-type authentication, how long should our cookies be?
116 #define AUTHENTICATION_COOKIE_LEN 32
118 /** If true, we've set authentication_cookie to a secret code and
119 * stored it to disk. */
120 static int authentication_cookie_is_set = 0;
121 /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
122 * and which we're using to authenticate controllers. (If the controller can
123 * read it off disk, it has permission to connect.) */
124 static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
126 #define SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT \
127 "Tor safe cookie authentication server-to-controller hash"
128 #define SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT \
129 "Tor safe cookie authentication controller-to-server hash"
130 #define SAFECOOKIE_SERVER_NONCE_LEN DIGEST256_LEN
132 /** A sufficiently large size to record the last bootstrap phase string. */
133 #define BOOTSTRAP_MSG_LEN 1024
135 /** What was the last bootstrap phase message we sent? We keep track
136 * of this so we can respond to getinfo status/bootstrap-phase queries. */
137 static char last_sent_bootstrap_message[BOOTSTRAP_MSG_LEN];
139 /** Flag for event_format_t. Indicates that we should use the one standard
140 format.
142 #define ALL_FORMATS 1
144 /** Bit field of flags to select how to format a controller event. Recognized
145 * flag is ALL_FORMATS. */
146 typedef int event_format_t;
148 static void connection_printf_to_buf(control_connection_t *conn,
149 const char *format, ...)
150 CHECK_PRINTF(2,3);
151 static void send_control_event_impl(uint16_t event, event_format_t which,
152 const char *format, va_list ap)
153 CHECK_PRINTF(3,0);
154 static int control_event_status(int type, int severity, const char *format,
155 va_list args)
156 CHECK_PRINTF(3,0);
158 static void send_control_done(control_connection_t *conn);
159 static void send_control_event(uint16_t event, event_format_t which,
160 const char *format, ...)
161 CHECK_PRINTF(3,4);
162 static int handle_control_setconf(control_connection_t *conn, uint32_t len,
163 char *body);
164 static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
165 char *body);
166 static int handle_control_getconf(control_connection_t *conn, uint32_t len,
167 const char *body);
168 static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
169 const char *body);
170 static int handle_control_setevents(control_connection_t *conn, uint32_t len,
171 const char *body);
172 static int handle_control_authenticate(control_connection_t *conn,
173 uint32_t len,
174 const char *body);
175 static int handle_control_signal(control_connection_t *conn, uint32_t len,
176 const char *body);
177 static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
178 const char *body);
179 static char *list_getinfo_options(void);
180 static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
181 const char *body);
182 static int handle_control_extendcircuit(control_connection_t *conn,
183 uint32_t len,
184 const char *body);
185 static int handle_control_setcircuitpurpose(control_connection_t *conn,
186 uint32_t len, const char *body);
187 static int handle_control_attachstream(control_connection_t *conn,
188 uint32_t len,
189 const char *body);
190 static int handle_control_postdescriptor(control_connection_t *conn,
191 uint32_t len,
192 const char *body);
193 static int handle_control_redirectstream(control_connection_t *conn,
194 uint32_t len,
195 const char *body);
196 static int handle_control_closestream(control_connection_t *conn, uint32_t len,
197 const char *body);
198 static int handle_control_closecircuit(control_connection_t *conn,
199 uint32_t len,
200 const char *body);
201 static int handle_control_resolve(control_connection_t *conn, uint32_t len,
202 const char *body);
203 static int handle_control_usefeature(control_connection_t *conn,
204 uint32_t len,
205 const char *body);
206 static int write_stream_target_to_buf(entry_connection_t *conn, char *buf,
207 size_t len);
208 static void orconn_target_get_name(char *buf, size_t len,
209 or_connection_t *conn);
210 static char *get_cookie_file(void);
212 /** Given a control event code for a message event, return the corresponding
213 * log severity. */
214 static INLINE int
215 event_to_log_severity(int event)
217 switch (event) {
218 case EVENT_DEBUG_MSG: return LOG_DEBUG;
219 case EVENT_INFO_MSG: return LOG_INFO;
220 case EVENT_NOTICE_MSG: return LOG_NOTICE;
221 case EVENT_WARN_MSG: return LOG_WARN;
222 case EVENT_ERR_MSG: return LOG_ERR;
223 default: return -1;
227 /** Given a log severity, return the corresponding control event code. */
228 static INLINE int
229 log_severity_to_event(int severity)
231 switch (severity) {
232 case LOG_DEBUG: return EVENT_DEBUG_MSG;
233 case LOG_INFO: return EVENT_INFO_MSG;
234 case LOG_NOTICE: return EVENT_NOTICE_MSG;
235 case LOG_WARN: return EVENT_WARN_MSG;
236 case LOG_ERR: return EVENT_ERR_MSG;
237 default: return -1;
241 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
242 * connection's event_mask field. */
243 void
244 control_update_global_event_mask(void)
246 smartlist_t *conns = get_connection_array();
247 event_mask_t old_mask, new_mask;
248 old_mask = global_event_mask;
250 global_event_mask = 0;
251 SMARTLIST_FOREACH(conns, connection_t *, _conn,
253 if (_conn->type == CONN_TYPE_CONTROL &&
254 STATE_IS_OPEN(_conn->state)) {
255 control_connection_t *conn = TO_CONTROL_CONN(_conn);
256 global_event_mask |= conn->event_mask;
260 new_mask = global_event_mask;
262 /* Handle the aftermath. Set up the log callback to tell us only what
263 * we want to hear...*/
264 control_adjust_event_log_severity();
266 /* ...then, if we've started logging stream or circ bw, clear the
267 * appropriate fields. */
268 if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
269 (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
270 SMARTLIST_FOREACH(conns, connection_t *, conn,
272 if (conn->type == CONN_TYPE_AP) {
273 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
274 edge_conn->n_written = edge_conn->n_read = 0;
278 if (! (old_mask & EVENT_CIRC_BANDWIDTH_USED) &&
279 (new_mask & EVENT_CIRC_BANDWIDTH_USED)) {
280 circuit_t *circ;
281 origin_circuit_t *ocirc;
282 for (circ = global_circuitlist; circ; circ = circ->next) {
283 if (!CIRCUIT_IS_ORIGIN(circ))
284 continue;
285 ocirc = TO_ORIGIN_CIRCUIT(circ);
286 ocirc->n_written = ocirc->n_read = 0;
291 /** Adjust the log severities that result in control_event_logmsg being called
292 * to match the severity of log messages that any controllers are interested
293 * in. */
294 void
295 control_adjust_event_log_severity(void)
297 int i;
298 int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
300 for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
301 if (EVENT_IS_INTERESTING(i)) {
302 min_log_event = i;
303 break;
306 for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
307 if (EVENT_IS_INTERESTING(i)) {
308 max_log_event = i;
309 break;
312 if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
313 if (min_log_event > EVENT_NOTICE_MSG)
314 min_log_event = EVENT_NOTICE_MSG;
315 if (max_log_event < EVENT_ERR_MSG)
316 max_log_event = EVENT_ERR_MSG;
318 if (min_log_event <= max_log_event)
319 change_callback_log_severity(event_to_log_severity(min_log_event),
320 event_to_log_severity(max_log_event),
321 control_event_logmsg);
322 else
323 change_callback_log_severity(LOG_ERR, LOG_ERR,
324 control_event_logmsg);
327 /** Return true iff the event with code <b>c</b> is being sent to any current
328 * control connection. This is useful if the amount of work needed to prepare
329 * to call the appropriate control_event_...() function is high.
332 control_event_is_interesting(int event)
334 return EVENT_IS_INTERESTING(event);
337 /** Append a NUL-terminated string <b>s</b> to the end of
338 * <b>conn</b>-\>outbuf.
340 static INLINE void
341 connection_write_str_to_buf(const char *s, control_connection_t *conn)
343 size_t len = strlen(s);
344 connection_write_to_buf(s, len, TO_CONN(conn));
347 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
348 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
349 * contents of <b>data</b> into *<b>out</b>, adding a period before any period
350 * that appears at the start of a line, and adding a period-CRLF line at
351 * the end. Replace all LF characters sequences with CRLF. Return the number
352 * of bytes in *<b>out</b>.
354 /* static */ size_t
355 write_escaped_data(const char *data, size_t len, char **out)
357 size_t sz_out = len+8;
358 char *outp;
359 const char *start = data, *end;
360 int i;
361 int start_of_line;
362 for (i=0; i<(int)len; ++i) {
363 if (data[i]== '\n')
364 sz_out += 2; /* Maybe add a CR; maybe add a dot. */
366 *out = outp = tor_malloc(sz_out+1);
367 end = data+len;
368 start_of_line = 1;
369 while (data < end) {
370 if (*data == '\n') {
371 if (data > start && data[-1] != '\r')
372 *outp++ = '\r';
373 start_of_line = 1;
374 } else if (*data == '.') {
375 if (start_of_line) {
376 start_of_line = 0;
377 *outp++ = '.';
379 } else {
380 start_of_line = 0;
382 *outp++ = *data++;
384 if (outp < *out+2 || fast_memcmp(outp-2, "\r\n", 2)) {
385 *outp++ = '\r';
386 *outp++ = '\n';
388 *outp++ = '.';
389 *outp++ = '\r';
390 *outp++ = '\n';
391 *outp = '\0'; /* NUL-terminate just in case. */
392 tor_assert((outp - *out) <= (int)sz_out);
393 return outp - *out;
396 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
397 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
398 * the contents of <b>data</b> into *<b>out</b>, removing any period
399 * that appears at the start of a line, and replacing all CRLF sequences
400 * with LF. Return the number of
401 * bytes in *<b>out</b>. */
402 /* static */ size_t
403 read_escaped_data(const char *data, size_t len, char **out)
405 char *outp;
406 const char *next;
407 const char *end;
409 *out = outp = tor_malloc(len+1);
411 end = data+len;
413 while (data < end) {
414 /* we're at the start of a line. */
415 if (*data == '.')
416 ++data;
417 next = memchr(data, '\n', end-data);
418 if (next) {
419 size_t n_to_copy = next-data;
420 /* Don't copy a CR that precedes this LF. */
421 if (n_to_copy && *(next-1) == '\r')
422 --n_to_copy;
423 memcpy(outp, data, n_to_copy);
424 outp += n_to_copy;
425 data = next+1; /* This will point at the start of the next line,
426 * or the end of the string, or a period. */
427 } else {
428 memcpy(outp, data, end-data);
429 outp += (end-data);
430 *outp = '\0';
431 return outp - *out;
433 *outp++ = '\n';
436 *outp = '\0';
437 return outp - *out;
440 /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
441 * double-quoted string with escaped characters, return the length of that
442 * string (as encoded, including quotes). Otherwise return -1. */
443 static INLINE int
444 get_escaped_string_length(const char *start, size_t in_len_max,
445 int *chars_out)
447 const char *cp, *end;
448 int chars = 0;
450 if (*start != '\"')
451 return -1;
453 cp = start+1;
454 end = start+in_len_max;
456 /* Calculate length. */
457 while (1) {
458 if (cp >= end) {
459 return -1; /* Too long. */
460 } else if (*cp == '\\') {
461 if (++cp == end)
462 return -1; /* Can't escape EOS. */
463 ++cp;
464 ++chars;
465 } else if (*cp == '\"') {
466 break;
467 } else {
468 ++cp;
469 ++chars;
472 if (chars_out)
473 *chars_out = chars;
474 return (int)(cp - start+1);
477 /** As decode_escaped_string, but does not decode the string: copies the
478 * entire thing, including quotation marks. */
479 static const char *
480 extract_escaped_string(const char *start, size_t in_len_max,
481 char **out, size_t *out_len)
483 int length = get_escaped_string_length(start, in_len_max, NULL);
484 if (length<0)
485 return NULL;
486 *out_len = length;
487 *out = tor_strndup(start, *out_len);
488 return start+length;
491 /** Given a pointer to a string starting at <b>start</b> containing
492 * <b>in_len_max</b> characters, decode a string beginning with one double
493 * quote, containing any number of non-quote characters or characters escaped
494 * with a backslash, and ending with a final double quote. Place the resulting
495 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
496 * store its length in <b>out_len</b>. On success, return a pointer to the
497 * character immediately following the escaped string. On failure, return
498 * NULL. */
499 static const char *
500 decode_escaped_string(const char *start, size_t in_len_max,
501 char **out, size_t *out_len)
503 const char *cp, *end;
504 char *outp;
505 int len, n_chars = 0;
507 len = get_escaped_string_length(start, in_len_max, &n_chars);
508 if (len<0)
509 return NULL;
511 end = start+len-1; /* Index of last quote. */
512 tor_assert(*end == '\"');
513 outp = *out = tor_malloc(len+1);
514 *out_len = n_chars;
516 cp = start+1;
517 while (cp < end) {
518 if (*cp == '\\')
519 ++cp;
520 *outp++ = *cp++;
522 *outp = '\0';
523 tor_assert((outp - *out) == (int)*out_len);
525 return end+1;
528 /** Acts like sprintf, but writes its formatted string to the end of
529 * <b>conn</b>-\>outbuf. */
530 static void
531 connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
533 va_list ap;
534 char *buf = NULL;
535 int len;
537 va_start(ap,format);
538 len = tor_vasprintf(&buf, format, ap);
539 va_end(ap);
541 if (len < 0) {
542 log_err(LD_BUG, "Unable to format string for controller.");
543 tor_assert(0);
546 connection_write_to_buf(buf, (size_t)len, TO_CONN(conn));
548 tor_free(buf);
551 /** Write all of the open control ports to ControlPortWriteToFile */
552 void
553 control_ports_write_to_file(void)
555 smartlist_t *lines;
556 char *joined = NULL;
557 const or_options_t *options = get_options();
559 if (!options->ControlPortWriteToFile)
560 return;
562 lines = smartlist_new();
564 SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t *, conn) {
565 if (conn->type != CONN_TYPE_CONTROL_LISTENER || conn->marked_for_close)
566 continue;
567 #ifdef AF_UNIX
568 if (conn->socket_family == AF_UNIX) {
569 smartlist_add_asprintf(lines, "UNIX_PORT=%s\n", conn->address);
570 continue;
572 #endif
573 smartlist_add_asprintf(lines, "PORT=%s:%d\n", conn->address, conn->port);
574 } SMARTLIST_FOREACH_END(conn);
576 joined = smartlist_join_strings(lines, "", 0, NULL);
578 if (write_str_to_file(options->ControlPortWriteToFile, joined, 0) < 0) {
579 log_warn(LD_CONTROL, "Writing %s failed: %s",
580 options->ControlPortWriteToFile, strerror(errno));
582 #ifndef _WIN32
583 if (options->ControlPortFileGroupReadable) {
584 if (chmod(options->ControlPortWriteToFile, 0640)) {
585 log_warn(LD_FS,"Unable to make %s group-readable.",
586 options->ControlPortWriteToFile);
589 #endif
590 tor_free(joined);
591 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
592 smartlist_free(lines);
595 /** Send a "DONE" message down the control connection <b>conn</b>. */
596 static void
597 send_control_done(control_connection_t *conn)
599 connection_write_str_to_buf("250 OK\r\n", conn);
602 /** Send an event to all v1 controllers that are listening for code
603 * <b>event</b>. The event's body is given by <b>msg</b>.
605 * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
606 * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
607 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
608 * to controllers that <em>have</em> enabled VERBOSE_NAMES.
610 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
611 * respect to the EXTENDED_EVENTS feature. */
612 static void
613 send_control_event_string(uint16_t event, event_format_t which,
614 const char *msg)
616 smartlist_t *conns = get_connection_array();
617 (void)which;
618 tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
620 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
621 if (conn->type == CONN_TYPE_CONTROL &&
622 !conn->marked_for_close &&
623 conn->state == CONTROL_CONN_STATE_OPEN) {
624 control_connection_t *control_conn = TO_CONTROL_CONN(conn);
626 if (control_conn->event_mask & (1<<event)) {
627 int is_err = 0;
628 connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
629 if (event == EVENT_ERR_MSG)
630 is_err = 1;
631 else if (event == EVENT_STATUS_GENERAL)
632 is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
633 else if (event == EVENT_STATUS_CLIENT)
634 is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
635 else if (event == EVENT_STATUS_SERVER)
636 is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
637 if (is_err)
638 connection_flush(TO_CONN(control_conn));
641 } SMARTLIST_FOREACH_END(conn);
644 /** Helper for send_control_event and control_event_status:
645 * Send an event to all v1 controllers that are listening for code
646 * <b>event</b>. The event's body is created by the printf-style format in
647 * <b>format</b>, and other arguments as provided. */
648 static void
649 send_control_event_impl(uint16_t event, event_format_t which,
650 const char *format, va_list ap)
652 char *buf = NULL;
653 int len;
655 len = tor_vasprintf(&buf, format, ap);
656 if (len < 0) {
657 log_warn(LD_BUG, "Unable to format event for controller.");
658 return;
661 send_control_event_string(event, which|ALL_FORMATS, buf);
663 tor_free(buf);
666 /** Send an event to all v1 controllers that are listening for code
667 * <b>event</b>. The event's body is created by the printf-style format in
668 * <b>format</b>, and other arguments as provided. */
669 static void
670 send_control_event(uint16_t event, event_format_t which,
671 const char *format, ...)
673 va_list ap;
674 va_start(ap, format);
675 send_control_event_impl(event, which, format, ap);
676 va_end(ap);
679 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
680 static origin_circuit_t *
681 get_circ(const char *id)
683 uint32_t n_id;
684 int ok;
685 n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
686 if (!ok)
687 return NULL;
688 return circuit_get_by_global_id(n_id);
691 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
692 static entry_connection_t *
693 get_stream(const char *id)
695 uint64_t n_id;
696 int ok;
697 connection_t *conn;
698 n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
699 if (!ok)
700 return NULL;
701 conn = connection_get_by_global_id(n_id);
702 if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
703 return NULL;
704 return TO_ENTRY_CONN(conn);
707 /** Helper for setconf and resetconf. Acts like setconf, except
708 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
709 * contents of body.
711 static int
712 control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
713 int use_defaults)
715 setopt_err_t opt_err;
716 config_line_t *lines=NULL;
717 char *start = body;
718 char *errstring = NULL;
719 const int clear_first = 1;
721 char *config;
722 smartlist_t *entries = smartlist_new();
724 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
725 * separated by space. break it into a list of configuration entries. */
726 while (*body) {
727 char *eq = body;
728 char *key;
729 char *entry;
730 while (!TOR_ISSPACE(*eq) && *eq != '=')
731 ++eq;
732 key = tor_strndup(body, eq-body);
733 body = eq+1;
734 if (*eq == '=') {
735 char *val=NULL;
736 size_t val_len=0;
737 if (*body != '\"') {
738 char *val_start = body;
739 while (!TOR_ISSPACE(*body))
740 body++;
741 val = tor_strndup(val_start, body-val_start);
742 val_len = strlen(val);
743 } else {
744 body = (char*)extract_escaped_string(body, (len - (body-start)),
745 &val, &val_len);
746 if (!body) {
747 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
748 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
749 smartlist_free(entries);
750 tor_free(key);
751 return 0;
754 tor_asprintf(&entry, "%s %s", key, val);
755 tor_free(key);
756 tor_free(val);
757 } else {
758 entry = key;
760 smartlist_add(entries, entry);
761 while (TOR_ISSPACE(*body))
762 ++body;
765 smartlist_add(entries, tor_strdup(""));
766 config = smartlist_join_strings(entries, "\n", 0, NULL);
767 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
768 smartlist_free(entries);
770 if (config_get_lines(config, &lines, 0) < 0) {
771 log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
772 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
773 conn);
774 tor_free(config);
775 return 0;
777 tor_free(config);
779 opt_err = options_trial_assign(lines, use_defaults, clear_first, &errstring);
781 const char *msg;
782 switch (opt_err) {
783 case SETOPT_ERR_MISC:
784 msg = "552 Unrecognized option";
785 break;
786 case SETOPT_ERR_PARSE:
787 msg = "513 Unacceptable option value";
788 break;
789 case SETOPT_ERR_TRANSITION:
790 msg = "553 Transition not allowed";
791 break;
792 case SETOPT_ERR_SETTING:
793 default:
794 msg = "553 Unable to set option";
795 break;
796 case SETOPT_OK:
797 config_free_lines(lines);
798 send_control_done(conn);
799 return 0;
801 log_warn(LD_CONTROL,
802 "Controller gave us config lines that didn't validate: %s",
803 errstring);
804 connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
805 config_free_lines(lines);
806 tor_free(errstring);
807 return 0;
811 /** Called when we receive a SETCONF message: parse the body and try
812 * to update our configuration. Reply with a DONE or ERROR message.
813 * Modifies the contents of body.*/
814 static int
815 handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
817 return control_setconf_helper(conn, len, body, 0);
820 /** Called when we receive a RESETCONF message: parse the body and try
821 * to update our configuration. Reply with a DONE or ERROR message.
822 * Modifies the contents of body. */
823 static int
824 handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
826 return control_setconf_helper(conn, len, body, 1);
829 /** Called when we receive a GETCONF message. Parse the request, and
830 * reply with a CONFVALUE or an ERROR message */
831 static int
832 handle_control_getconf(control_connection_t *conn, uint32_t body_len,
833 const char *body)
835 smartlist_t *questions = smartlist_new();
836 smartlist_t *answers = smartlist_new();
837 smartlist_t *unrecognized = smartlist_new();
838 char *msg = NULL;
839 size_t msg_len;
840 const or_options_t *options = get_options();
841 int i, len;
843 (void) body_len; /* body is NUL-terminated; so we can ignore len. */
844 smartlist_split_string(questions, body, " ",
845 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
846 SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
847 if (!option_is_recognized(q)) {
848 smartlist_add(unrecognized, (char*) q);
849 } else {
850 config_line_t *answer = option_get_assignment(options,q);
851 if (!answer) {
852 const char *name = option_get_canonical_name(q);
853 smartlist_add_asprintf(answers, "250-%s\r\n", name);
856 while (answer) {
857 config_line_t *next;
858 smartlist_add_asprintf(answers, "250-%s=%s\r\n",
859 answer->key, answer->value);
861 next = answer->next;
862 tor_free(answer->key);
863 tor_free(answer->value);
864 tor_free(answer);
865 answer = next;
868 } SMARTLIST_FOREACH_END(q);
870 if ((len = smartlist_len(unrecognized))) {
871 for (i=0; i < len-1; ++i)
872 connection_printf_to_buf(conn,
873 "552-Unrecognized configuration key \"%s\"\r\n",
874 (char*)smartlist_get(unrecognized, i));
875 connection_printf_to_buf(conn,
876 "552 Unrecognized configuration key \"%s\"\r\n",
877 (char*)smartlist_get(unrecognized, len-1));
878 } else if ((len = smartlist_len(answers))) {
879 char *tmp = smartlist_get(answers, len-1);
880 tor_assert(strlen(tmp)>4);
881 tmp[3] = ' ';
882 msg = smartlist_join_strings(answers, "", 0, &msg_len);
883 connection_write_to_buf(msg, msg_len, TO_CONN(conn));
884 } else {
885 connection_write_str_to_buf("250 OK\r\n", conn);
888 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
889 smartlist_free(answers);
890 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
891 smartlist_free(questions);
892 smartlist_free(unrecognized);
894 tor_free(msg);
896 return 0;
899 /** Called when we get a +LOADCONF message. */
900 static int
901 handle_control_loadconf(control_connection_t *conn, uint32_t len,
902 const char *body)
904 setopt_err_t retval;
905 char *errstring = NULL;
906 const char *msg = NULL;
907 (void) len;
909 retval = options_init_from_string(NULL, body, CMD_RUN_TOR, NULL, &errstring);
911 if (retval != SETOPT_OK)
912 log_warn(LD_CONTROL,
913 "Controller gave us config file that didn't validate: %s",
914 errstring);
916 switch (retval) {
917 case SETOPT_ERR_PARSE:
918 msg = "552 Invalid config file";
919 break;
920 case SETOPT_ERR_TRANSITION:
921 msg = "553 Transition not allowed";
922 break;
923 case SETOPT_ERR_SETTING:
924 msg = "553 Unable to set option";
925 break;
926 case SETOPT_ERR_MISC:
927 default:
928 msg = "550 Unable to load config";
929 break;
930 case SETOPT_OK:
931 break;
933 if (msg) {
934 if (errstring)
935 connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
936 else
937 connection_printf_to_buf(conn, "%s\r\n", msg);
938 } else {
939 send_control_done(conn);
941 tor_free(errstring);
942 return 0;
945 /** Helper structure: maps event values to their names. */
946 struct control_event_t {
947 uint16_t event_code;
948 const char *event_name;
950 /** Table mapping event values to their names. Used to implement SETEVENTS
951 * and GETINFO events/names, and to keep they in sync. */
952 static const struct control_event_t control_event_table[] = {
953 { EVENT_CIRCUIT_STATUS, "CIRC" },
954 { EVENT_CIRCUIT_STATUS_MINOR, "CIRC_MINOR" },
955 { EVENT_STREAM_STATUS, "STREAM" },
956 { EVENT_OR_CONN_STATUS, "ORCONN" },
957 { EVENT_BANDWIDTH_USED, "BW" },
958 { EVENT_DEBUG_MSG, "DEBUG" },
959 { EVENT_INFO_MSG, "INFO" },
960 { EVENT_NOTICE_MSG, "NOTICE" },
961 { EVENT_WARN_MSG, "WARN" },
962 { EVENT_ERR_MSG, "ERR" },
963 { EVENT_NEW_DESC, "NEWDESC" },
964 { EVENT_ADDRMAP, "ADDRMAP" },
965 { EVENT_AUTHDIR_NEWDESCS, "AUTHDIR_NEWDESCS" },
966 { EVENT_DESCCHANGED, "DESCCHANGED" },
967 { EVENT_NS, "NS" },
968 { EVENT_STATUS_GENERAL, "STATUS_GENERAL" },
969 { EVENT_STATUS_CLIENT, "STATUS_CLIENT" },
970 { EVENT_STATUS_SERVER, "STATUS_SERVER" },
971 { EVENT_GUARD, "GUARD" },
972 { EVENT_STREAM_BANDWIDTH_USED, "STREAM_BW" },
973 { EVENT_CLIENTS_SEEN, "CLIENTS_SEEN" },
974 { EVENT_NEWCONSENSUS, "NEWCONSENSUS" },
975 { EVENT_BUILDTIMEOUT_SET, "BUILDTIMEOUT_SET" },
976 { EVENT_SIGNAL, "SIGNAL" },
977 { EVENT_CONF_CHANGED, "CONF_CHANGED"},
978 { EVENT_CONN_BW, "CONN_BW" },
979 { EVENT_CELL_STATS, "CELL_STATS" },
980 { EVENT_TB_EMPTY, "TB_EMPTY" },
981 { EVENT_CIRC_BANDWIDTH_USED, "CIRC_BW" },
982 { 0, NULL },
985 /** Called when we get a SETEVENTS message: update conn->event_mask,
986 * and reply with DONE or ERROR. */
987 static int
988 handle_control_setevents(control_connection_t *conn, uint32_t len,
989 const char *body)
991 int event_code = -1;
992 uint32_t event_mask = 0;
993 smartlist_t *events = smartlist_new();
995 (void) len;
997 smartlist_split_string(events, body, " ",
998 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
999 SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
1001 if (!strcasecmp(ev, "EXTENDED")) {
1002 continue;
1003 } else {
1004 int i;
1005 for (i = 0; control_event_table[i].event_name != NULL; ++i) {
1006 if (!strcasecmp(ev, control_event_table[i].event_name)) {
1007 event_code = control_event_table[i].event_code;
1008 break;
1012 if (event_code == -1) {
1013 connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
1014 ev);
1015 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
1016 smartlist_free(events);
1017 return 0;
1020 event_mask |= (1 << event_code);
1022 SMARTLIST_FOREACH_END(ev);
1023 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
1024 smartlist_free(events);
1026 conn->event_mask = event_mask;
1028 control_update_global_event_mask();
1029 send_control_done(conn);
1030 return 0;
1033 /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
1034 * Return a smartlist of acceptable passwords (unterminated strings of
1035 * length S2K_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on failure.
1037 smartlist_t *
1038 decode_hashed_passwords(config_line_t *passwords)
1040 char decoded[64];
1041 config_line_t *cl;
1042 smartlist_t *sl = smartlist_new();
1044 tor_assert(passwords);
1046 for (cl = passwords; cl; cl = cl->next) {
1047 const char *hashed = cl->value;
1049 if (!strcmpstart(hashed, "16:")) {
1050 if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
1051 || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
1052 goto err;
1054 } else {
1055 if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
1056 != S2K_SPECIFIER_LEN+DIGEST_LEN) {
1057 goto err;
1060 smartlist_add(sl, tor_memdup(decoded, S2K_SPECIFIER_LEN+DIGEST_LEN));
1063 return sl;
1065 err:
1066 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
1067 smartlist_free(sl);
1068 return NULL;
1071 /** Called when we get an AUTHENTICATE message. Check whether the
1072 * authentication is valid, and if so, update the connection's state to
1073 * OPEN. Reply with DONE or ERROR.
1075 static int
1076 handle_control_authenticate(control_connection_t *conn, uint32_t len,
1077 const char *body)
1079 int used_quoted_string = 0;
1080 const or_options_t *options = get_options();
1081 const char *errstr = NULL;
1082 char *password;
1083 size_t password_len;
1084 const char *cp;
1085 int i;
1086 int bad_cookie=0, bad_password=0;
1087 smartlist_t *sl = NULL;
1089 if (!len) {
1090 password = tor_strdup("");
1091 password_len = 0;
1092 } else if (TOR_ISXDIGIT(body[0])) {
1093 cp = body;
1094 while (TOR_ISXDIGIT(*cp))
1095 ++cp;
1096 i = (int)(cp - body);
1097 tor_assert(i>0);
1098 password_len = i/2;
1099 password = tor_malloc(password_len + 1);
1100 if (base16_decode(password, password_len+1, body, i)<0) {
1101 connection_write_str_to_buf(
1102 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1103 "password? If so, the standard requires that you put it in "
1104 "double quotes.\r\n", conn);
1105 connection_mark_for_close(TO_CONN(conn));
1106 tor_free(password);
1107 return 0;
1109 } else {
1110 if (!decode_escaped_string(body, len, &password, &password_len)) {
1111 connection_write_str_to_buf("551 Invalid quoted string. You need "
1112 "to put the password in double quotes.\r\n", conn);
1113 connection_mark_for_close(TO_CONN(conn));
1114 return 0;
1116 used_quoted_string = 1;
1119 if (conn->safecookie_client_hash != NULL) {
1120 /* The controller has chosen safe cookie authentication; the only
1121 * acceptable authentication value is the controller-to-server
1122 * response. */
1124 tor_assert(authentication_cookie_is_set);
1126 if (password_len != DIGEST256_LEN) {
1127 log_warn(LD_CONTROL,
1128 "Got safe cookie authentication response with wrong length "
1129 "(%d)", (int)password_len);
1130 errstr = "Wrong length for safe cookie response.";
1131 goto err;
1134 if (tor_memneq(conn->safecookie_client_hash, password, DIGEST256_LEN)) {
1135 log_warn(LD_CONTROL,
1136 "Got incorrect safe cookie authentication response");
1137 errstr = "Safe cookie response did not match expected value.";
1138 goto err;
1141 tor_free(conn->safecookie_client_hash);
1142 goto ok;
1145 if (!options->CookieAuthentication && !options->HashedControlPassword &&
1146 !options->HashedControlSessionPassword) {
1147 /* if Tor doesn't demand any stronger authentication, then
1148 * the controller can get in with anything. */
1149 goto ok;
1152 if (options->CookieAuthentication) {
1153 int also_password = options->HashedControlPassword != NULL ||
1154 options->HashedControlSessionPassword != NULL;
1155 if (password_len != AUTHENTICATION_COOKIE_LEN) {
1156 if (!also_password) {
1157 log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
1158 "(%d)", (int)password_len);
1159 errstr = "Wrong length on authentication cookie.";
1160 goto err;
1162 bad_cookie = 1;
1163 } else if (tor_memneq(authentication_cookie, password, password_len)) {
1164 if (!also_password) {
1165 log_warn(LD_CONTROL, "Got mismatched authentication cookie");
1166 errstr = "Authentication cookie did not match expected value.";
1167 goto err;
1169 bad_cookie = 1;
1170 } else {
1171 goto ok;
1175 if (options->HashedControlPassword ||
1176 options->HashedControlSessionPassword) {
1177 int bad = 0;
1178 smartlist_t *sl_tmp;
1179 char received[DIGEST_LEN];
1180 int also_cookie = options->CookieAuthentication;
1181 sl = smartlist_new();
1182 if (options->HashedControlPassword) {
1183 sl_tmp = decode_hashed_passwords(options->HashedControlPassword);
1184 if (!sl_tmp)
1185 bad = 1;
1186 else {
1187 smartlist_add_all(sl, sl_tmp);
1188 smartlist_free(sl_tmp);
1191 if (options->HashedControlSessionPassword) {
1192 sl_tmp = decode_hashed_passwords(options->HashedControlSessionPassword);
1193 if (!sl_tmp)
1194 bad = 1;
1195 else {
1196 smartlist_add_all(sl, sl_tmp);
1197 smartlist_free(sl_tmp);
1200 if (bad) {
1201 if (!also_cookie) {
1202 log_warn(LD_CONTROL,
1203 "Couldn't decode HashedControlPassword: invalid base16");
1204 errstr="Couldn't decode HashedControlPassword value in configuration.";
1206 bad_password = 1;
1207 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1208 smartlist_free(sl);
1209 } else {
1210 SMARTLIST_FOREACH(sl, char *, expected,
1212 secret_to_key(received,DIGEST_LEN,password,password_len,expected);
1213 if (tor_memeq(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
1214 goto ok;
1216 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1217 smartlist_free(sl);
1219 if (used_quoted_string)
1220 errstr = "Password did not match HashedControlPassword value from "
1221 "configuration";
1222 else
1223 errstr = "Password did not match HashedControlPassword value from "
1224 "configuration. Maybe you tried a plain text password? "
1225 "If so, the standard requires that you put it in double quotes.";
1226 bad_password = 1;
1227 if (!also_cookie)
1228 goto err;
1232 /** We only get here if both kinds of authentication failed. */
1233 tor_assert(bad_password && bad_cookie);
1234 log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
1235 errstr = "Password did not match HashedControlPassword *or* authentication "
1236 "cookie.";
1238 err:
1239 tor_free(password);
1240 connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n",
1241 errstr ? errstr : "Unknown reason.");
1242 connection_mark_for_close(TO_CONN(conn));
1243 return 0;
1245 log_info(LD_CONTROL, "Authenticated control connection ("TOR_SOCKET_T_FORMAT
1246 ")", conn->base_.s);
1247 send_control_done(conn);
1248 conn->base_.state = CONTROL_CONN_STATE_OPEN;
1249 tor_free(password);
1250 if (sl) { /* clean up */
1251 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1252 smartlist_free(sl);
1254 return 0;
1257 /** Called when we get a SAVECONF command. Try to flush the current options to
1258 * disk, and report success or failure. */
1259 static int
1260 handle_control_saveconf(control_connection_t *conn, uint32_t len,
1261 const char *body)
1263 (void) len;
1264 (void) body;
1265 if (options_save_current()<0) {
1266 connection_write_str_to_buf(
1267 "551 Unable to write configuration to disk.\r\n", conn);
1268 } else {
1269 send_control_done(conn);
1271 return 0;
1274 struct signal_t {
1275 int sig;
1276 const char *signal_name;
1279 static const struct signal_t signal_table[] = {
1280 { SIGHUP, "RELOAD" },
1281 { SIGHUP, "HUP" },
1282 { SIGINT, "SHUTDOWN" },
1283 { SIGUSR1, "DUMP" },
1284 { SIGUSR1, "USR1" },
1285 { SIGUSR2, "DEBUG" },
1286 { SIGUSR2, "USR2" },
1287 { SIGTERM, "HALT" },
1288 { SIGTERM, "TERM" },
1289 { SIGTERM, "INT" },
1290 { SIGNEWNYM, "NEWNYM" },
1291 { SIGCLEARDNSCACHE, "CLEARDNSCACHE"},
1292 { 0, NULL },
1295 /** Called when we get a SIGNAL command. React to the provided signal, and
1296 * report success or failure. (If the signal results in a shutdown, success
1297 * may not be reported.) */
1298 static int
1299 handle_control_signal(control_connection_t *conn, uint32_t len,
1300 const char *body)
1302 int sig = -1;
1303 int i;
1304 int n = 0;
1305 char *s;
1307 (void) len;
1309 while (body[n] && ! TOR_ISSPACE(body[n]))
1310 ++n;
1311 s = tor_strndup(body, n);
1313 for (i = 0; signal_table[i].signal_name != NULL; ++i) {
1314 if (!strcasecmp(s, signal_table[i].signal_name)) {
1315 sig = signal_table[i].sig;
1316 break;
1320 if (sig < 0)
1321 connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
1323 tor_free(s);
1324 if (sig < 0)
1325 return 0;
1327 send_control_done(conn);
1328 /* Flush the "done" first if the signal might make us shut down. */
1329 if (sig == SIGTERM || sig == SIGINT)
1330 connection_flush(TO_CONN(conn));
1332 process_signal(sig);
1334 return 0;
1337 /** Called when we get a TAKEOWNERSHIP command. Mark this connection
1338 * as an owning connection, so that we will exit if the connection
1339 * closes. */
1340 static int
1341 handle_control_takeownership(control_connection_t *conn, uint32_t len,
1342 const char *body)
1344 (void)len;
1345 (void)body;
1347 conn->is_owning_control_connection = 1;
1349 log_info(LD_CONTROL, "Control connection %d has taken ownership of this "
1350 "Tor instance.",
1351 (int)(conn->base_.s));
1353 send_control_done(conn);
1354 return 0;
1357 /** Return true iff <b>addr</b> is unusable as a mapaddress target because of
1358 * containing funny characters. */
1359 static int
1360 address_is_invalid_mapaddress_target(const char *addr)
1362 if (!strcmpstart(addr, "*."))
1363 return address_is_invalid_destination(addr+2, 1);
1364 else
1365 return address_is_invalid_destination(addr, 1);
1368 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1369 * and report success or failure. */
1370 static int
1371 handle_control_mapaddress(control_connection_t *conn, uint32_t len,
1372 const char *body)
1374 smartlist_t *elts;
1375 smartlist_t *lines;
1376 smartlist_t *reply;
1377 char *r;
1378 size_t sz;
1379 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
1381 lines = smartlist_new();
1382 elts = smartlist_new();
1383 reply = smartlist_new();
1384 smartlist_split_string(lines, body, " ",
1385 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1386 SMARTLIST_FOREACH_BEGIN(lines, char *, line) {
1387 tor_strlower(line);
1388 smartlist_split_string(elts, line, "=", 0, 2);
1389 if (smartlist_len(elts) == 2) {
1390 const char *from = smartlist_get(elts,0);
1391 const char *to = smartlist_get(elts,1);
1392 if (address_is_invalid_mapaddress_target(to)) {
1393 smartlist_add_asprintf(reply,
1394 "512-syntax error: invalid address '%s'", to);
1395 log_warn(LD_CONTROL,
1396 "Skipping invalid argument '%s' in MapAddress msg", to);
1397 } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0") ||
1398 !strcmp(from, "::")) {
1399 const char type =
1400 !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME :
1401 (!strcmp(from, "0.0.0.0") ? RESOLVED_TYPE_IPV4 : RESOLVED_TYPE_IPV6);
1402 const char *address = addressmap_register_virtual_address(
1403 type, tor_strdup(to));
1404 if (!address) {
1405 smartlist_add_asprintf(reply,
1406 "451-resource exhausted: skipping '%s'", line);
1407 log_warn(LD_CONTROL,
1408 "Unable to allocate address for '%s' in MapAddress msg",
1409 safe_str_client(line));
1410 } else {
1411 smartlist_add_asprintf(reply, "250-%s=%s", address, to);
1413 } else {
1414 const char *msg;
1415 if (addressmap_register_auto(from, to, 1,
1416 ADDRMAPSRC_CONTROLLER, &msg) < 0) {
1417 smartlist_add_asprintf(reply,
1418 "512-syntax error: invalid address mapping "
1419 " '%s': %s", line, msg);
1420 log_warn(LD_CONTROL,
1421 "Skipping invalid argument '%s' in MapAddress msg: %s",
1422 line, msg);
1423 } else {
1424 smartlist_add_asprintf(reply, "250-%s", line);
1427 } else {
1428 smartlist_add_asprintf(reply, "512-syntax error: mapping '%s' is "
1429 "not of expected form 'foo=bar'.", line);
1430 log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
1431 "number of items.",
1432 safe_str_client(line));
1434 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
1435 smartlist_clear(elts);
1436 } SMARTLIST_FOREACH_END(line);
1437 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1438 smartlist_free(lines);
1439 smartlist_free(elts);
1441 if (smartlist_len(reply)) {
1442 ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
1443 r = smartlist_join_strings(reply, "\r\n", 1, &sz);
1444 connection_write_to_buf(r, sz, TO_CONN(conn));
1445 tor_free(r);
1446 } else {
1447 const char *response =
1448 "512 syntax error: not enough arguments to mapaddress.\r\n";
1449 connection_write_to_buf(response, strlen(response), TO_CONN(conn));
1452 SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
1453 smartlist_free(reply);
1454 return 0;
1457 /** Implementation helper for GETINFO: knows the answers for various
1458 * trivial-to-implement questions. */
1459 static int
1460 getinfo_helper_misc(control_connection_t *conn, const char *question,
1461 char **answer, const char **errmsg)
1463 (void) conn;
1464 if (!strcmp(question, "version")) {
1465 *answer = tor_strdup(get_version());
1466 } else if (!strcmp(question, "config-file")) {
1467 *answer = tor_strdup(get_torrc_fname(0));
1468 } else if (!strcmp(question, "config-defaults-file")) {
1469 *answer = tor_strdup(get_torrc_fname(1));
1470 } else if (!strcmp(question, "config-text")) {
1471 *answer = options_dump(get_options(), 1);
1472 } else if (!strcmp(question, "info/names")) {
1473 *answer = list_getinfo_options();
1474 } else if (!strcmp(question, "dormant")) {
1475 int dormant = rep_hist_circbuilding_dormant(time(NULL));
1476 *answer = tor_strdup(dormant ? "1" : "0");
1477 } else if (!strcmp(question, "events/names")) {
1478 int i;
1479 smartlist_t *event_names = smartlist_new();
1481 for (i = 0; control_event_table[i].event_name != NULL; ++i) {
1482 smartlist_add(event_names, (char *)control_event_table[i].event_name);
1485 *answer = smartlist_join_strings(event_names, " ", 0, NULL);
1487 smartlist_free(event_names);
1488 } else if (!strcmp(question, "signal/names")) {
1489 smartlist_t *signal_names = smartlist_new();
1490 int j;
1491 for (j = 0; signal_table[j].signal_name != NULL; ++j) {
1492 smartlist_add(signal_names, (char*)signal_table[j].signal_name);
1495 *answer = smartlist_join_strings(signal_names, " ", 0, NULL);
1497 smartlist_free(signal_names);
1498 } else if (!strcmp(question, "features/names")) {
1499 *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1500 } else if (!strcmp(question, "address")) {
1501 uint32_t addr;
1502 if (router_pick_published_address(get_options(), &addr) < 0) {
1503 *errmsg = "Address unknown";
1504 return -1;
1506 *answer = tor_dup_ip(addr);
1507 } else if (!strcmp(question, "traffic/read")) {
1508 tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_read()));
1509 } else if (!strcmp(question, "traffic/written")) {
1510 tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_written()));
1511 } else if (!strcmp(question, "process/pid")) {
1512 int myPid = -1;
1514 #ifdef _WIN32
1515 myPid = _getpid();
1516 #else
1517 myPid = getpid();
1518 #endif
1520 tor_asprintf(answer, "%d", myPid);
1521 } else if (!strcmp(question, "process/uid")) {
1522 #ifdef _WIN32
1523 *answer = tor_strdup("-1");
1524 #else
1525 int myUid = geteuid();
1526 tor_asprintf(answer, "%d", myUid);
1527 #endif
1528 } else if (!strcmp(question, "process/user")) {
1529 #ifdef _WIN32
1530 *answer = tor_strdup("");
1531 #else
1532 int myUid = geteuid();
1533 struct passwd *myPwEntry = getpwuid(myUid);
1535 if (myPwEntry) {
1536 *answer = tor_strdup(myPwEntry->pw_name);
1537 } else {
1538 *answer = tor_strdup("");
1540 #endif
1541 } else if (!strcmp(question, "process/descriptor-limit")) {
1542 int max_fds=-1;
1543 set_max_file_descriptors(0, &max_fds);
1544 tor_asprintf(answer, "%d", max_fds);
1545 } else if (!strcmp(question, "dir-usage")) {
1546 *answer = directory_dump_request_log();
1547 } else if (!strcmp(question, "fingerprint")) {
1548 crypto_pk_t *server_key;
1549 if (!server_mode(get_options())) {
1550 *errmsg = "Not running in server mode";
1551 return -1;
1553 server_key = get_server_identity_key();
1554 *answer = tor_malloc(HEX_DIGEST_LEN+1);
1555 crypto_pk_get_fingerprint(server_key, *answer, 0);
1557 return 0;
1560 /** Awful hack: return a newly allocated string based on a routerinfo and
1561 * (possibly) an extrainfo, sticking the read-history and write-history from
1562 * <b>ei</b> into the resulting string. The thing you get back won't
1563 * necessarily have a valid signature.
1565 * New code should never use this; it's for backward compatibility.
1567 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1568 * not be NUL-terminated. */
1569 static char *
1570 munge_extrainfo_into_routerinfo(const char *ri_body,
1571 const signed_descriptor_t *ri,
1572 const signed_descriptor_t *ei)
1574 char *out = NULL, *outp;
1575 int i;
1576 const char *router_sig;
1577 const char *ei_body = signed_descriptor_get_body(ei);
1578 size_t ri_len = ri->signed_descriptor_len;
1579 size_t ei_len = ei->signed_descriptor_len;
1580 if (!ei_body)
1581 goto bail;
1583 outp = out = tor_malloc(ri_len+ei_len+1);
1584 if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
1585 goto bail;
1586 ++router_sig;
1587 memcpy(out, ri_body, router_sig-ri_body);
1588 outp += router_sig-ri_body;
1590 for (i=0; i < 2; ++i) {
1591 const char *kwd = i?"\nwrite-history ":"\nread-history ";
1592 const char *cp, *eol;
1593 if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
1594 continue;
1595 ++cp;
1596 if (!(eol = memchr(cp, '\n', ei_len - (cp-ei_body))))
1597 continue;
1598 memcpy(outp, cp, eol-cp+1);
1599 outp += eol-cp+1;
1601 memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
1602 *outp++ = '\0';
1603 tor_assert(outp-out < (int)(ri_len+ei_len+1));
1605 return out;
1606 bail:
1607 tor_free(out);
1608 return tor_strndup(ri_body, ri->signed_descriptor_len);
1611 /** Implementation helper for GETINFO: answers requests for information about
1612 * which ports are bound. */
1613 static int
1614 getinfo_helper_listeners(control_connection_t *control_conn,
1615 const char *question,
1616 char **answer, const char **errmsg)
1618 int type;
1619 smartlist_t *res;
1621 (void)control_conn;
1622 (void)errmsg;
1624 if (!strcmp(question, "net/listeners/or"))
1625 type = CONN_TYPE_OR_LISTENER;
1626 else if (!strcmp(question, "net/listeners/dir"))
1627 type = CONN_TYPE_DIR_LISTENER;
1628 else if (!strcmp(question, "net/listeners/socks"))
1629 type = CONN_TYPE_AP_LISTENER;
1630 else if (!strcmp(question, "net/listeners/trans"))
1631 type = CONN_TYPE_AP_TRANS_LISTENER;
1632 else if (!strcmp(question, "net/listeners/natd"))
1633 type = CONN_TYPE_AP_NATD_LISTENER;
1634 else if (!strcmp(question, "net/listeners/dns"))
1635 type = CONN_TYPE_AP_DNS_LISTENER;
1636 else if (!strcmp(question, "net/listeners/control"))
1637 type = CONN_TYPE_CONTROL_LISTENER;
1638 else
1639 return 0; /* unknown key */
1641 res = smartlist_new();
1642 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
1643 struct sockaddr_storage ss;
1644 socklen_t ss_len = sizeof(ss);
1646 if (conn->type != type || conn->marked_for_close || !SOCKET_OK(conn->s))
1647 continue;
1649 if (getsockname(conn->s, (struct sockaddr *)&ss, &ss_len) < 0) {
1650 smartlist_add_asprintf(res, "%s:%d", conn->address, (int)conn->port);
1651 } else {
1652 char *tmp = tor_sockaddr_to_str((struct sockaddr *)&ss);
1653 smartlist_add(res, esc_for_log(tmp));
1654 tor_free(tmp);
1657 } SMARTLIST_FOREACH_END(conn);
1659 *answer = smartlist_join_strings(res, " ", 0, NULL);
1661 SMARTLIST_FOREACH(res, char *, cp, tor_free(cp));
1662 smartlist_free(res);
1663 return 0;
1666 /** Implementation helper for GETINFO: knows the answers for questions about
1667 * directory information. */
1668 static int
1669 getinfo_helper_dir(control_connection_t *control_conn,
1670 const char *question, char **answer,
1671 const char **errmsg)
1673 const node_t *node;
1674 const routerinfo_t *ri = NULL;
1675 (void) control_conn;
1676 if (!strcmpstart(question, "desc/id/")) {
1677 node = node_get_by_hex_id(question+strlen("desc/id/"));
1678 if (node)
1679 ri = node->ri;
1680 if (ri) {
1681 const char *body = signed_descriptor_get_body(&ri->cache_info);
1682 if (body)
1683 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1685 } else if (!strcmpstart(question, "desc/name/")) {
1686 /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
1687 * warning goes to the user, not to the controller. */
1688 node = node_get_by_nickname(question+strlen("desc/name/"), 1);
1689 if (node)
1690 ri = node->ri;
1691 if (ri) {
1692 const char *body = signed_descriptor_get_body(&ri->cache_info);
1693 if (body)
1694 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1696 } else if (!strcmp(question, "desc/all-recent")) {
1697 routerlist_t *routerlist = router_get_routerlist();
1698 smartlist_t *sl = smartlist_new();
1699 if (routerlist && routerlist->routers) {
1700 SMARTLIST_FOREACH(routerlist->routers, const routerinfo_t *, ri,
1702 const char *body = signed_descriptor_get_body(&ri->cache_info);
1703 if (body)
1704 smartlist_add(sl,
1705 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1708 *answer = smartlist_join_strings(sl, "", 0, NULL);
1709 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1710 smartlist_free(sl);
1711 } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
1712 /* XXXX Remove this once Torstat asks for extrainfos. */
1713 routerlist_t *routerlist = router_get_routerlist();
1714 smartlist_t *sl = smartlist_new();
1715 if (routerlist && routerlist->routers) {
1716 SMARTLIST_FOREACH_BEGIN(routerlist->routers, const routerinfo_t *, ri) {
1717 const char *body = signed_descriptor_get_body(&ri->cache_info);
1718 signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
1719 ri->cache_info.extra_info_digest);
1720 if (ei && body) {
1721 smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
1722 &ri->cache_info, ei));
1723 } else if (body) {
1724 smartlist_add(sl,
1725 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1727 } SMARTLIST_FOREACH_END(ri);
1729 *answer = smartlist_join_strings(sl, "", 0, NULL);
1730 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1731 smartlist_free(sl);
1732 } else if (!strcmpstart(question, "md/id/")) {
1733 const node_t *node = node_get_by_hex_id(question+strlen("md/id/"));
1734 const microdesc_t *md = NULL;
1735 if (node) md = node->md;
1736 if (md) {
1737 tor_assert(md->body);
1738 *answer = tor_strndup(md->body, md->bodylen);
1740 } else if (!strcmpstart(question, "md/name/")) {
1741 /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
1742 * warning goes to the user, not to the controller. */
1743 const node_t *node = node_get_by_nickname(question+strlen("md/name/"), 1);
1744 /* XXXX duplicated code */
1745 const microdesc_t *md = NULL;
1746 if (node) md = node->md;
1747 if (md) {
1748 tor_assert(md->body);
1749 *answer = tor_strndup(md->body, md->bodylen);
1751 } else if (!strcmpstart(question, "desc-annotations/id/")) {
1752 node = node_get_by_hex_id(question+strlen("desc-annotations/id/"));
1753 if (node)
1754 ri = node->ri;
1755 if (ri) {
1756 const char *annotations =
1757 signed_descriptor_get_annotations(&ri->cache_info);
1758 if (annotations)
1759 *answer = tor_strndup(annotations,
1760 ri->cache_info.annotations_len);
1762 } else if (!strcmpstart(question, "dir/server/")) {
1763 size_t answer_len = 0;
1764 char *url = NULL;
1765 smartlist_t *descs = smartlist_new();
1766 const char *msg;
1767 int res;
1768 char *cp;
1769 tor_asprintf(&url, "/tor/%s", question+4);
1770 res = dirserv_get_routerdescs(descs, url, &msg);
1771 if (res) {
1772 log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
1773 smartlist_free(descs);
1774 tor_free(url);
1775 *errmsg = msg;
1776 return -1;
1778 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1779 answer_len += sd->signed_descriptor_len);
1780 cp = *answer = tor_malloc(answer_len+1);
1781 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1783 memcpy(cp, signed_descriptor_get_body(sd),
1784 sd->signed_descriptor_len);
1785 cp += sd->signed_descriptor_len;
1787 *cp = '\0';
1788 tor_free(url);
1789 smartlist_free(descs);
1790 } else if (!strcmpstart(question, "dir/status/")) {
1791 if (directory_permits_controller_requests(get_options())) {
1792 size_t len=0;
1793 char *cp;
1794 smartlist_t *status_list = smartlist_new();
1795 dirserv_get_networkstatus_v2(status_list,
1796 question+strlen("dir/status/"));
1797 SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
1798 cp = *answer = tor_malloc(len+1);
1799 SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
1800 memcpy(cp, d->dir, d->dir_len);
1801 cp += d->dir_len;
1803 *cp = '\0';
1804 smartlist_free(status_list);
1805 } else {
1806 smartlist_t *fp_list = smartlist_new();
1807 smartlist_t *status_list = smartlist_new();
1808 dirserv_get_networkstatus_v2_fingerprints(
1809 fp_list, question+strlen("dir/status/"));
1810 SMARTLIST_FOREACH(fp_list, const char *, fp, {
1811 char *s;
1812 char *fname = networkstatus_get_cache_filename(fp);
1813 s = read_file_to_str(fname, 0, NULL);
1814 if (s)
1815 smartlist_add(status_list, s);
1816 tor_free(fname);
1818 SMARTLIST_FOREACH(fp_list, char *, fp, tor_free(fp));
1819 smartlist_free(fp_list);
1820 *answer = smartlist_join_strings(status_list, "", 0, NULL);
1821 SMARTLIST_FOREACH(status_list, char *, s, tor_free(s));
1822 smartlist_free(status_list);
1824 } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
1825 if (directory_caches_dir_info(get_options())) {
1826 const cached_dir_t *consensus = dirserv_get_consensus("ns");
1827 if (consensus)
1828 *answer = tor_strdup(consensus->dir);
1830 if (!*answer) { /* try loading it from disk */
1831 char *filename = get_datadir_fname("cached-consensus");
1832 *answer = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
1833 tor_free(filename);
1835 } else if (!strcmp(question, "network-status")) { /* v1 */
1836 routerlist_t *routerlist = router_get_routerlist();
1837 if (!routerlist || !routerlist->routers ||
1838 list_server_status_v1(routerlist->routers, answer, 1) < 0) {
1839 return -1;
1841 } else if (!strcmpstart(question, "extra-info/digest/")) {
1842 question += strlen("extra-info/digest/");
1843 if (strlen(question) == HEX_DIGEST_LEN) {
1844 char d[DIGEST_LEN];
1845 signed_descriptor_t *sd = NULL;
1846 if (base16_decode(d, sizeof(d), question, strlen(question))==0) {
1847 /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
1848 * but I don't want to risk affecting other parts of the code,
1849 * especially since the rules for using our own extrainfo (including
1850 * when it might be freed) are different from those for using one
1851 * we have downloaded. */
1852 if (router_extrainfo_digest_is_me(d))
1853 sd = &(router_get_my_extrainfo()->cache_info);
1854 else
1855 sd = extrainfo_get_by_descriptor_digest(d);
1857 if (sd) {
1858 const char *body = signed_descriptor_get_body(sd);
1859 if (body)
1860 *answer = tor_strndup(body, sd->signed_descriptor_len);
1865 return 0;
1868 /** Allocate and return a description of <b>circ</b>'s current status,
1869 * including its path (if any). */
1870 static char *
1871 circuit_describe_status_for_controller(origin_circuit_t *circ)
1873 char *rv;
1874 smartlist_t *descparts = smartlist_new();
1877 char *vpath = circuit_list_path_for_controller(circ);
1878 if (*vpath) {
1879 smartlist_add(descparts, vpath);
1880 } else {
1881 tor_free(vpath); /* empty path; don't put an extra space in the result */
1886 cpath_build_state_t *build_state = circ->build_state;
1887 smartlist_t *flaglist = smartlist_new();
1888 char *flaglist_joined;
1890 if (build_state->onehop_tunnel)
1891 smartlist_add(flaglist, (void *)"ONEHOP_TUNNEL");
1892 if (build_state->is_internal)
1893 smartlist_add(flaglist, (void *)"IS_INTERNAL");
1894 if (build_state->need_capacity)
1895 smartlist_add(flaglist, (void *)"NEED_CAPACITY");
1896 if (build_state->need_uptime)
1897 smartlist_add(flaglist, (void *)"NEED_UPTIME");
1899 /* Only emit a BUILD_FLAGS argument if it will have a non-empty value. */
1900 if (smartlist_len(flaglist)) {
1901 flaglist_joined = smartlist_join_strings(flaglist, ",", 0, NULL);
1903 smartlist_add_asprintf(descparts, "BUILD_FLAGS=%s", flaglist_joined);
1905 tor_free(flaglist_joined);
1908 smartlist_free(flaglist);
1911 smartlist_add_asprintf(descparts, "PURPOSE=%s",
1912 circuit_purpose_to_controller_string(circ->base_.purpose));
1915 const char *hs_state =
1916 circuit_purpose_to_controller_hs_state_string(circ->base_.purpose);
1918 if (hs_state != NULL) {
1919 smartlist_add_asprintf(descparts, "HS_STATE=%s", hs_state);
1923 if (circ->rend_data != NULL) {
1924 smartlist_add_asprintf(descparts, "REND_QUERY=%s",
1925 circ->rend_data->onion_address);
1929 char tbuf[ISO_TIME_USEC_LEN+1];
1930 format_iso_time_nospace_usec(tbuf, &circ->base_.timestamp_created);
1932 smartlist_add_asprintf(descparts, "TIME_CREATED=%s", tbuf);
1935 rv = smartlist_join_strings(descparts, " ", 0, NULL);
1937 SMARTLIST_FOREACH(descparts, char *, cp, tor_free(cp));
1938 smartlist_free(descparts);
1940 return rv;
1943 /** Implementation helper for GETINFO: knows how to generate summaries of the
1944 * current states of things we send events about. */
1945 static int
1946 getinfo_helper_events(control_connection_t *control_conn,
1947 const char *question, char **answer,
1948 const char **errmsg)
1950 (void) control_conn;
1951 if (!strcmp(question, "circuit-status")) {
1952 circuit_t *circ_;
1953 smartlist_t *status = smartlist_new();
1954 for (circ_ = circuit_get_global_list_(); circ_; circ_ = circ_->next) {
1955 origin_circuit_t *circ;
1956 char *circdesc;
1957 const char *state;
1958 if (! CIRCUIT_IS_ORIGIN(circ_) || circ_->marked_for_close)
1959 continue;
1960 circ = TO_ORIGIN_CIRCUIT(circ_);
1962 if (circ->base_.state == CIRCUIT_STATE_OPEN)
1963 state = "BUILT";
1964 else if (circ->cpath)
1965 state = "EXTENDED";
1966 else
1967 state = "LAUNCHED";
1969 circdesc = circuit_describe_status_for_controller(circ);
1971 smartlist_add_asprintf(status, "%lu %s%s%s",
1972 (unsigned long)circ->global_identifier,
1973 state, *circdesc ? " " : "", circdesc);
1974 tor_free(circdesc);
1976 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1977 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1978 smartlist_free(status);
1979 } else if (!strcmp(question, "stream-status")) {
1980 smartlist_t *conns = get_connection_array();
1981 smartlist_t *status = smartlist_new();
1982 char buf[256];
1983 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1984 const char *state;
1985 entry_connection_t *conn;
1986 circuit_t *circ;
1987 origin_circuit_t *origin_circ = NULL;
1988 if (base_conn->type != CONN_TYPE_AP ||
1989 base_conn->marked_for_close ||
1990 base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
1991 base_conn->state == AP_CONN_STATE_NATD_WAIT)
1992 continue;
1993 conn = TO_ENTRY_CONN(base_conn);
1994 switch (base_conn->state)
1996 case AP_CONN_STATE_CONTROLLER_WAIT:
1997 case AP_CONN_STATE_CIRCUIT_WAIT:
1998 if (conn->socks_request &&
1999 SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
2000 state = "NEWRESOLVE";
2001 else
2002 state = "NEW";
2003 break;
2004 case AP_CONN_STATE_RENDDESC_WAIT:
2005 case AP_CONN_STATE_CONNECT_WAIT:
2006 state = "SENTCONNECT"; break;
2007 case AP_CONN_STATE_RESOLVE_WAIT:
2008 state = "SENTRESOLVE"; break;
2009 case AP_CONN_STATE_OPEN:
2010 state = "SUCCEEDED"; break;
2011 default:
2012 log_warn(LD_BUG, "Asked for stream in unknown state %d",
2013 base_conn->state);
2014 continue;
2016 circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
2017 if (circ && CIRCUIT_IS_ORIGIN(circ))
2018 origin_circ = TO_ORIGIN_CIRCUIT(circ);
2019 write_stream_target_to_buf(conn, buf, sizeof(buf));
2020 smartlist_add_asprintf(status, "%lu %s %lu %s",
2021 (unsigned long) base_conn->global_identifier,state,
2022 origin_circ?
2023 (unsigned long)origin_circ->global_identifier : 0ul,
2024 buf);
2025 } SMARTLIST_FOREACH_END(base_conn);
2026 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
2027 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
2028 smartlist_free(status);
2029 } else if (!strcmp(question, "orconn-status")) {
2030 smartlist_t *conns = get_connection_array();
2031 smartlist_t *status = smartlist_new();
2032 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
2033 const char *state;
2034 char name[128];
2035 or_connection_t *conn;
2036 if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
2037 continue;
2038 conn = TO_OR_CONN(base_conn);
2039 if (conn->base_.state == OR_CONN_STATE_OPEN)
2040 state = "CONNECTED";
2041 else if (conn->nickname)
2042 state = "LAUNCHED";
2043 else
2044 state = "NEW";
2045 orconn_target_get_name(name, sizeof(name), conn);
2046 smartlist_add_asprintf(status, "%s %s", name, state);
2047 } SMARTLIST_FOREACH_END(base_conn);
2048 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
2049 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
2050 smartlist_free(status);
2051 } else if (!strcmpstart(question, "address-mappings/")) {
2052 time_t min_e, max_e;
2053 smartlist_t *mappings;
2054 question += strlen("address-mappings/");
2055 if (!strcmp(question, "all")) {
2056 min_e = 0; max_e = TIME_MAX;
2057 } else if (!strcmp(question, "cache")) {
2058 min_e = 2; max_e = TIME_MAX;
2059 } else if (!strcmp(question, "config")) {
2060 min_e = 0; max_e = 0;
2061 } else if (!strcmp(question, "control")) {
2062 min_e = 1; max_e = 1;
2063 } else {
2064 return 0;
2066 mappings = smartlist_new();
2067 addressmap_get_mappings(mappings, min_e, max_e, 1);
2068 *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
2069 SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
2070 smartlist_free(mappings);
2071 } else if (!strcmpstart(question, "status/")) {
2072 /* Note that status/ is not a catch-all for events; there's only supposed
2073 * to be a status GETINFO if there's a corresponding STATUS event. */
2074 if (!strcmp(question, "status/circuit-established")) {
2075 *answer = tor_strdup(can_complete_circuit ? "1" : "0");
2076 } else if (!strcmp(question, "status/enough-dir-info")) {
2077 *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
2078 } else if (!strcmp(question, "status/good-server-descriptor") ||
2079 !strcmp(question, "status/accepted-server-descriptor")) {
2080 /* They're equivalent for now, until we can figure out how to make
2081 * good-server-descriptor be what we want. See comment in
2082 * control-spec.txt. */
2083 *answer = tor_strdup(directories_have_accepted_server_descriptor()
2084 ? "1" : "0");
2085 } else if (!strcmp(question, "status/reachability-succeeded/or")) {
2086 *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
2087 } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
2088 *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
2089 } else if (!strcmp(question, "status/reachability-succeeded")) {
2090 tor_asprintf(answer, "OR=%d DIR=%d",
2091 check_whether_orport_reachable() ? 1 : 0,
2092 check_whether_dirport_reachable() ? 1 : 0);
2093 } else if (!strcmp(question, "status/bootstrap-phase")) {
2094 *answer = tor_strdup(last_sent_bootstrap_message);
2095 } else if (!strcmpstart(question, "status/version/")) {
2096 int is_server = server_mode(get_options());
2097 networkstatus_t *c = networkstatus_get_latest_consensus();
2098 version_status_t status;
2099 const char *recommended;
2100 if (c) {
2101 recommended = is_server ? c->server_versions : c->client_versions;
2102 status = tor_version_is_obsolete(VERSION, recommended);
2103 } else {
2104 recommended = "?";
2105 status = VS_UNKNOWN;
2108 if (!strcmp(question, "status/version/recommended")) {
2109 *answer = tor_strdup(recommended);
2110 return 0;
2112 if (!strcmp(question, "status/version/current")) {
2113 switch (status)
2115 case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
2116 case VS_OLD: *answer = tor_strdup("obsolete"); break;
2117 case VS_NEW: *answer = tor_strdup("new"); break;
2118 case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
2119 case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
2120 case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
2121 case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
2122 default: tor_fragile_assert();
2124 } else if (!strcmp(question, "status/version/num-versioning") ||
2125 !strcmp(question, "status/version/num-concurring")) {
2126 tor_asprintf(answer, "%d", get_n_authorities(V3_DIRINFO));
2127 log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
2128 "information", question);
2130 } else if (!strcmp(question, "status/clients-seen")) {
2131 char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
2132 if (!bridge_stats) {
2133 *errmsg = "No bridge-client stats available";
2134 return -1;
2136 *answer = bridge_stats;
2137 } else {
2138 return 0;
2141 return 0;
2144 /** Callback function for GETINFO: on a given control connection, try to
2145 * answer the question <b>q</b> and store the newly-allocated answer in
2146 * *<b>a</b>. If an internal error occurs, return -1 and optionally set
2147 * *<b>error_out</b> to point to an error message to be delivered to the
2148 * controller. On success, _or if the key is not recognized_, return 0. Do not
2149 * set <b>a</b> if the key is not recognized.
2151 typedef int (*getinfo_helper_t)(control_connection_t *,
2152 const char *q, char **a,
2153 const char **error_out);
2155 /** A single item for the GETINFO question-to-answer-function table. */
2156 typedef struct getinfo_item_t {
2157 const char *varname; /**< The value (or prefix) of the question. */
2158 getinfo_helper_t fn; /**< The function that knows the answer: NULL if
2159 * this entry is documentation-only. */
2160 const char *desc; /**< Description of the variable. */
2161 int is_prefix; /** Must varname match exactly, or must it be a prefix? */
2162 } getinfo_item_t;
2164 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
2165 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
2166 #define DOC(name, desc) { name, NULL, desc, 0 }
2168 /** Table mapping questions accepted by GETINFO to the functions that know how
2169 * to answer them. */
2170 static const getinfo_item_t getinfo_items[] = {
2171 ITEM("version", misc, "The current version of Tor."),
2172 ITEM("config-file", misc, "Current location of the \"torrc\" file."),
2173 ITEM("config-defaults-file", misc, "Current location of the defaults file."),
2174 ITEM("config-text", misc,
2175 "Return the string that would be written by a saveconf command."),
2176 ITEM("accounting/bytes", accounting,
2177 "Number of bytes read/written so far in the accounting interval."),
2178 ITEM("accounting/bytes-left", accounting,
2179 "Number of bytes left to write/read so far in the accounting interval."),
2180 ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
2181 ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
2182 ITEM("accounting/interval-start", accounting,
2183 "Time when the accounting period starts."),
2184 ITEM("accounting/interval-end", accounting,
2185 "Time when the accounting period ends."),
2186 ITEM("accounting/interval-wake", accounting,
2187 "Time to wake up in this accounting period."),
2188 ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
2189 ITEM("entry-guards", entry_guards,
2190 "Which nodes are we using as entry guards?"),
2191 ITEM("fingerprint", misc, NULL),
2192 PREFIX("config/", config, "Current configuration values."),
2193 DOC("config/names",
2194 "List of configuration options, types, and documentation."),
2195 DOC("config/defaults",
2196 "List of default values for configuration options. "
2197 "See also config/names"),
2198 ITEM("info/names", misc,
2199 "List of GETINFO options, types, and documentation."),
2200 ITEM("events/names", misc,
2201 "Events that the controller can ask for with SETEVENTS."),
2202 ITEM("signal/names", misc, "Signal names recognized by the SIGNAL command"),
2203 ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
2204 PREFIX("desc/id/", dir, "Router descriptors by ID."),
2205 PREFIX("desc/name/", dir, "Router descriptors by nickname."),
2206 ITEM("desc/all-recent", dir,
2207 "All non-expired, non-superseded router descriptors."),
2208 ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
2209 PREFIX("md/id/", dir, "Microdescriptors by ID"),
2210 PREFIX("md/name/", dir, "Microdescriptors by name"),
2211 PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
2212 PREFIX("net/listeners/", listeners, "Bound addresses by type"),
2213 ITEM("ns/all", networkstatus,
2214 "Brief summary of router status (v2 directory format)"),
2215 PREFIX("ns/id/", networkstatus,
2216 "Brief summary of router status by ID (v2 directory format)."),
2217 PREFIX("ns/name/", networkstatus,
2218 "Brief summary of router status by nickname (v2 directory format)."),
2219 PREFIX("ns/purpose/", networkstatus,
2220 "Brief summary of router status by purpose (v2 directory format)."),
2221 ITEM("network-status", dir,
2222 "Brief summary of router status (v1 directory format)"),
2223 ITEM("circuit-status", events, "List of current circuits originating here."),
2224 ITEM("stream-status", events,"List of current streams."),
2225 ITEM("orconn-status", events, "A list of current OR connections."),
2226 ITEM("dormant", misc,
2227 "Is Tor dormant (not building circuits because it's idle)?"),
2228 PREFIX("address-mappings/", events, NULL),
2229 DOC("address-mappings/all", "Current address mappings."),
2230 DOC("address-mappings/cache", "Current cached DNS replies."),
2231 DOC("address-mappings/config",
2232 "Current address mappings from configuration."),
2233 DOC("address-mappings/control", "Current address mappings from controller."),
2234 PREFIX("status/", events, NULL),
2235 DOC("status/circuit-established",
2236 "Whether we think client functionality is working."),
2237 DOC("status/enough-dir-info",
2238 "Whether we have enough up-to-date directory information to build "
2239 "circuits."),
2240 DOC("status/bootstrap-phase",
2241 "The last bootstrap phase status event that Tor sent."),
2242 DOC("status/clients-seen",
2243 "Breakdown of client countries seen by a bridge."),
2244 DOC("status/version/recommended", "List of currently recommended versions."),
2245 DOC("status/version/current", "Status of the current version."),
2246 DOC("status/version/num-versioning", "Number of versioning authorities."),
2247 DOC("status/version/num-concurring",
2248 "Number of versioning authorities agreeing on the status of the "
2249 "current version"),
2250 ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
2251 ITEM("traffic/read", misc,"Bytes read since the process was started."),
2252 ITEM("traffic/written", misc,
2253 "Bytes written since the process was started."),
2254 ITEM("process/pid", misc, "Process id belonging to the main tor process."),
2255 ITEM("process/uid", misc, "User id running the tor process."),
2256 ITEM("process/user", misc,
2257 "Username under which the tor process is running."),
2258 ITEM("process/descriptor-limit", misc, "File descriptor limit."),
2259 ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
2260 PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
2261 PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
2262 PREFIX("dir/status/", dir,
2263 "v2 networkstatus docs as retrieved from a DirPort."),
2264 ITEM("dir/status-vote/current/consensus", dir,
2265 "v3 Networkstatus consensus as retrieved from a DirPort."),
2266 ITEM("exit-policy/default", policies,
2267 "The default value appended to the configured exit policy."),
2268 PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
2269 { NULL, NULL, NULL, 0 }
2272 /** Allocate and return a list of recognized GETINFO options. */
2273 static char *
2274 list_getinfo_options(void)
2276 int i;
2277 smartlist_t *lines = smartlist_new();
2278 char *ans;
2279 for (i = 0; getinfo_items[i].varname; ++i) {
2280 if (!getinfo_items[i].desc)
2281 continue;
2283 smartlist_add_asprintf(lines, "%s%s -- %s\n",
2284 getinfo_items[i].varname,
2285 getinfo_items[i].is_prefix ? "*" : "",
2286 getinfo_items[i].desc);
2288 smartlist_sort_strings(lines);
2290 ans = smartlist_join_strings(lines, "", 0, NULL);
2291 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
2292 smartlist_free(lines);
2294 return ans;
2297 /** Lookup the 'getinfo' entry <b>question</b>, and return
2298 * the answer in <b>*answer</b> (or NULL if key not recognized).
2299 * Return 0 if success or unrecognized, or -1 if recognized but
2300 * internal error. */
2301 static int
2302 handle_getinfo_helper(control_connection_t *control_conn,
2303 const char *question, char **answer,
2304 const char **err_out)
2306 int i;
2307 *answer = NULL; /* unrecognized key by default */
2309 for (i = 0; getinfo_items[i].varname; ++i) {
2310 int match;
2311 if (getinfo_items[i].is_prefix)
2312 match = !strcmpstart(question, getinfo_items[i].varname);
2313 else
2314 match = !strcmp(question, getinfo_items[i].varname);
2315 if (match) {
2316 tor_assert(getinfo_items[i].fn);
2317 return getinfo_items[i].fn(control_conn, question, answer, err_out);
2321 return 0; /* unrecognized */
2324 /** Called when we receive a GETINFO command. Try to fetch all requested
2325 * information, and reply with information or error message. */
2326 static int
2327 handle_control_getinfo(control_connection_t *conn, uint32_t len,
2328 const char *body)
2330 smartlist_t *questions = smartlist_new();
2331 smartlist_t *answers = smartlist_new();
2332 smartlist_t *unrecognized = smartlist_new();
2333 char *msg = NULL, *ans = NULL;
2334 int i;
2335 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
2337 smartlist_split_string(questions, body, " ",
2338 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2339 SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
2340 const char *errmsg = NULL;
2341 if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
2342 if (!errmsg)
2343 errmsg = "Internal error";
2344 connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
2345 goto done;
2347 if (!ans) {
2348 smartlist_add(unrecognized, (char*)q);
2349 } else {
2350 smartlist_add(answers, tor_strdup(q));
2351 smartlist_add(answers, ans);
2353 } SMARTLIST_FOREACH_END(q);
2354 if (smartlist_len(unrecognized)) {
2355 for (i=0; i < smartlist_len(unrecognized)-1; ++i)
2356 connection_printf_to_buf(conn,
2357 "552-Unrecognized key \"%s\"\r\n",
2358 (char*)smartlist_get(unrecognized, i));
2359 connection_printf_to_buf(conn,
2360 "552 Unrecognized key \"%s\"\r\n",
2361 (char*)smartlist_get(unrecognized, i));
2362 goto done;
2365 for (i = 0; i < smartlist_len(answers); i += 2) {
2366 char *k = smartlist_get(answers, i);
2367 char *v = smartlist_get(answers, i+1);
2368 if (!strchr(v, '\n') && !strchr(v, '\r')) {
2369 connection_printf_to_buf(conn, "250-%s=", k);
2370 connection_write_str_to_buf(v, conn);
2371 connection_write_str_to_buf("\r\n", conn);
2372 } else {
2373 char *esc = NULL;
2374 size_t esc_len;
2375 esc_len = write_escaped_data(v, strlen(v), &esc);
2376 connection_printf_to_buf(conn, "250+%s=\r\n", k);
2377 connection_write_to_buf(esc, esc_len, TO_CONN(conn));
2378 tor_free(esc);
2381 connection_write_str_to_buf("250 OK\r\n", conn);
2383 done:
2384 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
2385 smartlist_free(answers);
2386 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
2387 smartlist_free(questions);
2388 smartlist_free(unrecognized);
2389 tor_free(msg);
2391 return 0;
2394 /** Given a string, convert it to a circuit purpose. */
2395 static uint8_t
2396 circuit_purpose_from_string(const char *string)
2398 if (!strcasecmpstart(string, "purpose="))
2399 string += strlen("purpose=");
2401 if (!strcasecmp(string, "general"))
2402 return CIRCUIT_PURPOSE_C_GENERAL;
2403 else if (!strcasecmp(string, "controller"))
2404 return CIRCUIT_PURPOSE_CONTROLLER;
2405 else
2406 return CIRCUIT_PURPOSE_UNKNOWN;
2409 /** Return a newly allocated smartlist containing the arguments to the command
2410 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
2411 * or if <b>max_args</b> is nonnegative and there are more than
2412 * <b>max_args</b> arguments, send a 512 error to the controller, using
2413 * <b>command</b> as the command name in the error message. */
2414 static smartlist_t *
2415 getargs_helper(const char *command, control_connection_t *conn,
2416 const char *body, int min_args, int max_args)
2418 smartlist_t *args = smartlist_new();
2419 smartlist_split_string(args, body, " ",
2420 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2421 if (smartlist_len(args) < min_args) {
2422 connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
2423 goto err;
2424 } else if (max_args >= 0 && smartlist_len(args) > max_args) {
2425 connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
2426 goto err;
2428 return args;
2429 err:
2430 SMARTLIST_FOREACH(args, char *, s, tor_free(s));
2431 smartlist_free(args);
2432 return NULL;
2435 /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
2436 * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
2437 * such element exists. */
2438 static const char *
2439 find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
2441 int i;
2442 for (i = start_at; i < smartlist_len(sl); ++i) {
2443 const char *elt = smartlist_get(sl, i);
2444 if (!strcasecmpstart(elt, prefix))
2445 return elt;
2447 return NULL;
2450 /** Helper. Return true iff s is an argument that we should treat as a
2451 * key-value pair. */
2452 static int
2453 is_keyval_pair(const char *s)
2455 /* An argument is a key-value pair if it has an =, and it isn't of the form
2456 * $fingeprint=name */
2457 return strchr(s, '=') && s[0] != '$';
2460 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
2461 * circuit, and report success or failure. */
2462 static int
2463 handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
2464 const char *body)
2466 smartlist_t *router_nicknames=NULL, *nodes=NULL;
2467 origin_circuit_t *circ = NULL;
2468 int zero_circ;
2469 uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
2470 smartlist_t *args;
2471 (void) len;
2473 router_nicknames = smartlist_new();
2475 args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
2476 if (!args)
2477 goto done;
2479 zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
2481 if (zero_circ) {
2482 const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
2484 if (purp) {
2485 intended_purpose = circuit_purpose_from_string(purp);
2486 if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
2487 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
2488 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2489 smartlist_free(args);
2490 goto done;
2494 if ((smartlist_len(args) == 1) ||
2495 (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
2496 // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
2497 circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
2498 if (!circ) {
2499 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
2500 } else {
2501 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
2502 (unsigned long)circ->global_identifier);
2504 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2505 smartlist_free(args);
2506 goto done;
2508 // "EXTENDCIRCUIT 0 router1,router2" ||
2509 // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
2512 if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
2513 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2514 (char*)smartlist_get(args, 0));
2515 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2516 smartlist_free(args);
2517 goto done;
2520 smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
2522 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2523 smartlist_free(args);
2525 nodes = smartlist_new();
2526 SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
2527 const node_t *node = node_get_by_nickname(n, 1);
2528 if (!node) {
2529 connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
2530 goto done;
2532 if (!node_has_descriptor(node)) {
2533 connection_printf_to_buf(conn, "552 descriptor for \"%s\"\r\n", n);
2534 goto done;
2536 smartlist_add(nodes, (void*)node);
2537 } SMARTLIST_FOREACH_END(n);
2538 if (!smartlist_len(nodes)) {
2539 connection_write_str_to_buf("512 No router names provided\r\n", conn);
2540 goto done;
2543 if (zero_circ) {
2544 /* start a new circuit */
2545 circ = origin_circuit_init(intended_purpose, 0);
2548 /* now circ refers to something that is ready to be extended */
2549 SMARTLIST_FOREACH(nodes, const node_t *, node,
2551 extend_info_t *info = extend_info_from_node(node, 0);
2552 tor_assert(info); /* True, since node_has_descriptor(node) == true */
2553 circuit_append_new_exit(circ, info);
2554 extend_info_free(info);
2557 /* now that we've populated the cpath, start extending */
2558 if (zero_circ) {
2559 int err_reason = 0;
2560 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
2561 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2562 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
2563 goto done;
2565 } else {
2566 if (circ->base_.state == CIRCUIT_STATE_OPEN) {
2567 int err_reason = 0;
2568 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
2569 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
2570 log_info(LD_CONTROL,
2571 "send_next_onion_skin failed; circuit marked for closing.");
2572 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2573 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
2574 goto done;
2579 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
2580 (unsigned long)circ->global_identifier);
2581 if (zero_circ) /* send a 'launched' event, for completeness */
2582 control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
2583 done:
2584 SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
2585 smartlist_free(router_nicknames);
2586 smartlist_free(nodes);
2587 return 0;
2590 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
2591 * circuit and it's a valid purpose, change it. */
2592 static int
2593 handle_control_setcircuitpurpose(control_connection_t *conn,
2594 uint32_t len, const char *body)
2596 origin_circuit_t *circ = NULL;
2597 uint8_t new_purpose;
2598 smartlist_t *args;
2599 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
2601 args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
2602 if (!args)
2603 goto done;
2605 if (!(circ = get_circ(smartlist_get(args,0)))) {
2606 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2607 (char*)smartlist_get(args, 0));
2608 goto done;
2612 const char *purp = find_element_starting_with(args,1,"PURPOSE=");
2613 if (!purp) {
2614 connection_write_str_to_buf("552 No purpose given\r\n", conn);
2615 goto done;
2617 new_purpose = circuit_purpose_from_string(purp);
2618 if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
2619 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
2620 goto done;
2624 circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
2625 connection_write_str_to_buf("250 OK\r\n", conn);
2627 done:
2628 if (args) {
2629 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2630 smartlist_free(args);
2632 return 0;
2635 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
2636 * stream, and report success or failure. */
2637 static int
2638 handle_control_attachstream(control_connection_t *conn, uint32_t len,
2639 const char *body)
2641 entry_connection_t *ap_conn = NULL;
2642 origin_circuit_t *circ = NULL;
2643 int zero_circ;
2644 smartlist_t *args;
2645 crypt_path_t *cpath=NULL;
2646 int hop=0, hop_line_ok=1;
2647 (void) len;
2649 args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
2650 if (!args)
2651 return 0;
2653 zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
2655 if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
2656 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2657 (char*)smartlist_get(args, 0));
2658 } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
2659 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2660 (char*)smartlist_get(args, 1));
2661 } else if (circ) {
2662 const char *hopstring = find_element_starting_with(args,2,"HOP=");
2663 if (hopstring) {
2664 hopstring += strlen("HOP=");
2665 hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
2666 &hop_line_ok, NULL);
2667 if (!hop_line_ok) { /* broken hop line */
2668 connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
2672 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2673 smartlist_free(args);
2674 if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
2675 return 0;
2677 if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
2678 ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
2679 ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
2680 connection_write_str_to_buf(
2681 "555 Connection is not managed by controller.\r\n",
2682 conn);
2683 return 0;
2686 /* Do we need to detach it first? */
2687 if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
2688 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
2689 circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
2690 connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
2691 /* Un-mark it as ending, since we're going to reuse it. */
2692 edge_conn->edge_has_sent_end = 0;
2693 edge_conn->end_reason = 0;
2694 if (tmpcirc)
2695 circuit_detach_stream(tmpcirc, edge_conn);
2696 TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
2699 if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
2700 connection_write_str_to_buf(
2701 "551 Can't attach stream to non-open origin circuit\r\n",
2702 conn);
2703 return 0;
2705 /* Is this a single hop circuit? */
2706 if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
2707 const node_t *node = NULL;
2708 char *exit_digest;
2709 if (circ->build_state &&
2710 circ->build_state->chosen_exit &&
2711 !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
2712 exit_digest = circ->build_state->chosen_exit->identity_digest;
2713 node = node_get_by_id(exit_digest);
2715 /* Do both the client and relay allow one-hop exit circuits? */
2716 if (!node ||
2717 !node_allows_single_hop_exits(node) ||
2718 !get_options()->AllowSingleHopCircuits) {
2719 connection_write_str_to_buf(
2720 "551 Can't attach stream to this one-hop circuit.\r\n", conn);
2721 return 0;
2723 ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
2726 if (circ && hop>0) {
2727 /* find this hop in the circuit, and set cpath */
2728 cpath = circuit_get_cpath_hop(circ, hop);
2729 if (!cpath) {
2730 connection_printf_to_buf(conn,
2731 "551 Circuit doesn't have %d hops.\r\n", hop);
2732 return 0;
2735 if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
2736 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
2737 return 0;
2739 send_control_done(conn);
2740 return 0;
2743 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
2744 * descriptor, and report success or failure. */
2745 static int
2746 handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
2747 const char *body)
2749 char *desc;
2750 const char *msg=NULL;
2751 uint8_t purpose = ROUTER_PURPOSE_GENERAL;
2752 int cache = 0; /* eventually, we may switch this to 1 */
2754 char *cp = memchr(body, '\n', len);
2755 smartlist_t *args = smartlist_new();
2756 tor_assert(cp);
2757 *cp++ = '\0';
2759 smartlist_split_string(args, body, " ",
2760 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2761 SMARTLIST_FOREACH_BEGIN(args, char *, option) {
2762 if (!strcasecmpstart(option, "purpose=")) {
2763 option += strlen("purpose=");
2764 purpose = router_purpose_from_string(option);
2765 if (purpose == ROUTER_PURPOSE_UNKNOWN) {
2766 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
2767 option);
2768 goto done;
2770 } else if (!strcasecmpstart(option, "cache=")) {
2771 option += strlen("cache=");
2772 if (!strcasecmp(option, "no"))
2773 cache = 0;
2774 else if (!strcasecmp(option, "yes"))
2775 cache = 1;
2776 else {
2777 connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
2778 option);
2779 goto done;
2781 } else { /* unrecognized argument? */
2782 connection_printf_to_buf(conn,
2783 "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
2784 goto done;
2786 } SMARTLIST_FOREACH_END(option);
2788 read_escaped_data(cp, len-(cp-body), &desc);
2790 switch (router_load_single_router(desc, purpose, cache, &msg)) {
2791 case -1:
2792 if (!msg) msg = "Could not parse descriptor";
2793 connection_printf_to_buf(conn, "554 %s\r\n", msg);
2794 break;
2795 case 0:
2796 if (!msg) msg = "Descriptor not added";
2797 connection_printf_to_buf(conn, "251 %s\r\n",msg);
2798 break;
2799 case 1:
2800 send_control_done(conn);
2801 break;
2804 tor_free(desc);
2805 done:
2806 SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
2807 smartlist_free(args);
2808 return 0;
2811 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
2812 * address of the named AP stream, and report success or failure. */
2813 static int
2814 handle_control_redirectstream(control_connection_t *conn, uint32_t len,
2815 const char *body)
2817 entry_connection_t *ap_conn = NULL;
2818 char *new_addr = NULL;
2819 uint16_t new_port = 0;
2820 smartlist_t *args;
2821 (void) len;
2823 args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
2824 if (!args)
2825 return 0;
2827 if (!(ap_conn = get_stream(smartlist_get(args, 0)))
2828 || !ap_conn->socks_request) {
2829 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2830 (char*)smartlist_get(args, 0));
2831 } else {
2832 int ok = 1;
2833 if (smartlist_len(args) > 2) { /* they included a port too */
2834 new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
2835 10, 1, 65535, &ok, NULL);
2837 if (!ok) {
2838 connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
2839 (char*)smartlist_get(args, 2));
2840 } else {
2841 new_addr = tor_strdup(smartlist_get(args, 1));
2845 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2846 smartlist_free(args);
2847 if (!new_addr)
2848 return 0;
2850 strlcpy(ap_conn->socks_request->address, new_addr,
2851 sizeof(ap_conn->socks_request->address));
2852 if (new_port)
2853 ap_conn->socks_request->port = new_port;
2854 tor_free(new_addr);
2855 send_control_done(conn);
2856 return 0;
2859 /** Called when we get a CLOSESTREAM command; try to close the named stream
2860 * and report success or failure. */
2861 static int
2862 handle_control_closestream(control_connection_t *conn, uint32_t len,
2863 const char *body)
2865 entry_connection_t *ap_conn=NULL;
2866 uint8_t reason=0;
2867 smartlist_t *args;
2868 int ok;
2869 (void) len;
2871 args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
2872 if (!args)
2873 return 0;
2875 else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
2876 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2877 (char*)smartlist_get(args, 0));
2878 else {
2879 reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
2880 &ok, NULL);
2881 if (!ok) {
2882 connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
2883 (char*)smartlist_get(args, 1));
2884 ap_conn = NULL;
2887 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2888 smartlist_free(args);
2889 if (!ap_conn)
2890 return 0;
2892 connection_mark_unattached_ap(ap_conn, reason);
2893 send_control_done(conn);
2894 return 0;
2897 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
2898 * and report success or failure. */
2899 static int
2900 handle_control_closecircuit(control_connection_t *conn, uint32_t len,
2901 const char *body)
2903 origin_circuit_t *circ = NULL;
2904 int safe = 0;
2905 smartlist_t *args;
2906 (void) len;
2908 args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
2909 if (!args)
2910 return 0;
2912 if (!(circ=get_circ(smartlist_get(args, 0))))
2913 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2914 (char*)smartlist_get(args, 0));
2915 else {
2916 int i;
2917 for (i=1; i < smartlist_len(args); ++i) {
2918 if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
2919 safe = 1;
2920 else
2921 log_info(LD_CONTROL, "Skipping unknown option %s",
2922 (char*)smartlist_get(args,i));
2925 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2926 smartlist_free(args);
2927 if (!circ)
2928 return 0;
2930 if (!safe || !circ->p_streams) {
2931 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
2934 send_control_done(conn);
2935 return 0;
2938 /** Called when we get a RESOLVE command: start trying to resolve
2939 * the listed addresses. */
2940 static int
2941 handle_control_resolve(control_connection_t *conn, uint32_t len,
2942 const char *body)
2944 smartlist_t *args, *failed;
2945 int is_reverse = 0;
2946 (void) len; /* body is nul-terminated; it's safe to ignore the length */
2948 if (!(conn->event_mask & ((uint32_t)1L<<EVENT_ADDRMAP))) {
2949 log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
2950 "isn't listening for ADDRMAP events. It probably won't see "
2951 "the answer.");
2953 args = smartlist_new();
2954 smartlist_split_string(args, body, " ",
2955 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2957 const char *modearg = find_element_starting_with(args, 0, "mode=");
2958 if (modearg && !strcasecmp(modearg, "mode=reverse"))
2959 is_reverse = 1;
2961 failed = smartlist_new();
2962 SMARTLIST_FOREACH(args, const char *, arg, {
2963 if (!is_keyval_pair(arg)) {
2964 if (dnsserv_launch_request(arg, is_reverse, conn)<0)
2965 smartlist_add(failed, (char*)arg);
2969 send_control_done(conn);
2970 SMARTLIST_FOREACH(failed, const char *, arg, {
2971 control_event_address_mapped(arg, arg, time(NULL),
2972 "internal", 0);
2975 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2976 smartlist_free(args);
2977 smartlist_free(failed);
2978 return 0;
2981 /** Called when we get a PROTOCOLINFO command: send back a reply. */
2982 static int
2983 handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
2984 const char *body)
2986 const char *bad_arg = NULL;
2987 smartlist_t *args;
2988 (void)len;
2990 conn->have_sent_protocolinfo = 1;
2991 args = smartlist_new();
2992 smartlist_split_string(args, body, " ",
2993 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2994 SMARTLIST_FOREACH(args, const char *, arg, {
2995 int ok;
2996 tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
2997 if (!ok) {
2998 bad_arg = arg;
2999 break;
3002 if (bad_arg) {
3003 connection_printf_to_buf(conn, "513 No such version %s\r\n",
3004 escaped(bad_arg));
3005 /* Don't tolerate bad arguments when not authenticated. */
3006 if (!STATE_IS_OPEN(TO_CONN(conn)->state))
3007 connection_mark_for_close(TO_CONN(conn));
3008 goto done;
3009 } else {
3010 const or_options_t *options = get_options();
3011 int cookies = options->CookieAuthentication;
3012 char *cfile = get_cookie_file();
3013 char *abs_cfile;
3014 char *esc_cfile;
3015 char *methods;
3016 abs_cfile = make_path_absolute(cfile);
3017 esc_cfile = esc_for_log(abs_cfile);
3019 int passwd = (options->HashedControlPassword != NULL ||
3020 options->HashedControlSessionPassword != NULL);
3021 smartlist_t *mlist = smartlist_new();
3022 if (cookies) {
3023 smartlist_add(mlist, (char*)"COOKIE");
3024 smartlist_add(mlist, (char*)"SAFECOOKIE");
3026 if (passwd)
3027 smartlist_add(mlist, (char*)"HASHEDPASSWORD");
3028 if (!cookies && !passwd)
3029 smartlist_add(mlist, (char*)"NULL");
3030 methods = smartlist_join_strings(mlist, ",", 0, NULL);
3031 smartlist_free(mlist);
3034 connection_printf_to_buf(conn,
3035 "250-PROTOCOLINFO 1\r\n"
3036 "250-AUTH METHODS=%s%s%s\r\n"
3037 "250-VERSION Tor=%s\r\n"
3038 "250 OK\r\n",
3039 methods,
3040 cookies?" COOKIEFILE=":"",
3041 cookies?esc_cfile:"",
3042 escaped(VERSION));
3043 tor_free(methods);
3044 tor_free(cfile);
3045 tor_free(abs_cfile);
3046 tor_free(esc_cfile);
3048 done:
3049 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3050 smartlist_free(args);
3051 return 0;
3054 /** Called when we get an AUTHCHALLENGE command. */
3055 static int
3056 handle_control_authchallenge(control_connection_t *conn, uint32_t len,
3057 const char *body)
3059 const char *cp = body;
3060 char *client_nonce;
3061 size_t client_nonce_len;
3062 char server_hash[DIGEST256_LEN];
3063 char server_hash_encoded[HEX_DIGEST256_LEN+1];
3064 char server_nonce[SAFECOOKIE_SERVER_NONCE_LEN];
3065 char server_nonce_encoded[(2*SAFECOOKIE_SERVER_NONCE_LEN) + 1];
3067 cp += strspn(cp, " \t\n\r");
3068 if (!strcasecmpstart(cp, "SAFECOOKIE")) {
3069 cp += strlen("SAFECOOKIE");
3070 } else {
3071 connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
3072 "authentication\r\n", conn);
3073 connection_mark_for_close(TO_CONN(conn));
3074 return -1;
3077 if (!authentication_cookie_is_set) {
3078 connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
3079 conn);
3080 connection_mark_for_close(TO_CONN(conn));
3081 return -1;
3084 cp += strspn(cp, " \t\n\r");
3085 if (*cp == '"') {
3086 const char *newcp =
3087 decode_escaped_string(cp, len - (cp - body),
3088 &client_nonce, &client_nonce_len);
3089 if (newcp == NULL) {
3090 connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
3091 conn);
3092 connection_mark_for_close(TO_CONN(conn));
3093 return -1;
3095 cp = newcp;
3096 } else {
3097 size_t client_nonce_encoded_len = strspn(cp, "0123456789ABCDEFabcdef");
3099 client_nonce_len = client_nonce_encoded_len / 2;
3100 client_nonce = tor_malloc_zero(client_nonce_len);
3102 if (base16_decode(client_nonce, client_nonce_len,
3103 cp, client_nonce_encoded_len) < 0) {
3104 connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
3105 conn);
3106 connection_mark_for_close(TO_CONN(conn));
3107 tor_free(client_nonce);
3108 return -1;
3111 cp += client_nonce_encoded_len;
3114 cp += strspn(cp, " \t\n\r");
3115 if (*cp != '\0' ||
3116 cp != body + len) {
3117 connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
3118 conn);
3119 connection_mark_for_close(TO_CONN(conn));
3120 tor_free(client_nonce);
3121 return -1;
3124 tor_assert(!crypto_rand(server_nonce, SAFECOOKIE_SERVER_NONCE_LEN));
3126 /* Now compute and send the server-to-controller response, and the
3127 * server's nonce. */
3128 tor_assert(authentication_cookie != NULL);
3131 size_t tmp_len = (AUTHENTICATION_COOKIE_LEN +
3132 client_nonce_len +
3133 SAFECOOKIE_SERVER_NONCE_LEN);
3134 char *tmp = tor_malloc_zero(tmp_len);
3135 char *client_hash = tor_malloc_zero(DIGEST256_LEN);
3136 memcpy(tmp, authentication_cookie, AUTHENTICATION_COOKIE_LEN);
3137 memcpy(tmp + AUTHENTICATION_COOKIE_LEN, client_nonce, client_nonce_len);
3138 memcpy(tmp + AUTHENTICATION_COOKIE_LEN + client_nonce_len,
3139 server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
3141 crypto_hmac_sha256(server_hash,
3142 SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT,
3143 strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT),
3144 tmp,
3145 tmp_len);
3147 crypto_hmac_sha256(client_hash,
3148 SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT,
3149 strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT),
3150 tmp,
3151 tmp_len);
3153 conn->safecookie_client_hash = client_hash;
3155 tor_free(tmp);
3158 base16_encode(server_hash_encoded, sizeof(server_hash_encoded),
3159 server_hash, sizeof(server_hash));
3160 base16_encode(server_nonce_encoded, sizeof(server_nonce_encoded),
3161 server_nonce, sizeof(server_nonce));
3163 connection_printf_to_buf(conn,
3164 "250 AUTHCHALLENGE SERVERHASH=%s "
3165 "SERVERNONCE=%s\r\n",
3166 server_hash_encoded,
3167 server_nonce_encoded);
3169 tor_free(client_nonce);
3170 return 0;
3173 /** Called when we get a USEFEATURE command: parse the feature list, and
3174 * set up the control_connection's options properly. */
3175 static int
3176 handle_control_usefeature(control_connection_t *conn,
3177 uint32_t len,
3178 const char *body)
3180 smartlist_t *args;
3181 int bad = 0;
3182 (void) len; /* body is nul-terminated; it's safe to ignore the length */
3183 args = smartlist_new();
3184 smartlist_split_string(args, body, " ",
3185 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3186 SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
3187 if (!strcasecmp(arg, "VERBOSE_NAMES"))
3189 else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
3191 else {
3192 connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
3193 arg);
3194 bad = 1;
3195 break;
3197 } SMARTLIST_FOREACH_END(arg);
3199 if (!bad) {
3200 send_control_done(conn);
3203 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3204 smartlist_free(args);
3205 return 0;
3208 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
3210 connection_control_finished_flushing(control_connection_t *conn)
3212 tor_assert(conn);
3213 return 0;
3216 /** Called when <b>conn</b> has gotten its socket closed. */
3218 connection_control_reached_eof(control_connection_t *conn)
3220 tor_assert(conn);
3222 log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
3223 connection_mark_for_close(TO_CONN(conn));
3224 return 0;
3227 /** Shut down this Tor instance in the same way that SIGINT would, but
3228 * with a log message appropriate for the loss of an owning controller. */
3229 static void
3230 lost_owning_controller(const char *owner_type, const char *loss_manner)
3232 int shutdown_slowly = server_mode(get_options());
3234 log_notice(LD_CONTROL, "Owning controller %s has %s -- %s.",
3235 owner_type, loss_manner,
3236 shutdown_slowly ? "shutting down" : "exiting now");
3238 /* XXXX Perhaps this chunk of code should be a separate function,
3239 * called here and by process_signal(SIGINT). */
3241 if (!shutdown_slowly) {
3242 tor_cleanup();
3243 exit(0);
3245 /* XXXX This will close all listening sockets except control-port
3246 * listeners. Perhaps we should close those too. */
3247 hibernate_begin_shutdown();
3250 /** Called when <b>conn</b> is being freed. */
3251 void
3252 connection_control_closed(control_connection_t *conn)
3254 tor_assert(conn);
3256 conn->event_mask = 0;
3257 control_update_global_event_mask();
3259 if (conn->is_owning_control_connection) {
3260 lost_owning_controller("connection", "closed");
3264 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
3265 * stage of the protocol. */
3266 static int
3267 is_valid_initial_command(control_connection_t *conn, const char *cmd)
3269 if (conn->base_.state == CONTROL_CONN_STATE_OPEN)
3270 return 1;
3271 if (!strcasecmp(cmd, "PROTOCOLINFO"))
3272 return (!conn->have_sent_protocolinfo &&
3273 conn->safecookie_client_hash == NULL);
3274 if (!strcasecmp(cmd, "AUTHCHALLENGE"))
3275 return (conn->safecookie_client_hash == NULL);
3276 if (!strcasecmp(cmd, "AUTHENTICATE") ||
3277 !strcasecmp(cmd, "QUIT"))
3278 return 1;
3279 return 0;
3282 /** Do not accept any control command of more than 1MB in length. Anything
3283 * that needs to be anywhere near this long probably means that one of our
3284 * interfaces is broken. */
3285 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
3287 /** Wrapper around peek_(evbuffer|buf)_has_control0 command: presents the same
3288 * interface as those underlying functions, but takes a connection_t intead of
3289 * an evbuffer or a buf_t.
3291 static int
3292 peek_connection_has_control0_command(connection_t *conn)
3294 IF_HAS_BUFFEREVENT(conn, {
3295 struct evbuffer *input = bufferevent_get_input(conn->bufev);
3296 return peek_evbuffer_has_control0_command(input);
3297 }) ELSE_IF_NO_BUFFEREVENT {
3298 return peek_buf_has_control0_command(conn->inbuf);
3302 /** Called when data has arrived on a v1 control connection: Try to fetch
3303 * commands from conn->inbuf, and execute them.
3306 connection_control_process_inbuf(control_connection_t *conn)
3308 size_t data_len;
3309 uint32_t cmd_data_len;
3310 int cmd_len;
3311 char *args;
3313 tor_assert(conn);
3314 tor_assert(conn->base_.state == CONTROL_CONN_STATE_OPEN ||
3315 conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH);
3317 if (!conn->incoming_cmd) {
3318 conn->incoming_cmd = tor_malloc(1024);
3319 conn->incoming_cmd_len = 1024;
3320 conn->incoming_cmd_cur_len = 0;
3323 if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
3324 peek_connection_has_control0_command(TO_CONN(conn))) {
3325 /* Detect v0 commands and send a "no more v0" message. */
3326 size_t body_len;
3327 char buf[128];
3328 set_uint16(buf+2, htons(0x0000)); /* type == error */
3329 set_uint16(buf+4, htons(0x0001)); /* code == internal error */
3330 strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
3331 "and later; upgrade your controller.",
3332 sizeof(buf)-6);
3333 body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
3334 set_uint16(buf+0, htons(body_len));
3335 connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
3337 connection_mark_and_flush(TO_CONN(conn));
3338 return 0;
3341 again:
3342 while (1) {
3343 size_t last_idx;
3344 int r;
3345 /* First, fetch a line. */
3346 do {
3347 data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
3348 r = connection_fetch_from_buf_line(TO_CONN(conn),
3349 conn->incoming_cmd+conn->incoming_cmd_cur_len,
3350 &data_len);
3351 if (r == 0)
3352 /* Line not all here yet. Wait. */
3353 return 0;
3354 else if (r == -1) {
3355 if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
3356 connection_write_str_to_buf("500 Line too long.\r\n", conn);
3357 connection_stop_reading(TO_CONN(conn));
3358 connection_mark_and_flush(TO_CONN(conn));
3360 while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
3361 conn->incoming_cmd_len *= 2;
3362 conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
3363 conn->incoming_cmd_len);
3365 } while (r != 1);
3367 tor_assert(data_len);
3369 last_idx = conn->incoming_cmd_cur_len;
3370 conn->incoming_cmd_cur_len += (int)data_len;
3372 /* We have appended a line to incoming_cmd. Is the command done? */
3373 if (last_idx == 0 && *conn->incoming_cmd != '+')
3374 /* One line command, didn't start with '+'. */
3375 break;
3376 /* XXXX this code duplication is kind of dumb. */
3377 if (last_idx+3 == conn->incoming_cmd_cur_len &&
3378 tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
3379 /* Just appended ".\r\n"; we're done. Remove it. */
3380 conn->incoming_cmd[last_idx] = '\0';
3381 conn->incoming_cmd_cur_len -= 3;
3382 break;
3383 } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
3384 tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
3385 /* Just appended ".\n"; we're done. Remove it. */
3386 conn->incoming_cmd[last_idx] = '\0';
3387 conn->incoming_cmd_cur_len -= 2;
3388 break;
3390 /* Otherwise, read another line. */
3392 data_len = conn->incoming_cmd_cur_len;
3393 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
3394 * recognize it.
3396 cmd_len = 0;
3397 while ((size_t)cmd_len < data_len
3398 && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
3399 ++cmd_len;
3401 conn->incoming_cmd[cmd_len]='\0';
3402 args = conn->incoming_cmd+cmd_len+1;
3403 tor_assert(data_len>(size_t)cmd_len);
3404 data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
3405 while (TOR_ISSPACE(*args)) {
3406 ++args;
3407 --data_len;
3410 /* If the connection is already closing, ignore further commands */
3411 if (TO_CONN(conn)->marked_for_close) {
3412 return 0;
3415 /* Otherwise, Quit is always valid. */
3416 if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
3417 connection_write_str_to_buf("250 closing connection\r\n", conn);
3418 connection_mark_and_flush(TO_CONN(conn));
3419 return 0;
3422 if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
3423 !is_valid_initial_command(conn, conn->incoming_cmd)) {
3424 connection_write_str_to_buf("514 Authentication required.\r\n", conn);
3425 connection_mark_for_close(TO_CONN(conn));
3426 return 0;
3429 if (data_len >= UINT32_MAX) {
3430 connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
3431 connection_mark_for_close(TO_CONN(conn));
3432 return 0;
3435 /* XXXX Why is this not implemented as a table like the GETINFO
3436 * items are? Even handling the plus signs at the beginnings of
3437 * commands wouldn't be very hard with proper macros. */
3438 cmd_data_len = (uint32_t)data_len;
3439 if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
3440 if (handle_control_setconf(conn, cmd_data_len, args))
3441 return -1;
3442 } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
3443 if (handle_control_resetconf(conn, cmd_data_len, args))
3444 return -1;
3445 } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
3446 if (handle_control_getconf(conn, cmd_data_len, args))
3447 return -1;
3448 } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
3449 if (handle_control_loadconf(conn, cmd_data_len, args))
3450 return -1;
3451 } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
3452 if (handle_control_setevents(conn, cmd_data_len, args))
3453 return -1;
3454 } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
3455 if (handle_control_authenticate(conn, cmd_data_len, args))
3456 return -1;
3457 } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
3458 if (handle_control_saveconf(conn, cmd_data_len, args))
3459 return -1;
3460 } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
3461 if (handle_control_signal(conn, cmd_data_len, args))
3462 return -1;
3463 } else if (!strcasecmp(conn->incoming_cmd, "TAKEOWNERSHIP")) {
3464 if (handle_control_takeownership(conn, cmd_data_len, args))
3465 return -1;
3466 } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
3467 if (handle_control_mapaddress(conn, cmd_data_len, args))
3468 return -1;
3469 } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
3470 if (handle_control_getinfo(conn, cmd_data_len, args))
3471 return -1;
3472 } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
3473 if (handle_control_extendcircuit(conn, cmd_data_len, args))
3474 return -1;
3475 } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
3476 if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
3477 return -1;
3478 } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
3479 connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
3480 } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
3481 if (handle_control_attachstream(conn, cmd_data_len, args))
3482 return -1;
3483 } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
3484 if (handle_control_postdescriptor(conn, cmd_data_len, args))
3485 return -1;
3486 } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
3487 if (handle_control_redirectstream(conn, cmd_data_len, args))
3488 return -1;
3489 } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
3490 if (handle_control_closestream(conn, cmd_data_len, args))
3491 return -1;
3492 } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
3493 if (handle_control_closecircuit(conn, cmd_data_len, args))
3494 return -1;
3495 } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
3496 if (handle_control_usefeature(conn, cmd_data_len, args))
3497 return -1;
3498 } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
3499 if (handle_control_resolve(conn, cmd_data_len, args))
3500 return -1;
3501 } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
3502 if (handle_control_protocolinfo(conn, cmd_data_len, args))
3503 return -1;
3504 } else if (!strcasecmp(conn->incoming_cmd, "AUTHCHALLENGE")) {
3505 if (handle_control_authchallenge(conn, cmd_data_len, args))
3506 return -1;
3507 } else {
3508 connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
3509 conn->incoming_cmd);
3512 conn->incoming_cmd_cur_len = 0;
3513 goto again;
3516 /** Something major has happened to circuit <b>circ</b>: tell any
3517 * interested control connections. */
3519 control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
3520 int reason_code)
3522 const char *status;
3523 char reasons[64] = "";
3524 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
3525 return 0;
3526 tor_assert(circ);
3528 switch (tp)
3530 case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
3531 case CIRC_EVENT_BUILT: status = "BUILT"; break;
3532 case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
3533 case CIRC_EVENT_FAILED: status = "FAILED"; break;
3534 case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
3535 default:
3536 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3537 tor_fragile_assert();
3538 return 0;
3541 if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
3542 const char *reason_str = circuit_end_reason_to_control_string(reason_code);
3543 char unk_reason_buf[16];
3544 if (!reason_str) {
3545 tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
3546 reason_str = unk_reason_buf;
3548 if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
3549 tor_snprintf(reasons, sizeof(reasons),
3550 " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
3551 } else {
3552 tor_snprintf(reasons, sizeof(reasons),
3553 " REASON=%s", reason_str);
3558 char *circdesc = circuit_describe_status_for_controller(circ);
3559 const char *sp = strlen(circdesc) ? " " : "";
3560 send_control_event(EVENT_CIRCUIT_STATUS, ALL_FORMATS,
3561 "650 CIRC %lu %s%s%s%s\r\n",
3562 (unsigned long)circ->global_identifier,
3563 status, sp,
3564 circdesc,
3565 reasons);
3566 tor_free(circdesc);
3569 return 0;
3572 /** Something minor has happened to circuit <b>circ</b>: tell any
3573 * interested control connections. */
3574 static int
3575 control_event_circuit_status_minor(origin_circuit_t *circ,
3576 circuit_status_minor_event_t e,
3577 int purpose, const struct timeval *tv)
3579 const char *event_desc;
3580 char event_tail[160] = "";
3581 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
3582 return 0;
3583 tor_assert(circ);
3585 switch (e)
3587 case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
3588 event_desc = "PURPOSE_CHANGED";
3591 /* event_tail can currently be up to 68 chars long */
3592 const char *hs_state_str =
3593 circuit_purpose_to_controller_hs_state_string(purpose);
3594 tor_snprintf(event_tail, sizeof(event_tail),
3595 " OLD_PURPOSE=%s%s%s",
3596 circuit_purpose_to_controller_string(purpose),
3597 (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
3598 (hs_state_str != NULL) ? hs_state_str : "");
3601 break;
3602 case CIRC_MINOR_EVENT_CANNIBALIZED:
3603 event_desc = "CANNIBALIZED";
3606 /* event_tail can currently be up to 130 chars long */
3607 const char *hs_state_str =
3608 circuit_purpose_to_controller_hs_state_string(purpose);
3609 const struct timeval *old_timestamp_began = tv;
3610 char tbuf[ISO_TIME_USEC_LEN+1];
3611 format_iso_time_nospace_usec(tbuf, old_timestamp_began);
3613 tor_snprintf(event_tail, sizeof(event_tail),
3614 " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
3615 circuit_purpose_to_controller_string(purpose),
3616 (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
3617 (hs_state_str != NULL) ? hs_state_str : "",
3618 tbuf);
3621 break;
3622 default:
3623 log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
3624 tor_fragile_assert();
3625 return 0;
3629 char *circdesc = circuit_describe_status_for_controller(circ);
3630 const char *sp = strlen(circdesc) ? " " : "";
3631 send_control_event(EVENT_CIRCUIT_STATUS_MINOR, ALL_FORMATS,
3632 "650 CIRC_MINOR %lu %s%s%s%s\r\n",
3633 (unsigned long)circ->global_identifier,
3634 event_desc, sp,
3635 circdesc,
3636 event_tail);
3637 tor_free(circdesc);
3640 return 0;
3644 * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
3645 * interested controllers.
3648 control_event_circuit_purpose_changed(origin_circuit_t *circ,
3649 int old_purpose)
3651 return control_event_circuit_status_minor(circ,
3652 CIRC_MINOR_EVENT_PURPOSE_CHANGED,
3653 old_purpose,
3654 NULL);
3658 * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
3659 * created-time from <b>old_tv_created</b>: tell any interested controllers.
3662 control_event_circuit_cannibalized(origin_circuit_t *circ,
3663 int old_purpose,
3664 const struct timeval *old_tv_created)
3666 return control_event_circuit_status_minor(circ,
3667 CIRC_MINOR_EVENT_CANNIBALIZED,
3668 old_purpose,
3669 old_tv_created);
3672 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
3673 * <b>buf</b>, determine the address:port combination requested on
3674 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
3675 * failure. */
3676 static int
3677 write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
3679 char buf2[256];
3680 if (conn->chosen_exit_name)
3681 if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
3682 return -1;
3683 if (!conn->socks_request)
3684 return -1;
3685 if (tor_snprintf(buf, len, "%s%s%s:%d",
3686 conn->socks_request->address,
3687 conn->chosen_exit_name ? buf2 : "",
3688 !conn->chosen_exit_name && connection_edge_is_rendezvous_stream(
3689 ENTRY_TO_EDGE_CONN(conn)) ? ".onion" : "",
3690 conn->socks_request->port)<0)
3691 return -1;
3692 return 0;
3695 /** Something has happened to the stream associated with AP connection
3696 * <b>conn</b>: tell any interested control connections. */
3698 control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
3699 int reason_code)
3701 char reason_buf[64];
3702 char addrport_buf[64];
3703 const char *status;
3704 circuit_t *circ;
3705 origin_circuit_t *origin_circ = NULL;
3706 char buf[256];
3707 const char *purpose = "";
3708 tor_assert(conn->socks_request);
3710 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
3711 return 0;
3713 if (tp == STREAM_EVENT_CLOSED &&
3714 (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
3715 return 0;
3717 write_stream_target_to_buf(conn, buf, sizeof(buf));
3719 reason_buf[0] = '\0';
3720 switch (tp)
3722 case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
3723 case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
3724 case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
3725 case STREAM_EVENT_FAILED: status = "FAILED"; break;
3726 case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
3727 case STREAM_EVENT_NEW: status = "NEW"; break;
3728 case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
3729 case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
3730 case STREAM_EVENT_REMAP: status = "REMAP"; break;
3731 default:
3732 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3733 return 0;
3735 if (reason_code && (tp == STREAM_EVENT_FAILED ||
3736 tp == STREAM_EVENT_CLOSED ||
3737 tp == STREAM_EVENT_FAILED_RETRIABLE)) {
3738 const char *reason_str = stream_end_reason_to_control_string(reason_code);
3739 char *r = NULL;
3740 if (!reason_str) {
3741 tor_asprintf(&r, " UNKNOWN_%d", reason_code);
3742 reason_str = r;
3744 if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
3745 tor_snprintf(reason_buf, sizeof(reason_buf),
3746 " REASON=END REMOTE_REASON=%s", reason_str);
3747 else
3748 tor_snprintf(reason_buf, sizeof(reason_buf),
3749 " REASON=%s", reason_str);
3750 tor_free(r);
3751 } else if (reason_code && tp == STREAM_EVENT_REMAP) {
3752 switch (reason_code) {
3753 case REMAP_STREAM_SOURCE_CACHE:
3754 strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
3755 break;
3756 case REMAP_STREAM_SOURCE_EXIT:
3757 strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
3758 break;
3759 default:
3760 tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
3761 reason_code);
3762 /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
3763 break;
3767 if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
3768 tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
3769 ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
3770 } else {
3771 addrport_buf[0] = '\0';
3774 if (tp == STREAM_EVENT_NEW_RESOLVE) {
3775 purpose = " PURPOSE=DNS_REQUEST";
3776 } else if (tp == STREAM_EVENT_NEW) {
3777 if (conn->use_begindir) {
3778 connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
3779 int linked_dir_purpose = -1;
3780 if (linked && linked->type == CONN_TYPE_DIR)
3781 linked_dir_purpose = linked->purpose;
3782 if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
3783 purpose = " PURPOSE=DIR_UPLOAD";
3784 else
3785 purpose = " PURPOSE=DIR_FETCH";
3786 } else
3787 purpose = " PURPOSE=USER";
3790 circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
3791 if (circ && CIRCUIT_IS_ORIGIN(circ))
3792 origin_circ = TO_ORIGIN_CIRCUIT(circ);
3793 send_control_event(EVENT_STREAM_STATUS, ALL_FORMATS,
3794 "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
3795 U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
3796 status,
3797 origin_circ?
3798 (unsigned long)origin_circ->global_identifier : 0ul,
3799 buf, reason_buf, addrport_buf, purpose);
3801 /* XXX need to specify its intended exit, etc? */
3803 return 0;
3806 /** Figure out the best name for the target router of an OR connection
3807 * <b>conn</b>, and write it into the <b>len</b>-character buffer
3808 * <b>name</b>. */
3809 static void
3810 orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
3812 const node_t *node = node_get_by_id(conn->identity_digest);
3813 if (node) {
3814 tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
3815 node_get_verbose_nickname(node, name);
3816 } else if (! tor_digest_is_zero(conn->identity_digest)) {
3817 name[0] = '$';
3818 base16_encode(name+1, len-1, conn->identity_digest,
3819 DIGEST_LEN);
3820 } else {
3821 tor_snprintf(name, len, "%s:%d",
3822 conn->base_.address, conn->base_.port);
3826 /** Called when the status of an OR connection <b>conn</b> changes: tell any
3827 * interested control connections. <b>tp</b> is the new status for the
3828 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
3829 * may be the reason why.
3832 control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
3833 int reason)
3835 int ncircs = 0;
3836 const char *status;
3837 char name[128];
3838 char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
3840 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
3841 return 0;
3843 switch (tp)
3845 case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
3846 case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
3847 case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
3848 case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
3849 case OR_CONN_EVENT_NEW: status = "NEW"; break;
3850 default:
3851 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3852 return 0;
3854 if (conn->chan) {
3855 ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
3856 } else {
3857 ncircs = 0;
3859 ncircs += connection_or_get_num_circuits(conn);
3860 if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
3861 tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
3862 reason ? " " : "", ncircs);
3865 orconn_target_get_name(name, sizeof(name), conn);
3866 send_control_event(EVENT_OR_CONN_STATUS, ALL_FORMATS,
3867 "650 ORCONN %s %s ID="U64_FORMAT" %s%s%s\r\n",
3868 name, status,
3869 U64_PRINTF_ARG(conn->base_.global_identifier),
3870 reason ? "REASON=" : "",
3871 orconn_end_reason_to_control_string(reason),
3872 ncircs_buf);
3874 return 0;
3878 * Print out STREAM_BW event for a single conn
3881 control_event_stream_bandwidth(edge_connection_t *edge_conn)
3883 circuit_t *circ;
3884 origin_circuit_t *ocirc;
3885 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
3886 if (!edge_conn->n_read && !edge_conn->n_written)
3887 return 0;
3889 send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
3890 "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
3891 U64_PRINTF_ARG(edge_conn->base_.global_identifier),
3892 (unsigned long)edge_conn->n_read,
3893 (unsigned long)edge_conn->n_written);
3895 circ = circuit_get_by_edge_conn(edge_conn);
3896 if (circ && CIRCUIT_IS_ORIGIN(circ)) {
3897 ocirc = TO_ORIGIN_CIRCUIT(circ);
3898 ocirc->n_read += edge_conn->n_read;
3899 ocirc->n_written += edge_conn->n_written;
3901 edge_conn->n_written = edge_conn->n_read = 0;
3904 return 0;
3907 /** A second or more has elapsed: tell any interested control
3908 * connections how much bandwidth streams have used. */
3910 control_event_stream_bandwidth_used(void)
3912 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
3913 smartlist_t *conns = get_connection_array();
3914 edge_connection_t *edge_conn;
3916 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
3918 if (conn->type != CONN_TYPE_AP)
3919 continue;
3920 edge_conn = TO_EDGE_CONN(conn);
3921 if (!edge_conn->n_read && !edge_conn->n_written)
3922 continue;
3924 send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
3925 "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
3926 U64_PRINTF_ARG(edge_conn->base_.global_identifier),
3927 (unsigned long)edge_conn->n_read,
3928 (unsigned long)edge_conn->n_written);
3930 edge_conn->n_written = edge_conn->n_read = 0;
3932 SMARTLIST_FOREACH_END(conn);
3935 return 0;
3938 /** A second or more has elapsed: tell any interested control connections
3939 * how much bandwidth origin circuits have used. */
3941 control_event_circ_bandwidth_used(void)
3943 circuit_t *circ;
3944 origin_circuit_t *ocirc;
3945 if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
3946 return 0;
3948 for (circ = global_circuitlist; circ; circ = circ->next) {
3949 if (!CIRCUIT_IS_ORIGIN(circ))
3950 continue;
3951 ocirc = TO_ORIGIN_CIRCUIT(circ);
3952 if (!ocirc->n_read && !ocirc->n_written)
3953 continue;
3954 send_control_event(EVENT_CIRC_BANDWIDTH_USED, ALL_FORMATS,
3955 "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu\r\n",
3956 ocirc->global_identifier,
3957 (unsigned long)ocirc->n_read,
3958 (unsigned long)ocirc->n_written);
3959 ocirc->n_written = ocirc->n_read = 0;
3962 return 0;
3965 /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
3966 * bandwidth counters. */
3968 control_event_conn_bandwidth(connection_t *conn)
3970 const char *conn_type_str;
3971 if (!get_options()->TestingTorNetwork ||
3972 !EVENT_IS_INTERESTING(EVENT_CONN_BW))
3973 return 0;
3974 if (!conn->n_read && !conn->n_written)
3975 return 0;
3976 switch (conn->type) {
3977 case CONN_TYPE_OR:
3978 conn_type_str = "OR";
3979 break;
3980 case CONN_TYPE_DIR:
3981 conn_type_str = "DIR";
3982 break;
3983 case CONN_TYPE_EXIT:
3984 conn_type_str = "EXIT";
3985 break;
3986 default:
3987 return 0;
3989 send_control_event(EVENT_CONN_BW, ALL_FORMATS,
3990 "650 CONN_BW ID="U64_FORMAT" TYPE=%s "
3991 "READ=%lu WRITTEN=%lu\r\n",
3992 U64_PRINTF_ARG(conn->global_identifier),
3993 conn_type_str,
3994 (unsigned long)conn->n_read,
3995 (unsigned long)conn->n_written);
3996 conn->n_written = conn->n_read = 0;
3997 return 0;
4000 /** A second or more has elapsed: tell any interested control
4001 * connections how much bandwidth connections have used. */
4003 control_event_conn_bandwidth_used(void)
4005 if (get_options()->TestingTorNetwork &&
4006 EVENT_IS_INTERESTING(EVENT_CONN_BW)) {
4007 SMARTLIST_FOREACH(get_connection_array(), connection_t *, conn,
4008 control_event_conn_bandwidth(conn));
4010 return 0;
4013 /** Convert the cell <b>command</b> into a lower-case, human-readable
4014 * string. */
4015 static const char *
4016 cell_command_to_string(uint8_t command)
4018 switch (command) {
4019 case CELL_PADDING: return "padding";
4020 case CELL_CREATE: return "create";
4021 case CELL_CREATED: return "created";
4022 case CELL_RELAY: return "relay";
4023 case CELL_DESTROY: return "destroy";
4024 case CELL_CREATE_FAST: return "create_fast";
4025 case CELL_CREATED_FAST: return "created_fast";
4026 case CELL_VERSIONS: return "versions";
4027 case CELL_NETINFO: return "netinfo";
4028 case CELL_RELAY_EARLY: return "relay_early";
4029 case CELL_CREATE2: return "create2";
4030 case CELL_CREATED2: return "created2";
4031 case CELL_VPADDING: return "vpadding";
4032 case CELL_CERTS: return "certs";
4033 case CELL_AUTH_CHALLENGE: return "auth_challenge";
4034 case CELL_AUTHENTICATE: return "authenticate";
4035 case CELL_AUTHORIZE: return "authorize";
4036 default: return "unrecognized";
4040 /** Helper: append a cell statistics string to <code>event_parts</code>,
4041 * prefixed with <code>key</code>=. Statistics consist of comma-separated
4042 * key:value pairs with lower-case command strings as keys and cell
4043 * numbers or total waiting times as values. A key:value pair is included
4044 * if the entry in <code>include_if_positive</code> is positive, but with
4045 * the (possibly zero) entry from <code>number_to_include</code>. If no
4046 * entry in <code>include_if_positive</code> is positive, no string will
4047 * be added to <code>event_parts</code>. */
4048 static void
4049 append_cell_stats_by_command(smartlist_t *event_parts, const char *key,
4050 uint64_t *include_if_positive,
4051 uint64_t *number_to_include)
4053 smartlist_t *key_value_strings = smartlist_new();
4054 int i;
4055 for (i = 0; i <= CELL_MAX_; i++) {
4056 if (include_if_positive[i] > 0) {
4057 smartlist_add_asprintf(key_value_strings, "%s:"U64_FORMAT,
4058 cell_command_to_string(i),
4059 U64_PRINTF_ARG(number_to_include[i]));
4062 if (key_value_strings->num_used > 0) {
4063 char *joined = smartlist_join_strings(key_value_strings, ",", 0, NULL);
4064 char *result;
4065 tor_asprintf(&result, "%s=%s", key, joined);
4066 smartlist_add(event_parts, result);
4067 SMARTLIST_FOREACH(key_value_strings, char *, cp, tor_free(cp));
4068 tor_free(joined);
4070 smartlist_free(key_value_strings);
4073 /** A second or more has elapsed: tell any interested control connection
4074 * how many cells have been processed for a given circuit. */
4076 control_event_circuit_cell_stats(void)
4078 /* These arrays temporarily consume slightly over 6 KiB on the stack
4079 * every second, most of which are wasted for the non-existant commands
4080 * between CELL_RELAY_EARLY (9) and CELL_VPADDING (128). But nothing
4081 * beats the stack when it comes to performance. */
4082 uint64_t added_cells_appward[CELL_MAX_ + 1],
4083 added_cells_exitward[CELL_MAX_ + 1],
4084 removed_cells_appward[CELL_MAX_ + 1],
4085 removed_cells_exitward[CELL_MAX_ + 1],
4086 total_time_appward[CELL_MAX_ + 1],
4087 total_time_exitward[CELL_MAX_ + 1];
4088 circuit_t *circ;
4089 if (!get_options()->TestingTorNetwork ||
4090 !EVENT_IS_INTERESTING(EVENT_CELL_STATS))
4091 return 0;
4092 for (circ = global_circuitlist; circ; circ = circ->next) {
4093 smartlist_t *event_parts;
4094 char *event_string;
4096 if (!circ->testing_cell_stats)
4097 continue;
4099 memset(added_cells_appward, 0, (CELL_MAX_ + 1) * sizeof(uint64_t));
4100 memset(added_cells_exitward, 0, (CELL_MAX_ + 1) * sizeof(uint64_t));
4101 memset(removed_cells_appward, 0, (CELL_MAX_ + 1) * sizeof(uint64_t));
4102 memset(removed_cells_exitward, 0, (CELL_MAX_ + 1) * sizeof(uint64_t));
4103 memset(total_time_appward, 0, (CELL_MAX_ + 1) * sizeof(uint64_t));
4104 memset(total_time_exitward, 0, (CELL_MAX_ + 1) * sizeof(uint64_t));
4105 SMARTLIST_FOREACH_BEGIN(circ->testing_cell_stats,
4106 testing_cell_stats_entry_t *, ent) {
4107 tor_assert(ent->command <= CELL_MAX_);
4108 if (!ent->removed && !ent->exit_ward) {
4109 added_cells_appward[ent->command] += 1;
4110 } else if (!ent->removed && ent->exit_ward) {
4111 added_cells_exitward[ent->command] += 1;
4112 } else if (!ent->exit_ward) {
4113 removed_cells_appward[ent->command] += 1;
4114 total_time_appward[ent->command] += ent->waiting_time * 10;
4115 } else {
4116 removed_cells_exitward[ent->command] += 1;
4117 total_time_exitward[ent->command] += ent->waiting_time * 10;
4119 tor_free(ent);
4120 } SMARTLIST_FOREACH_END(ent);
4121 smartlist_free(circ->testing_cell_stats);
4122 circ->testing_cell_stats = NULL;
4124 event_parts = smartlist_new();
4125 if (CIRCUIT_IS_ORIGIN(circ)) {
4126 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
4127 char *id_string;
4128 tor_asprintf(&id_string, "ID=%lu",
4129 (unsigned long)ocirc->global_identifier);
4130 smartlist_add(event_parts, id_string);
4131 } else {
4132 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
4133 char *queue_string, *conn_string;
4134 tor_asprintf(&queue_string, "InboundQueue=%lu",
4135 (unsigned long)or_circ->p_circ_id);
4136 tor_asprintf(&conn_string, "InboundConn="U64_FORMAT,
4137 U64_PRINTF_ARG(or_circ->p_chan->global_identifier));
4138 smartlist_add(event_parts, queue_string);
4139 smartlist_add(event_parts, conn_string);
4140 append_cell_stats_by_command(event_parts, "InboundAdded",
4141 added_cells_appward, added_cells_appward);
4142 append_cell_stats_by_command(event_parts, "InboundRemoved",
4143 removed_cells_appward, removed_cells_appward);
4144 append_cell_stats_by_command(event_parts, "InboundTime",
4145 removed_cells_appward, total_time_appward);
4147 if (circ->n_chan) {
4148 char *queue_string, *conn_string;
4149 tor_asprintf(&queue_string, "OutboundQueue=%lu",
4150 (unsigned long)circ->n_circ_id);
4151 tor_asprintf(&conn_string, "OutboundConn="U64_FORMAT,
4152 U64_PRINTF_ARG(circ->n_chan->global_identifier));
4153 smartlist_add(event_parts, queue_string);
4154 smartlist_add(event_parts, conn_string);
4155 append_cell_stats_by_command(event_parts, "OutboundAdded",
4156 added_cells_exitward, added_cells_exitward);
4157 append_cell_stats_by_command(event_parts, "OutboundRemoved",
4158 removed_cells_exitward, removed_cells_exitward);
4159 append_cell_stats_by_command(event_parts, "OutboundTime",
4160 removed_cells_exitward, total_time_exitward);
4162 event_string = smartlist_join_strings(event_parts, " ", 0, NULL);
4163 send_control_event(EVENT_CELL_STATS, ALL_FORMATS,
4164 "650 CELL_STATS %s\r\n", event_string);
4165 SMARTLIST_FOREACH(event_parts, char *, cp, tor_free(cp));
4166 smartlist_free(event_parts);
4167 tor_free(event_string);
4169 return 0;
4172 /** Helper: return the time in millis that a given bucket was empty,
4173 * capped at the time in millis since last refilling that bucket. Return
4174 * 0 if the bucket was not empty during the last refill period. */
4175 static uint32_t
4176 bucket_millis_empty(int prev_tokens, uint32_t last_empty_time,
4177 uint32_t milliseconds_elapsed)
4179 uint32_t result = 0, refilled;
4180 if (prev_tokens <= 0) {
4181 struct timeval tvnow;
4182 tor_gettimeofday_cached(&tvnow);
4183 refilled = (uint32_t)((tvnow.tv_sec % 86400L) * 1000L +
4184 (uint32_t)tvnow.tv_usec / (uint32_t)1000L);
4185 result = (uint32_t)((refilled + 86400L * 1000L - last_empty_time) %
4186 (86400L * 1000L));
4187 if (result > milliseconds_elapsed)
4188 result = milliseconds_elapsed;
4190 return result;
4193 /** Token buckets have been refilled: tell any interested control
4194 * connections how global and relay token buckets have changed. */
4196 control_event_refill_global(int global_read, int prev_global_read,
4197 uint32_t global_read_emptied_time,
4198 int global_write, int prev_global_write,
4199 uint32_t global_write_emptied_time,
4200 int relay_read, int prev_relay_read,
4201 uint32_t relay_read_emptied_time,
4202 int relay_write, int prev_relay_write,
4203 uint32_t relay_write_emptied_time,
4204 uint32_t milliseconds_elapsed)
4206 uint32_t global_read_empty_time, global_write_empty_time,
4207 relay_read_empty_time, relay_write_empty_time;
4208 if (!get_options()->TestingTorNetwork ||
4209 !EVENT_IS_INTERESTING(EVENT_TB_EMPTY))
4210 return 0;
4211 if (prev_global_read == global_read &&
4212 prev_global_write == global_write &&
4213 prev_relay_read == relay_read &&
4214 prev_relay_write == relay_write)
4215 return 0;
4216 if (prev_global_read <= 0 && prev_global_write <= 0) {
4217 global_read_empty_time = bucket_millis_empty(prev_global_read,
4218 global_read_emptied_time, milliseconds_elapsed);
4219 global_write_empty_time = bucket_millis_empty(prev_global_write,
4220 global_write_emptied_time, milliseconds_elapsed);
4221 send_control_event(EVENT_TB_EMPTY, ALL_FORMATS,
4222 "650 TB_EMPTY GLOBAL READ=%d WRITTEN=%d "
4223 "LAST=%d\r\n",
4224 global_read_empty_time, global_write_empty_time,
4225 milliseconds_elapsed);
4227 if (prev_relay_read <= 0 && prev_relay_write <= 0) {
4228 relay_read_empty_time = bucket_millis_empty(prev_relay_read,
4229 relay_read_emptied_time, milliseconds_elapsed);
4230 relay_write_empty_time = bucket_millis_empty(prev_relay_write,
4231 relay_write_emptied_time, milliseconds_elapsed);
4232 send_control_event(EVENT_TB_EMPTY, ALL_FORMATS,
4233 "650 TB_EMPTY RELAY READ=%d WRITTEN=%d "
4234 "LAST=%d\r\n",
4235 relay_read_empty_time, relay_write_empty_time,
4236 milliseconds_elapsed);
4238 return 0;
4241 /** Token buckets of a connection have been refilled: tell any interested
4242 * control connections how per-connection token buckets have changed. */
4244 control_event_refill_conn(or_connection_t *or_conn,
4245 int prev_read, int prev_write,
4246 uint32_t milliseconds_elapsed)
4248 uint32_t read_bucket_empty_time, write_bucket_empty_time;
4249 if (!get_options()->TestingTorNetwork ||
4250 !EVENT_IS_INTERESTING(EVENT_TB_EMPTY))
4251 return 0;
4252 if (prev_read == or_conn->read_bucket &&
4253 prev_write == or_conn->write_bucket)
4254 return 0;
4255 if (prev_read <= 0 || prev_write <= 0) {
4256 read_bucket_empty_time = bucket_millis_empty(prev_read,
4257 or_conn->read_emptied_time, milliseconds_elapsed);
4258 write_bucket_empty_time = bucket_millis_empty(prev_write,
4259 or_conn->write_emptied_time, milliseconds_elapsed);
4260 send_control_event(EVENT_TB_EMPTY, ALL_FORMATS,
4261 "650 TB_EMPTY ORCONN ID="U64_FORMAT" READ=%d "
4262 "WRITTEN=%d LAST=%d\r\n",
4263 U64_PRINTF_ARG(or_conn->base_.global_identifier),
4264 read_bucket_empty_time, write_bucket_empty_time,
4265 milliseconds_elapsed);
4267 return 0;
4270 /** A second or more has elapsed: tell any interested control
4271 * connections how much bandwidth we used. */
4273 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
4275 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
4276 send_control_event(EVENT_BANDWIDTH_USED, ALL_FORMATS,
4277 "650 BW %lu %lu\r\n",
4278 (unsigned long)n_read,
4279 (unsigned long)n_written);
4282 return 0;
4285 /** Called when we are sending a log message to the controllers: suspend
4286 * sending further log messages to the controllers until we're done. Used by
4287 * CONN_LOG_PROTECT. */
4288 void
4289 disable_control_logging(void)
4291 ++disable_log_messages;
4294 /** We're done sending a log message to the controllers: re-enable controller
4295 * logging. Used by CONN_LOG_PROTECT. */
4296 void
4297 enable_control_logging(void)
4299 if (--disable_log_messages < 0)
4300 tor_assert(0);
4303 /** We got a log message: tell any interested control connections. */
4304 void
4305 control_event_logmsg(int severity, uint32_t domain, const char *msg)
4307 int event;
4309 /* Don't even think of trying to add stuff to a buffer from a cpuworker
4310 * thread. */
4311 if (! in_main_thread())
4312 return;
4314 if (disable_log_messages)
4315 return;
4317 if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
4318 severity <= LOG_NOTICE) {
4319 char *esc = esc_for_log(msg);
4320 ++disable_log_messages;
4321 control_event_general_status(severity, "BUG REASON=%s", esc);
4322 --disable_log_messages;
4323 tor_free(esc);
4326 event = log_severity_to_event(severity);
4327 if (event >= 0 && EVENT_IS_INTERESTING(event)) {
4328 char *b = NULL;
4329 const char *s;
4330 if (strchr(msg, '\n')) {
4331 char *cp;
4332 b = tor_strdup(msg);
4333 for (cp = b; *cp; ++cp)
4334 if (*cp == '\r' || *cp == '\n')
4335 *cp = ' ';
4337 switch (severity) {
4338 case LOG_DEBUG: s = "DEBUG"; break;
4339 case LOG_INFO: s = "INFO"; break;
4340 case LOG_NOTICE: s = "NOTICE"; break;
4341 case LOG_WARN: s = "WARN"; break;
4342 case LOG_ERR: s = "ERR"; break;
4343 default: s = "UnknownLogSeverity"; break;
4345 ++disable_log_messages;
4346 send_control_event(event, ALL_FORMATS, "650 %s %s\r\n", s, b?b:msg);
4347 --disable_log_messages;
4348 tor_free(b);
4352 /** Called whenever we receive new router descriptors: tell any
4353 * interested control connections. <b>routers</b> is a list of
4354 * routerinfo_t's.
4357 control_event_descriptors_changed(smartlist_t *routers)
4359 char *msg;
4361 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
4362 return 0;
4365 smartlist_t *names = smartlist_new();
4366 char *ids;
4367 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
4368 char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
4369 router_get_verbose_nickname(b, ri);
4370 smartlist_add(names, b);
4372 ids = smartlist_join_strings(names, " ", 0, NULL);
4373 tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
4374 send_control_event_string(EVENT_NEW_DESC, ALL_FORMATS, msg);
4375 tor_free(ids);
4376 tor_free(msg);
4377 SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
4378 smartlist_free(names);
4380 return 0;
4383 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
4384 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
4385 * <b>error</b> is non-NULL, it is an error code describing the failure
4386 * mode of the mapping.
4389 control_event_address_mapped(const char *from, const char *to, time_t expires,
4390 const char *error, const int cached)
4392 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
4393 return 0;
4395 if (expires < 3 || expires == TIME_MAX)
4396 send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
4397 "650 ADDRMAP %s %s NEVER %s%s"
4398 "CACHED=\"%s\"\r\n",
4399 from, to, error?error:"", error?" ":"",
4400 cached?"YES":"NO");
4401 else {
4402 char buf[ISO_TIME_LEN+1];
4403 char buf2[ISO_TIME_LEN+1];
4404 format_local_iso_time(buf,expires);
4405 format_iso_time(buf2,expires);
4406 send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
4407 "650 ADDRMAP %s %s \"%s\""
4408 " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
4409 from, to, buf,
4410 error?error:"", error?" ":"",
4411 buf2, cached?"YES":"NO");
4414 return 0;
4417 /** The authoritative dirserver has received a new descriptor that
4418 * has passed basic syntax checks and is properly self-signed.
4420 * Notify any interested party of the new descriptor and what has
4421 * been done with it, and also optionally give an explanation/reason. */
4423 control_event_or_authdir_new_descriptor(const char *action,
4424 const char *desc, size_t desclen,
4425 const char *msg)
4427 char firstline[1024];
4428 char *buf;
4429 size_t totallen;
4430 char *esc = NULL;
4431 size_t esclen;
4433 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
4434 return 0;
4436 tor_snprintf(firstline, sizeof(firstline),
4437 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
4438 action,
4439 msg ? msg : "");
4441 /* Escape the server descriptor properly */
4442 esclen = write_escaped_data(desc, desclen, &esc);
4444 totallen = strlen(firstline) + esclen + 1;
4445 buf = tor_malloc(totallen);
4446 strlcpy(buf, firstline, totallen);
4447 strlcpy(buf+strlen(firstline), esc, totallen);
4448 send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
4449 buf);
4450 send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
4451 "650 OK\r\n");
4452 tor_free(esc);
4453 tor_free(buf);
4455 return 0;
4458 /** Helper function for NS-style events. Constructs and sends an event
4459 * of type <b>event</b> with string <b>event_string</b> out of the set of
4460 * networkstatuses <b>statuses</b>. Currently it is used for NS events
4461 * and NEWCONSENSUS events. */
4462 static int
4463 control_event_networkstatus_changed_helper(smartlist_t *statuses,
4464 uint16_t event,
4465 const char *event_string)
4467 smartlist_t *strs;
4468 char *s, *esc = NULL;
4469 if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
4470 return 0;
4472 strs = smartlist_new();
4473 smartlist_add(strs, tor_strdup("650+"));
4474 smartlist_add(strs, tor_strdup(event_string));
4475 smartlist_add(strs, tor_strdup("\r\n"));
4476 SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
4478 s = networkstatus_getinfo_helper_single(rs);
4479 if (!s) continue;
4480 smartlist_add(strs, s);
4483 s = smartlist_join_strings(strs, "", 0, NULL);
4484 write_escaped_data(s, strlen(s), &esc);
4485 SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
4486 smartlist_free(strs);
4487 tor_free(s);
4488 send_control_event_string(event, ALL_FORMATS, esc);
4489 send_control_event_string(event, ALL_FORMATS,
4490 "650 OK\r\n");
4492 tor_free(esc);
4493 return 0;
4496 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
4497 * an NS event to any controller that cares. */
4499 control_event_networkstatus_changed(smartlist_t *statuses)
4501 return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
4504 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
4505 * event consisting of an NS-style line for each relay in the consensus. */
4507 control_event_newconsensus(const networkstatus_t *consensus)
4509 if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
4510 return 0;
4511 return control_event_networkstatus_changed_helper(
4512 consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
4515 /** Called when we compute a new circuitbuildtimeout */
4517 control_event_buildtimeout_set(const circuit_build_times_t *cbt,
4518 buildtimeout_set_event_t type)
4520 const char *type_string = NULL;
4521 double qnt;
4523 if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
4524 return 0;
4526 qnt = circuit_build_times_quantile_cutoff();
4528 switch (type) {
4529 case BUILDTIMEOUT_SET_EVENT_COMPUTED:
4530 type_string = "COMPUTED";
4531 break;
4532 case BUILDTIMEOUT_SET_EVENT_RESET:
4533 type_string = "RESET";
4534 qnt = 1.0;
4535 break;
4536 case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
4537 type_string = "SUSPENDED";
4538 qnt = 1.0;
4539 break;
4540 case BUILDTIMEOUT_SET_EVENT_DISCARD:
4541 type_string = "DISCARD";
4542 qnt = 1.0;
4543 break;
4544 case BUILDTIMEOUT_SET_EVENT_RESUME:
4545 type_string = "RESUME";
4546 break;
4547 default:
4548 type_string = "UNKNOWN";
4549 break;
4552 send_control_event(EVENT_BUILDTIMEOUT_SET, ALL_FORMATS,
4553 "650 BUILDTIMEOUT_SET %s TOTAL_TIMES=%lu "
4554 "TIMEOUT_MS=%lu XM=%lu ALPHA=%f CUTOFF_QUANTILE=%f "
4555 "TIMEOUT_RATE=%f CLOSE_MS=%lu CLOSE_RATE=%f\r\n",
4556 type_string, (unsigned long)cbt->total_build_times,
4557 (unsigned long)cbt->timeout_ms,
4558 (unsigned long)cbt->Xm, cbt->alpha, qnt,
4559 circuit_build_times_timeout_rate(cbt),
4560 (unsigned long)cbt->close_ms,
4561 circuit_build_times_close_rate(cbt));
4563 return 0;
4566 /** Called when a signal has been processed from signal_callback */
4568 control_event_signal(uintptr_t signal)
4570 const char *signal_string = NULL;
4572 if (!control_event_is_interesting(EVENT_SIGNAL))
4573 return 0;
4575 switch (signal) {
4576 case SIGHUP:
4577 signal_string = "RELOAD";
4578 break;
4579 case SIGUSR1:
4580 signal_string = "DUMP";
4581 break;
4582 case SIGUSR2:
4583 signal_string = "DEBUG";
4584 break;
4585 case SIGNEWNYM:
4586 signal_string = "NEWNYM";
4587 break;
4588 case SIGCLEARDNSCACHE:
4589 signal_string = "CLEARDNSCACHE";
4590 break;
4591 default:
4592 log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
4593 (unsigned long)signal);
4594 return -1;
4597 send_control_event(EVENT_SIGNAL, ALL_FORMATS, "650 SIGNAL %s\r\n",
4598 signal_string);
4599 return 0;
4602 /** Called when a single local_routerstatus_t has changed: Sends an NS event
4603 * to any controller that cares. */
4605 control_event_networkstatus_changed_single(const routerstatus_t *rs)
4607 smartlist_t *statuses;
4608 int r;
4610 if (!EVENT_IS_INTERESTING(EVENT_NS))
4611 return 0;
4613 statuses = smartlist_new();
4614 smartlist_add(statuses, (void*)rs);
4615 r = control_event_networkstatus_changed(statuses);
4616 smartlist_free(statuses);
4617 return r;
4620 /** Our own router descriptor has changed; tell any controllers that care.
4623 control_event_my_descriptor_changed(void)
4625 send_control_event(EVENT_DESCCHANGED, ALL_FORMATS, "650 DESCCHANGED\r\n");
4626 return 0;
4629 /** Helper: sends a status event where <b>type</b> is one of
4630 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
4631 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
4632 * string corresponding to <b>args</b>. */
4633 static int
4634 control_event_status(int type, int severity, const char *format, va_list args)
4636 char *user_buf = NULL;
4637 char format_buf[160];
4638 const char *status, *sev;
4640 switch (type) {
4641 case EVENT_STATUS_GENERAL:
4642 status = "STATUS_GENERAL";
4643 break;
4644 case EVENT_STATUS_CLIENT:
4645 status = "STATUS_CLIENT";
4646 break;
4647 case EVENT_STATUS_SERVER:
4648 status = "STATUS_SERVER";
4649 break;
4650 default:
4651 log_warn(LD_BUG, "Unrecognized status type %d", type);
4652 return -1;
4654 switch (severity) {
4655 case LOG_NOTICE:
4656 sev = "NOTICE";
4657 break;
4658 case LOG_WARN:
4659 sev = "WARN";
4660 break;
4661 case LOG_ERR:
4662 sev = "ERR";
4663 break;
4664 default:
4665 log_warn(LD_BUG, "Unrecognized status severity %d", severity);
4666 return -1;
4668 if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
4669 status, sev)<0) {
4670 log_warn(LD_BUG, "Format string too long.");
4671 return -1;
4673 tor_vasprintf(&user_buf, format, args);
4675 send_control_event(type, ALL_FORMATS, "%s %s\r\n", format_buf, user_buf);
4676 tor_free(user_buf);
4677 return 0;
4680 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
4681 * by formatting the arguments using the printf-style <b>format</b>. */
4683 control_event_general_status(int severity, const char *format, ...)
4685 va_list ap;
4686 int r;
4687 if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
4688 return 0;
4690 va_start(ap, format);
4691 r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
4692 va_end(ap);
4693 return r;
4696 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
4697 * by formatting the arguments using the printf-style <b>format</b>. */
4699 control_event_client_status(int severity, const char *format, ...)
4701 va_list ap;
4702 int r;
4703 if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
4704 return 0;
4706 va_start(ap, format);
4707 r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
4708 va_end(ap);
4709 return r;
4712 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
4713 * by formatting the arguments using the printf-style <b>format</b>. */
4715 control_event_server_status(int severity, const char *format, ...)
4717 va_list ap;
4718 int r;
4719 if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
4720 return 0;
4722 va_start(ap, format);
4723 r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
4724 va_end(ap);
4725 return r;
4728 /** Called when the status of an entry guard with the given <b>nickname</b>
4729 * and identity <b>digest</b> has changed to <b>status</b>: tells any
4730 * controllers that care. */
4732 control_event_guard(const char *nickname, const char *digest,
4733 const char *status)
4735 char hbuf[HEX_DIGEST_LEN+1];
4736 base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
4737 if (!EVENT_IS_INTERESTING(EVENT_GUARD))
4738 return 0;
4741 char buf[MAX_VERBOSE_NICKNAME_LEN+1];
4742 const node_t *node = node_get_by_id(digest);
4743 if (node) {
4744 node_get_verbose_nickname(node, buf);
4745 } else {
4746 tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
4748 send_control_event(EVENT_GUARD, ALL_FORMATS,
4749 "650 GUARD ENTRY %s %s\r\n", buf, status);
4751 return 0;
4754 /** Called when a configuration option changes. This is generally triggered
4755 * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
4756 * a smartlist_t containing (key, value, ...) pairs in sequence.
4757 * <b>value</b> can be NULL. */
4759 control_event_conf_changed(const smartlist_t *elements)
4761 int i;
4762 char *result;
4763 smartlist_t *lines;
4764 if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) ||
4765 smartlist_len(elements) == 0) {
4766 return 0;
4768 lines = smartlist_new();
4769 for (i = 0; i < smartlist_len(elements); i += 2) {
4770 char *k = smartlist_get(elements, i);
4771 char *v = smartlist_get(elements, i+1);
4772 if (v == NULL) {
4773 smartlist_add_asprintf(lines, "650-%s", k);
4774 } else {
4775 smartlist_add_asprintf(lines, "650-%s=%s", k, v);
4778 result = smartlist_join_strings(lines, "\r\n", 0, NULL);
4779 send_control_event(EVENT_CONF_CHANGED, 0,
4780 "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
4781 tor_free(result);
4782 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
4783 smartlist_free(lines);
4784 return 0;
4787 /** Helper: Return a newly allocated string containing a path to the
4788 * file where we store our authentication cookie. */
4789 static char *
4790 get_cookie_file(void)
4792 const or_options_t *options = get_options();
4793 if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
4794 return tor_strdup(options->CookieAuthFile);
4795 } else {
4796 return get_datadir_fname("control_auth_cookie");
4800 /** Choose a random authentication cookie and write it to disk.
4801 * Anybody who can read the cookie from disk will be considered
4802 * authorized to use the control connection. Return -1 if we can't
4803 * write the file, or 0 on success. */
4805 init_cookie_authentication(int enabled)
4807 char *fname;
4808 if (!enabled) {
4809 authentication_cookie_is_set = 0;
4810 return 0;
4813 /* We don't want to generate a new cookie every time we call
4814 * options_act(). One should be enough. */
4815 if (authentication_cookie_is_set)
4816 return 0; /* all set */
4818 fname = get_cookie_file();
4819 crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
4820 authentication_cookie_is_set = 1;
4821 if (write_bytes_to_file(fname, authentication_cookie,
4822 AUTHENTICATION_COOKIE_LEN, 1)) {
4823 log_warn(LD_FS,"Error writing authentication cookie to %s.",
4824 escaped(fname));
4825 tor_free(fname);
4826 return -1;
4828 #ifndef _WIN32
4829 if (get_options()->CookieAuthFileGroupReadable) {
4830 if (chmod(fname, 0640)) {
4831 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
4834 #endif
4836 tor_free(fname);
4837 return 0;
4840 /** A copy of the process specifier of Tor's owning controller, or
4841 * NULL if this Tor instance is not currently owned by a process. */
4842 static char *owning_controller_process_spec = NULL;
4844 /** A process-termination monitor for Tor's owning controller, or NULL
4845 * if this Tor instance is not currently owned by a process. */
4846 static tor_process_monitor_t *owning_controller_process_monitor = NULL;
4848 /** Process-termination monitor callback for Tor's owning controller
4849 * process. */
4850 static void
4851 owning_controller_procmon_cb(void *unused)
4853 (void)unused;
4855 lost_owning_controller("process", "vanished");
4858 /** Set <b>process_spec</b> as Tor's owning controller process.
4859 * Exit on failure. */
4860 void
4861 monitor_owning_controller_process(const char *process_spec)
4863 const char *msg;
4865 tor_assert((owning_controller_process_spec == NULL) ==
4866 (owning_controller_process_monitor == NULL));
4868 if (owning_controller_process_spec != NULL) {
4869 if ((process_spec != NULL) && !strcmp(process_spec,
4870 owning_controller_process_spec)) {
4871 /* Same process -- return now, instead of disposing of and
4872 * recreating the process-termination monitor. */
4873 return;
4876 /* We are currently owned by a process, and we should no longer be
4877 * owned by it. Free the process-termination monitor. */
4878 tor_process_monitor_free(owning_controller_process_monitor);
4879 owning_controller_process_monitor = NULL;
4881 tor_free(owning_controller_process_spec);
4882 owning_controller_process_spec = NULL;
4885 tor_assert((owning_controller_process_spec == NULL) &&
4886 (owning_controller_process_monitor == NULL));
4888 if (process_spec == NULL)
4889 return;
4891 owning_controller_process_spec = tor_strdup(process_spec);
4892 owning_controller_process_monitor =
4893 tor_process_monitor_new(tor_libevent_get_base(),
4894 owning_controller_process_spec,
4895 LD_CONTROL,
4896 owning_controller_procmon_cb, NULL,
4897 &msg);
4899 if (owning_controller_process_monitor == NULL) {
4900 log_err(LD_BUG, "Couldn't create process-termination monitor for "
4901 "owning controller: %s. Exiting.",
4902 msg);
4903 owning_controller_process_spec = NULL;
4904 tor_cleanup();
4905 exit(0);
4909 /** Convert the name of a bootstrapping phase <b>s</b> into strings
4910 * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
4911 static int
4912 bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
4913 const char **summary)
4915 switch (s) {
4916 case BOOTSTRAP_STATUS_UNDEF:
4917 *tag = "undef";
4918 *summary = "Undefined";
4919 break;
4920 case BOOTSTRAP_STATUS_STARTING:
4921 *tag = "starting";
4922 *summary = "Starting";
4923 break;
4924 case BOOTSTRAP_STATUS_CONN_DIR:
4925 *tag = "conn_dir";
4926 *summary = "Connecting to directory server";
4927 break;
4928 case BOOTSTRAP_STATUS_HANDSHAKE:
4929 *tag = "status_handshake";
4930 *summary = "Finishing handshake";
4931 break;
4932 case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
4933 *tag = "handshake_dir";
4934 *summary = "Finishing handshake with directory server";
4935 break;
4936 case BOOTSTRAP_STATUS_ONEHOP_CREATE:
4937 *tag = "onehop_create";
4938 *summary = "Establishing an encrypted directory connection";
4939 break;
4940 case BOOTSTRAP_STATUS_REQUESTING_STATUS:
4941 *tag = "requesting_status";
4942 *summary = "Asking for networkstatus consensus";
4943 break;
4944 case BOOTSTRAP_STATUS_LOADING_STATUS:
4945 *tag = "loading_status";
4946 *summary = "Loading networkstatus consensus";
4947 break;
4948 case BOOTSTRAP_STATUS_LOADING_KEYS:
4949 *tag = "loading_keys";
4950 *summary = "Loading authority key certs";
4951 break;
4952 case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
4953 *tag = "requesting_descriptors";
4954 *summary = "Asking for relay descriptors";
4955 break;
4956 case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
4957 *tag = "loading_descriptors";
4958 *summary = "Loading relay descriptors";
4959 break;
4960 case BOOTSTRAP_STATUS_CONN_OR:
4961 *tag = "conn_or";
4962 *summary = "Connecting to the Tor network";
4963 break;
4964 case BOOTSTRAP_STATUS_HANDSHAKE_OR:
4965 *tag = "handshake_or";
4966 *summary = "Finishing handshake with first hop";
4967 break;
4968 case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
4969 *tag = "circuit_create";
4970 *summary = "Establishing a Tor circuit";
4971 break;
4972 case BOOTSTRAP_STATUS_DONE:
4973 *tag = "done";
4974 *summary = "Done";
4975 break;
4976 default:
4977 // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
4978 *tag = *summary = "unknown";
4979 return -1;
4981 return 0;
4984 /** What percentage through the bootstrap process are we? We remember
4985 * this so we can avoid sending redundant bootstrap status events, and
4986 * so we can guess context for the bootstrap messages which are
4987 * ambiguous. It starts at 'undef', but gets set to 'starting' while
4988 * Tor initializes. */
4989 static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
4991 /** How many problems have we had getting to the next bootstrapping phase?
4992 * These include failure to establish a connection to a Tor relay,
4993 * failures to finish the TLS handshake, failures to validate the
4994 * consensus document, etc. */
4995 static int bootstrap_problems = 0;
4997 /* We only tell the controller once we've hit a threshold of problems
4998 * for the current phase. */
4999 #define BOOTSTRAP_PROBLEM_THRESHOLD 10
5001 /** Called when Tor has made progress at bootstrapping its directory
5002 * information and initial circuits.
5004 * <b>status</b> is the new status, that is, what task we will be doing
5005 * next. <b>progress</b> is zero if we just started this task, else it
5006 * represents progress on the task. */
5007 void
5008 control_event_bootstrap(bootstrap_status_t status, int progress)
5010 const char *tag, *summary;
5011 char buf[BOOTSTRAP_MSG_LEN];
5013 if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
5014 return; /* already bootstrapped; nothing to be done here. */
5016 /* special case for handshaking status, since our TLS handshaking code
5017 * can't distinguish what the connection is going to be for. */
5018 if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
5019 if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
5020 status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
5021 } else {
5022 status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
5026 if (status > bootstrap_percent ||
5027 (progress && progress > bootstrap_percent)) {
5028 bootstrap_status_to_string(status, &tag, &summary);
5029 tor_log(status ? LOG_NOTICE : LOG_INFO, LD_CONTROL,
5030 "Bootstrapped %d%%: %s.", progress ? progress : status, summary);
5031 tor_snprintf(buf, sizeof(buf),
5032 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
5033 progress ? progress : status, tag, summary);
5034 tor_snprintf(last_sent_bootstrap_message,
5035 sizeof(last_sent_bootstrap_message),
5036 "NOTICE %s", buf);
5037 control_event_client_status(LOG_NOTICE, "%s", buf);
5038 if (status > bootstrap_percent) {
5039 bootstrap_percent = status; /* new milestone reached */
5041 if (progress > bootstrap_percent) {
5042 /* incremental progress within a milestone */
5043 bootstrap_percent = progress;
5044 bootstrap_problems = 0; /* Progress! Reset our problem counter. */
5049 /** Called when Tor has failed to make bootstrapping progress in a way
5050 * that indicates a problem. <b>warn</b> gives a hint as to why, and
5051 * <b>reason</b> provides an "or_conn_end_reason" tag.
5053 void
5054 control_event_bootstrap_problem(const char *warn, int reason)
5056 int status = bootstrap_percent;
5057 const char *tag, *summary;
5058 char buf[BOOTSTRAP_MSG_LEN];
5059 const char *recommendation = "ignore";
5060 int severity;
5062 /* bootstrap_percent must not be in "undefined" state here. */
5063 tor_assert(status >= 0);
5065 if (bootstrap_percent == 100)
5066 return; /* already bootstrapped; nothing to be done here. */
5068 bootstrap_problems++;
5070 if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
5071 recommendation = "warn";
5073 if (reason == END_OR_CONN_REASON_NO_ROUTE)
5074 recommendation = "warn";
5076 if (get_options()->UseBridges &&
5077 !any_bridge_descriptors_known() &&
5078 !any_pending_bridge_descriptor_fetches())
5079 recommendation = "warn";
5081 if (we_are_hibernating())
5082 recommendation = "ignore";
5084 while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
5085 status--; /* find a recognized status string based on current progress */
5086 status = bootstrap_percent; /* set status back to the actual number */
5088 severity = !strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO;
5090 log_fn(severity,
5091 LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
5092 "count %d; recommendation %s)",
5093 status, summary, warn,
5094 orconn_end_reason_to_control_string(reason),
5095 bootstrap_problems, recommendation);
5097 connection_or_report_broken_states(severity, LD_HANDSHAKE);
5099 tor_snprintf(buf, sizeof(buf),
5100 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
5101 "COUNT=%d RECOMMENDATION=%s",
5102 bootstrap_percent, tag, summary, warn,
5103 orconn_end_reason_to_control_string(reason), bootstrap_problems,
5104 recommendation);
5105 tor_snprintf(last_sent_bootstrap_message,
5106 sizeof(last_sent_bootstrap_message),
5107 "WARN %s", buf);
5108 control_event_client_status(LOG_WARN, "%s", buf);
5111 /** We just generated a new summary of which countries we've seen clients
5112 * from recently. Send a copy to the controller in case it wants to
5113 * display it for the user. */
5114 void
5115 control_event_clients_seen(const char *controller_str)
5117 send_control_event(EVENT_CLIENTS_SEEN, 0,
5118 "650 CLIENTS_SEEN %s\r\n", controller_str);