Make SIGNAL DUMP work on FreeBSD
[tor.git] / src / or / control.c
blobbb1c3307af882f90d7241e5b906c0196c9d52412
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2011, 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 "buffers.h"
15 #include "circuitbuild.h"
16 #include "circuitlist.h"
17 #include "circuituse.h"
18 #include "config.h"
19 #include "connection.h"
20 #include "connection_edge.h"
21 #include "control.h"
22 #include "directory.h"
23 #include "dirserv.h"
24 #include "dnsserv.h"
25 #include "geoip.h"
26 #include "hibernate.h"
27 #include "main.h"
28 #include "networkstatus.h"
29 #include "policies.h"
30 #include "reasons.h"
31 #include "router.h"
32 #include "routerlist.h"
33 #include "routerparse.h"
35 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
36 * finished authentication and is accepting commands. */
37 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
39 /* Recognized asynchronous event types. It's okay to expand this list
40 * because it is used both as a list of v0 event types, and as indices
41 * into the bitfield to determine which controllers want which events.
43 #define _EVENT_MIN 0x0001
44 #define EVENT_CIRCUIT_STATUS 0x0001
45 #define EVENT_STREAM_STATUS 0x0002
46 #define EVENT_OR_CONN_STATUS 0x0003
47 #define EVENT_BANDWIDTH_USED 0x0004
48 #define EVENT_LOG_OBSOLETE 0x0005 /* Can reclaim this. */
49 #define EVENT_NEW_DESC 0x0006
50 #define EVENT_DEBUG_MSG 0x0007
51 #define EVENT_INFO_MSG 0x0008
52 #define EVENT_NOTICE_MSG 0x0009
53 #define EVENT_WARN_MSG 0x000A
54 #define EVENT_ERR_MSG 0x000B
55 #define EVENT_ADDRMAP 0x000C
56 // #define EVENT_AUTHDIR_NEWDESCS 0x000D
57 #define EVENT_DESCCHANGED 0x000E
58 // #define EVENT_NS 0x000F
59 #define EVENT_STATUS_CLIENT 0x0010
60 #define EVENT_STATUS_SERVER 0x0011
61 #define EVENT_STATUS_GENERAL 0x0012
62 #define EVENT_GUARD 0x0013
63 #define EVENT_STREAM_BANDWIDTH_USED 0x0014
64 #define EVENT_CLIENTS_SEEN 0x0015
65 #define EVENT_NEWCONSENSUS 0x0016
66 #define EVENT_BUILDTIMEOUT_SET 0x0017
67 #define _EVENT_MAX 0x0017
68 /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
70 /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
71 * connection is interested in events of type <b>e</b>. We use this
72 * so that we can decide to skip generating event messages that nobody
73 * has interest in without having to walk over the global connection
74 * list to find out.
75 **/
76 typedef uint32_t event_mask_t;
78 /** An event mask of all the events that any controller is interested in
79 * receiving. */
80 static event_mask_t global_event_mask = 0;
82 /** True iff we have disabled log messages from being sent to the controller */
83 static int disable_log_messages = 0;
85 /** Macro: true if any control connection is interested in events of type
86 * <b>e</b>. */
87 #define EVENT_IS_INTERESTING(e) \
88 (global_event_mask & (1<<(e)))
90 /** If we're using cookie-type authentication, how long should our cookies be?
92 #define AUTHENTICATION_COOKIE_LEN 32
94 /** If true, we've set authentication_cookie to a secret code and
95 * stored it to disk. */
96 static int authentication_cookie_is_set = 0;
97 /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
98 * and which we're using to authenticate controllers. (If the controller can
99 * read it off disk, it has permission to connect. */
100 static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
102 /** A sufficiently large size to record the last bootstrap phase string. */
103 #define BOOTSTRAP_MSG_LEN 1024
105 /** What was the last bootstrap phase message we sent? We keep track
106 * of this so we can respond to getinfo status/bootstrap-phase queries. */
107 static char last_sent_bootstrap_message[BOOTSTRAP_MSG_LEN];
109 /** Flag for event_format_t. Indicates that we should use the one standard
110 format.
112 #define ALL_FORMATS 1
114 /** Bit field of flags to select how to format a controller event. Recognized
115 * flag is ALL_FORMATS. */
116 typedef int event_format_t;
118 static void connection_printf_to_buf(control_connection_t *conn,
119 const char *format, ...)
120 CHECK_PRINTF(2,3);
121 static void send_control_done(control_connection_t *conn);
122 static void send_control_event(uint16_t event, event_format_t which,
123 const char *format, ...)
124 CHECK_PRINTF(3,4);
125 static int handle_control_setconf(control_connection_t *conn, uint32_t len,
126 char *body);
127 static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
128 char *body);
129 static int handle_control_getconf(control_connection_t *conn, uint32_t len,
130 const char *body);
131 static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
132 const char *body);
133 static int handle_control_setevents(control_connection_t *conn, uint32_t len,
134 const char *body);
135 static int handle_control_authenticate(control_connection_t *conn,
136 uint32_t len,
137 const char *body);
138 static int handle_control_signal(control_connection_t *conn, uint32_t len,
139 const char *body);
140 static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
141 const char *body);
142 static char *list_getinfo_options(void);
143 static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
144 const char *body);
145 static int handle_control_extendcircuit(control_connection_t *conn,
146 uint32_t len,
147 const char *body);
148 static int handle_control_setcircuitpurpose(control_connection_t *conn,
149 uint32_t len, const char *body);
150 static int handle_control_attachstream(control_connection_t *conn,
151 uint32_t len,
152 const char *body);
153 static int handle_control_postdescriptor(control_connection_t *conn,
154 uint32_t len,
155 const char *body);
156 static int handle_control_redirectstream(control_connection_t *conn,
157 uint32_t len,
158 const char *body);
159 static int handle_control_closestream(control_connection_t *conn, uint32_t len,
160 const char *body);
161 static int handle_control_closecircuit(control_connection_t *conn,
162 uint32_t len,
163 const char *body);
164 static int handle_control_resolve(control_connection_t *conn, uint32_t len,
165 const char *body);
166 static int handle_control_usefeature(control_connection_t *conn,
167 uint32_t len,
168 const char *body);
169 static int write_stream_target_to_buf(edge_connection_t *conn, char *buf,
170 size_t len);
171 static void orconn_target_get_name(char *buf, size_t len,
172 or_connection_t *conn);
173 static char *get_cookie_file(void);
175 /** Given a control event code for a message event, return the corresponding
176 * log severity. */
177 static INLINE int
178 event_to_log_severity(int event)
180 switch (event) {
181 case EVENT_DEBUG_MSG: return LOG_DEBUG;
182 case EVENT_INFO_MSG: return LOG_INFO;
183 case EVENT_NOTICE_MSG: return LOG_NOTICE;
184 case EVENT_WARN_MSG: return LOG_WARN;
185 case EVENT_ERR_MSG: return LOG_ERR;
186 default: return -1;
190 /** Given a log severity, return the corresponding control event code. */
191 static INLINE int
192 log_severity_to_event(int severity)
194 switch (severity) {
195 case LOG_DEBUG: return EVENT_DEBUG_MSG;
196 case LOG_INFO: return EVENT_INFO_MSG;
197 case LOG_NOTICE: return EVENT_NOTICE_MSG;
198 case LOG_WARN: return EVENT_WARN_MSG;
199 case LOG_ERR: return EVENT_ERR_MSG;
200 default: return -1;
204 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
205 * connection's event_mask field. */
206 void
207 control_update_global_event_mask(void)
209 smartlist_t *conns = get_connection_array();
210 event_mask_t old_mask, new_mask;
211 old_mask = global_event_mask;
213 global_event_mask = 0;
214 SMARTLIST_FOREACH(conns, connection_t *, _conn,
216 if (_conn->type == CONN_TYPE_CONTROL &&
217 STATE_IS_OPEN(_conn->state)) {
218 control_connection_t *conn = TO_CONTROL_CONN(_conn);
219 global_event_mask |= conn->event_mask;
223 new_mask = global_event_mask;
225 /* Handle the aftermath. Set up the log callback to tell us only what
226 * we want to hear...*/
227 control_adjust_event_log_severity();
229 /* ...then, if we've started logging stream bw, clear the appropriate
230 * fields. */
231 if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
232 (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
233 SMARTLIST_FOREACH(conns, connection_t *, conn,
235 if (conn->type == CONN_TYPE_AP) {
236 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
237 edge_conn->n_written = edge_conn->n_read = 0;
243 /** Adjust the log severities that result in control_event_logmsg being called
244 * to match the severity of log messages that any controllers are interested
245 * in. */
246 void
247 control_adjust_event_log_severity(void)
249 int i;
250 int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
252 for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
253 if (EVENT_IS_INTERESTING(i)) {
254 min_log_event = i;
255 break;
258 for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
259 if (EVENT_IS_INTERESTING(i)) {
260 max_log_event = i;
261 break;
264 if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE) ||
265 EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
266 if (min_log_event > EVENT_NOTICE_MSG)
267 min_log_event = EVENT_NOTICE_MSG;
268 if (max_log_event < EVENT_ERR_MSG)
269 max_log_event = EVENT_ERR_MSG;
271 if (min_log_event <= max_log_event)
272 change_callback_log_severity(event_to_log_severity(min_log_event),
273 event_to_log_severity(max_log_event),
274 control_event_logmsg);
275 else
276 change_callback_log_severity(LOG_ERR, LOG_ERR,
277 control_event_logmsg);
280 /** Return true iff the event with code <b>c</b> is being sent to any current
281 * control connection. This is useful if the amount of work needed to prepare
282 * to call the appropriate control_event_...() function is high.
285 control_event_is_interesting(int event)
287 return EVENT_IS_INTERESTING(event);
290 /** Append a NUL-terminated string <b>s</b> to the end of
291 * <b>conn</b>-\>outbuf.
293 static INLINE void
294 connection_write_str_to_buf(const char *s, control_connection_t *conn)
296 size_t len = strlen(s);
297 connection_write_to_buf(s, len, TO_CONN(conn));
300 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
301 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
302 * contents of <b>data</b> into *<b>out</b>, adding a period before any period
303 * that appears at the start of a line, and adding a period-CRLF line at
304 * the end. Replace all LF characters sequences with CRLF. Return the number
305 * of bytes in *<b>out</b>.
307 /* static */ size_t
308 write_escaped_data(const char *data, size_t len, char **out)
310 size_t sz_out = len+8;
311 char *outp;
312 const char *start = data, *end;
313 int i;
314 int start_of_line;
315 for (i=0; i<(int)len; ++i) {
316 if (data[i]== '\n')
317 sz_out += 2; /* Maybe add a CR; maybe add a dot. */
319 *out = outp = tor_malloc(sz_out+1);
320 end = data+len;
321 start_of_line = 1;
322 while (data < end) {
323 if (*data == '\n') {
324 if (data > start && data[-1] != '\r')
325 *outp++ = '\r';
326 start_of_line = 1;
327 } else if (*data == '.') {
328 if (start_of_line) {
329 start_of_line = 0;
330 *outp++ = '.';
332 } else {
333 start_of_line = 0;
335 *outp++ = *data++;
337 if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
338 *outp++ = '\r';
339 *outp++ = '\n';
341 *outp++ = '.';
342 *outp++ = '\r';
343 *outp++ = '\n';
344 *outp = '\0'; /* NUL-terminate just in case. */
345 tor_assert((outp - *out) <= (int)sz_out);
346 return outp - *out;
349 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
350 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
351 * the contents of <b>data</b> into *<b>out</b>, removing any period
352 * that appears at the start of a line, and replacing all CRLF sequences
353 * with LF. Return the number of
354 * bytes in *<b>out</b>. */
355 /* static */ size_t
356 read_escaped_data(const char *data, size_t len, char **out)
358 char *outp;
359 const char *next;
360 const char *end;
362 *out = outp = tor_malloc(len+1);
364 end = data+len;
366 while (data < end) {
367 /* we're at the start of a line. */
368 if (*data == '.')
369 ++data;
370 next = memchr(data, '\n', end-data);
371 if (next) {
372 size_t n_to_copy = next-data;
373 /* Don't copy a CR that precedes this LF. */
374 if (n_to_copy && *(next-1) == '\r')
375 --n_to_copy;
376 memcpy(outp, data, n_to_copy);
377 outp += n_to_copy;
378 data = next+1; /* This will point at the start of the next line,
379 * or the end of the string, or a period. */
380 } else {
381 memcpy(outp, data, end-data);
382 outp += (end-data);
383 *outp = '\0';
384 return outp - *out;
386 *outp++ = '\n';
389 *outp = '\0';
390 return outp - *out;
393 /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
394 * double-quoted string with escaped characters, return the length of that
395 * string (as encoded, including quotes). Otherwise return -1. */
396 static INLINE int
397 get_escaped_string_length(const char *start, size_t in_len_max,
398 int *chars_out)
400 const char *cp, *end;
401 int chars = 0;
403 if (*start != '\"')
404 return -1;
406 cp = start+1;
407 end = start+in_len_max;
409 /* Calculate length. */
410 while (1) {
411 if (cp >= end) {
412 return -1; /* Too long. */
413 } else if (*cp == '\\') {
414 if (++cp == end)
415 return -1; /* Can't escape EOS. */
416 ++cp;
417 ++chars;
418 } else if (*cp == '\"') {
419 break;
420 } else {
421 ++cp;
422 ++chars;
425 if (chars_out)
426 *chars_out = chars;
427 return (int)(cp - start+1);
430 /** As decode_escaped_string, but does not decode the string: copies the
431 * entire thing, including quotation marks. */
432 static const char *
433 extract_escaped_string(const char *start, size_t in_len_max,
434 char **out, size_t *out_len)
436 int length = get_escaped_string_length(start, in_len_max, NULL);
437 if (length<0)
438 return NULL;
439 *out_len = length;
440 *out = tor_strndup(start, *out_len);
441 return start+length;
444 /** Given a pointer to a string starting at <b>start</b> containing
445 * <b>in_len_max</b> characters, decode a string beginning with one double
446 * quote, containing any number of non-quote characters or characters escaped
447 * with a backslash, and ending with a final double quote. Place the resulting
448 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
449 * store its length in <b>out_len</b>. On success, return a pointer to the
450 * character immediately following the escaped string. On failure, return
451 * NULL. */
452 static const char *
453 decode_escaped_string(const char *start, size_t in_len_max,
454 char **out, size_t *out_len)
456 const char *cp, *end;
457 char *outp;
458 int len, n_chars = 0;
460 len = get_escaped_string_length(start, in_len_max, &n_chars);
461 if (len<0)
462 return NULL;
464 end = start+len-1; /* Index of last quote. */
465 tor_assert(*end == '\"');
466 outp = *out = tor_malloc(len+1);
467 *out_len = n_chars;
469 cp = start+1;
470 while (cp < end) {
471 if (*cp == '\\')
472 ++cp;
473 *outp++ = *cp++;
475 *outp = '\0';
476 tor_assert((outp - *out) == (int)*out_len);
478 return end+1;
481 /** Acts like sprintf, but writes its formatted string to the end of
482 * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
483 * but it will always end with a CRLF sequence.
485 * Currently the length of the message is limited to 1024 (including the
486 * ending CR LF NUL ("\\r\\n\\0"). */
487 static void
488 connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
490 #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
491 va_list ap;
492 char buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE];
493 int r;
494 size_t len;
495 va_start(ap,format);
496 r = tor_vsnprintf(buf, sizeof(buf), format, ap);
497 va_end(ap);
498 if (r<0) {
499 log_warn(LD_BUG, "Unable to format string for controller.");
500 return;
502 len = strlen(buf);
503 if (memcmp("\r\n\0", buf+len-2, 3)) {
504 buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-1] = '\0';
505 buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-2] = '\n';
506 buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-3] = '\r';
508 connection_write_to_buf(buf, len, TO_CONN(conn));
511 /** Send a "DONE" message down the control connection <b>conn</b>. */
512 static void
513 send_control_done(control_connection_t *conn)
515 connection_write_str_to_buf("250 OK\r\n", conn);
518 /** Send an event to all v1 controllers that are listening for code
519 * <b>event</b>. The event's body is given by <b>msg</b>.
521 * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
522 * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
523 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
524 * to controllers that <em>have</em> enabled VERBOSE_NAMES.
526 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
527 * respect to the EXTENDED_EVENTS feature. */
528 static void
529 send_control_event_string(uint16_t event, event_format_t which,
530 const char *msg)
532 smartlist_t *conns = get_connection_array();
533 (void)which;
534 tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);
536 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
537 if (conn->type == CONN_TYPE_CONTROL &&
538 !conn->marked_for_close &&
539 conn->state == CONTROL_CONN_STATE_OPEN) {
540 control_connection_t *control_conn = TO_CONTROL_CONN(conn);
542 if (control_conn->event_mask & (1<<event)) {
543 int is_err = 0;
544 connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
545 if (event == EVENT_ERR_MSG)
546 is_err = 1;
547 else if (event == EVENT_STATUS_GENERAL)
548 is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
549 else if (event == EVENT_STATUS_CLIENT)
550 is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
551 else if (event == EVENT_STATUS_SERVER)
552 is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
553 if (is_err)
554 connection_handle_write(TO_CONN(control_conn), 1);
557 } SMARTLIST_FOREACH_END(conn);
560 /** Helper for send_control1_event and send_control1_event_extended:
561 * Send an event to all v1 controllers that are listening for code
562 * <b>event</b>. The event's body is created by the printf-style format in
563 * <b>format</b>, and other arguments as provided.
565 * Currently the length of the message is limited to 1024 (including the
566 * ending \\r\\n\\0). */
567 static void
568 send_control_event_impl(uint16_t event, event_format_t which,
569 const char *format, va_list ap)
571 /* This is just a little longer than the longest allowed log message */
572 #define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
573 int r;
574 char buf[SEND_CONTROL1_EVENT_BUFFERSIZE];
575 size_t len;
577 r = tor_vsnprintf(buf, sizeof(buf), format, ap);
578 if (r<0) {
579 log_warn(LD_BUG, "Unable to format event for controller.");
580 return;
583 len = strlen(buf);
584 if (memcmp("\r\n\0", buf+len-2, 3)) {
585 /* if it is not properly terminated, do it now */
586 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-1] = '\0';
587 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-2] = '\n';
588 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-3] = '\r';
591 send_control_event_string(event, which|ALL_FORMATS, buf);
594 /** Send an event to all v1 controllers that are listening for code
595 * <b>event</b>. The event's body is created by the printf-style format in
596 * <b>format</b>, and other arguments as provided.
598 * Currently the length of the message is limited to 1024 (including the
599 * ending \\n\\r\\0. */
600 static void
601 send_control_event(uint16_t event, event_format_t which,
602 const char *format, ...)
604 va_list ap;
605 va_start(ap, format);
606 send_control_event_impl(event, which, format, ap);
607 va_end(ap);
610 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
611 static origin_circuit_t *
612 get_circ(const char *id)
614 uint32_t n_id;
615 int ok;
616 n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
617 if (!ok)
618 return NULL;
619 return circuit_get_by_global_id(n_id);
622 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
623 static edge_connection_t *
624 get_stream(const char *id)
626 uint64_t n_id;
627 int ok;
628 connection_t *conn;
629 n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
630 if (!ok)
631 return NULL;
632 conn = connection_get_by_global_id(n_id);
633 if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
634 return NULL;
635 return TO_EDGE_CONN(conn);
638 /** Helper for setconf and resetconf. Acts like setconf, except
639 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
640 * contents of body.
642 static int
643 control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
644 int use_defaults)
646 setopt_err_t opt_err;
647 config_line_t *lines=NULL;
648 char *start = body;
649 char *errstring = NULL;
650 const int clear_first = 1;
652 char *config;
653 smartlist_t *entries = smartlist_create();
655 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
656 * separated by space. break it into a list of configuration entries. */
657 while (*body) {
658 char *eq = body;
659 char *key;
660 char *entry;
661 while (!TOR_ISSPACE(*eq) && *eq != '=')
662 ++eq;
663 key = tor_strndup(body, eq-body);
664 body = eq+1;
665 if (*eq == '=') {
666 char *val=NULL;
667 size_t val_len=0;
668 size_t ent_len;
669 if (*body != '\"') {
670 char *val_start = body;
671 while (!TOR_ISSPACE(*body))
672 body++;
673 val = tor_strndup(val_start, body-val_start);
674 val_len = strlen(val);
675 } else {
676 body = (char*)extract_escaped_string(body, (len - (body-start)),
677 &val, &val_len);
678 if (!body) {
679 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
680 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
681 smartlist_free(entries);
682 tor_free(key);
683 return 0;
686 ent_len = strlen(key)+val_len+3;
687 entry = tor_malloc(ent_len+1);
688 tor_snprintf(entry, ent_len, "%s %s", key, val);
689 tor_free(key);
690 tor_free(val);
691 } else {
692 entry = key;
694 smartlist_add(entries, entry);
695 while (TOR_ISSPACE(*body))
696 ++body;
699 smartlist_add(entries, tor_strdup(""));
700 config = smartlist_join_strings(entries, "\n", 0, NULL);
701 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
702 smartlist_free(entries);
704 if (config_get_lines(config, &lines) < 0) {
705 log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
706 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
707 conn);
708 tor_free(config);
709 return 0;
711 tor_free(config);
713 opt_err = options_trial_assign(lines, use_defaults, clear_first, &errstring);
715 const char *msg;
716 switch (opt_err) {
717 case SETOPT_ERR_MISC:
718 msg = "552 Unrecognized option";
719 break;
720 case SETOPT_ERR_PARSE:
721 msg = "513 Unacceptable option value";
722 break;
723 case SETOPT_ERR_TRANSITION:
724 msg = "553 Transition not allowed";
725 break;
726 case SETOPT_ERR_SETTING:
727 default:
728 msg = "553 Unable to set option";
729 break;
730 case SETOPT_OK:
731 config_free_lines(lines);
732 send_control_done(conn);
733 return 0;
735 log_warn(LD_CONTROL,
736 "Controller gave us config lines that didn't validate: %s",
737 errstring);
738 connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
739 config_free_lines(lines);
740 tor_free(errstring);
741 return 0;
745 /** Called when we receive a SETCONF message: parse the body and try
746 * to update our configuration. Reply with a DONE or ERROR message.
747 * Modifies the contents of body.*/
748 static int
749 handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
751 return control_setconf_helper(conn, len, body, 0);
754 /** Called when we receive a RESETCONF message: parse the body and try
755 * to update our configuration. Reply with a DONE or ERROR message.
756 * Modifies the contents of body. */
757 static int
758 handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
760 return control_setconf_helper(conn, len, body, 1);
763 /** Called when we receive a GETCONF message. Parse the request, and
764 * reply with a CONFVALUE or an ERROR message */
765 static int
766 handle_control_getconf(control_connection_t *conn, uint32_t body_len,
767 const char *body)
769 smartlist_t *questions = smartlist_create();
770 smartlist_t *answers = smartlist_create();
771 smartlist_t *unrecognized = smartlist_create();
772 char *msg = NULL;
773 size_t msg_len;
774 or_options_t *options = get_options();
775 int i, len;
777 (void) body_len; /* body is NUL-terminated; so we can ignore len. */
778 smartlist_split_string(questions, body, " ",
779 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
780 SMARTLIST_FOREACH(questions, const char *, q,
782 if (!option_is_recognized(q)) {
783 smartlist_add(unrecognized, (char*) q);
784 } else {
785 config_line_t *answer = option_get_assignment(options,q);
786 if (!answer) {
787 const char *name = option_get_canonical_name(q);
788 size_t alen = strlen(name)+8;
789 char *astr = tor_malloc(alen);
790 tor_snprintf(astr, alen, "250-%s\r\n", name);
791 smartlist_add(answers, astr);
794 while (answer) {
795 config_line_t *next;
796 size_t alen = strlen(answer->key)+strlen(answer->value)+8;
797 char *astr = tor_malloc(alen);
798 tor_snprintf(astr, alen, "250-%s=%s\r\n",
799 answer->key, answer->value);
800 smartlist_add(answers, astr);
802 next = answer->next;
803 tor_free(answer->key);
804 tor_free(answer->value);
805 tor_free(answer);
806 answer = next;
811 if ((len = smartlist_len(unrecognized))) {
812 for (i=0; i < len-1; ++i)
813 connection_printf_to_buf(conn,
814 "552-Unrecognized configuration key \"%s\"\r\n",
815 (char*)smartlist_get(unrecognized, i));
816 connection_printf_to_buf(conn,
817 "552 Unrecognized configuration key \"%s\"\r\n",
818 (char*)smartlist_get(unrecognized, len-1));
819 } else if ((len = smartlist_len(answers))) {
820 char *tmp = smartlist_get(answers, len-1);
821 tor_assert(strlen(tmp)>4);
822 tmp[3] = ' ';
823 msg = smartlist_join_strings(answers, "", 0, &msg_len);
824 connection_write_to_buf(msg, msg_len, TO_CONN(conn));
825 } else {
826 connection_write_str_to_buf("250 OK\r\n", conn);
829 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
830 smartlist_free(answers);
831 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
832 smartlist_free(questions);
833 smartlist_free(unrecognized);
835 tor_free(msg);
837 return 0;
840 /** Called when we get a +LOADCONF message. */
841 static int
842 handle_control_loadconf(control_connection_t *conn, uint32_t len,
843 const char *body)
845 setopt_err_t retval;
846 char *errstring = NULL;
847 const char *msg = NULL;
848 (void) len;
850 retval = options_init_from_string(body, CMD_RUN_TOR, NULL, &errstring);
852 if (retval != SETOPT_OK)
853 log_warn(LD_CONTROL,
854 "Controller gave us config file that didn't validate: %s",
855 errstring);
857 switch (retval) {
858 case SETOPT_ERR_PARSE:
859 msg = "552 Invalid config file";
860 break;
861 case SETOPT_ERR_TRANSITION:
862 msg = "553 Transition not allowed";
863 break;
864 case SETOPT_ERR_SETTING:
865 msg = "553 Unable to set option";
866 break;
867 case SETOPT_ERR_MISC:
868 default:
869 msg = "550 Unable to load config";
870 break;
871 case SETOPT_OK:
872 break;
874 if (msg) {
875 if (errstring)
876 connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
877 else
878 connection_printf_to_buf(conn, "%s\r\n", msg);
879 } else {
880 send_control_done(conn);
882 tor_free(errstring);
883 return 0;
886 /** Called when we get a SETEVENTS message: update conn->event_mask,
887 * and reply with DONE or ERROR. */
888 static int
889 handle_control_setevents(control_connection_t *conn, uint32_t len,
890 const char *body)
892 uint16_t event_code;
893 uint32_t event_mask = 0;
894 smartlist_t *events = smartlist_create();
896 (void) len;
898 smartlist_split_string(events, body, " ",
899 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
900 SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
902 if (!strcasecmp(ev, "EXTENDED")) {
903 continue;
904 } else if (!strcasecmp(ev, "CIRC"))
905 event_code = EVENT_CIRCUIT_STATUS;
906 else if (!strcasecmp(ev, "STREAM"))
907 event_code = EVENT_STREAM_STATUS;
908 else if (!strcasecmp(ev, "ORCONN"))
909 event_code = EVENT_OR_CONN_STATUS;
910 else if (!strcasecmp(ev, "BW"))
911 event_code = EVENT_BANDWIDTH_USED;
912 else if (!strcasecmp(ev, "DEBUG"))
913 event_code = EVENT_DEBUG_MSG;
914 else if (!strcasecmp(ev, "INFO"))
915 event_code = EVENT_INFO_MSG;
916 else if (!strcasecmp(ev, "NOTICE"))
917 event_code = EVENT_NOTICE_MSG;
918 else if (!strcasecmp(ev, "WARN"))
919 event_code = EVENT_WARN_MSG;
920 else if (!strcasecmp(ev, "ERR"))
921 event_code = EVENT_ERR_MSG;
922 else if (!strcasecmp(ev, "NEWDESC"))
923 event_code = EVENT_NEW_DESC;
924 else if (!strcasecmp(ev, "ADDRMAP"))
925 event_code = EVENT_ADDRMAP;
926 else if (!strcasecmp(ev, "AUTHDIR_NEWDESCS"))
927 event_code = EVENT_AUTHDIR_NEWDESCS;
928 else if (!strcasecmp(ev, "DESCCHANGED"))
929 event_code = EVENT_DESCCHANGED;
930 else if (!strcasecmp(ev, "NS"))
931 event_code = EVENT_NS;
932 else if (!strcasecmp(ev, "STATUS_GENERAL"))
933 event_code = EVENT_STATUS_GENERAL;
934 else if (!strcasecmp(ev, "STATUS_CLIENT"))
935 event_code = EVENT_STATUS_CLIENT;
936 else if (!strcasecmp(ev, "STATUS_SERVER"))
937 event_code = EVENT_STATUS_SERVER;
938 else if (!strcasecmp(ev, "GUARD"))
939 event_code = EVENT_GUARD;
940 else if (!strcasecmp(ev, "STREAM_BW"))
941 event_code = EVENT_STREAM_BANDWIDTH_USED;
942 else if (!strcasecmp(ev, "CLIENTS_SEEN"))
943 event_code = EVENT_CLIENTS_SEEN;
944 else if (!strcasecmp(ev, "NEWCONSENSUS"))
945 event_code = EVENT_NEWCONSENSUS;
946 else if (!strcasecmp(ev, "BUILDTIMEOUT_SET"))
947 event_code = EVENT_BUILDTIMEOUT_SET;
948 else {
949 connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
950 ev);
951 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
952 smartlist_free(events);
953 return 0;
955 event_mask |= (1 << event_code);
957 SMARTLIST_FOREACH_END(ev);
958 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
959 smartlist_free(events);
961 conn->event_mask = event_mask;
963 control_update_global_event_mask();
964 send_control_done(conn);
965 return 0;
968 /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
969 * Return a smartlist of acceptable passwords (unterminated strings of
970 * length S2K_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on failure.
972 smartlist_t *
973 decode_hashed_passwords(config_line_t *passwords)
975 char decoded[64];
976 config_line_t *cl;
977 smartlist_t *sl = smartlist_create();
979 tor_assert(passwords);
981 for (cl = passwords; cl; cl = cl->next) {
982 const char *hashed = cl->value;
984 if (!strcmpstart(hashed, "16:")) {
985 if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
986 || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
987 goto err;
989 } else {
990 if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
991 != S2K_SPECIFIER_LEN+DIGEST_LEN) {
992 goto err;
995 smartlist_add(sl, tor_memdup(decoded, S2K_SPECIFIER_LEN+DIGEST_LEN));
998 return sl;
1000 err:
1001 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
1002 smartlist_free(sl);
1003 return NULL;
1006 /** Called when we get an AUTHENTICATE message. Check whether the
1007 * authentication is valid, and if so, update the connection's state to
1008 * OPEN. Reply with DONE or ERROR.
1010 static int
1011 handle_control_authenticate(control_connection_t *conn, uint32_t len,
1012 const char *body)
1014 int used_quoted_string = 0;
1015 or_options_t *options = get_options();
1016 const char *errstr = NULL;
1017 char *password;
1018 size_t password_len;
1019 const char *cp;
1020 int i;
1021 int bad_cookie=0, bad_password=0;
1022 smartlist_t *sl = NULL;
1024 if (TOR_ISXDIGIT(body[0])) {
1025 cp = body;
1026 while (TOR_ISXDIGIT(*cp))
1027 ++cp;
1028 i = (int)(cp - body);
1029 tor_assert(i>0);
1030 password_len = i/2;
1031 password = tor_malloc(password_len + 1);
1032 if (base16_decode(password, password_len+1, body, i)<0) {
1033 connection_write_str_to_buf(
1034 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1035 "password? If so, the standard requires that you put it in "
1036 "double quotes.\r\n", conn);
1037 connection_mark_for_close(TO_CONN(conn));
1038 tor_free(password);
1039 return 0;
1041 } else if (TOR_ISSPACE(body[0])) {
1042 password = tor_strdup("");
1043 password_len = 0;
1044 } else {
1045 if (!decode_escaped_string(body, len, &password, &password_len)) {
1046 connection_write_str_to_buf("551 Invalid quoted string. You need "
1047 "to put the password in double quotes.\r\n", conn);
1048 connection_mark_for_close(TO_CONN(conn));
1049 return 0;
1051 used_quoted_string = 1;
1054 if (!options->CookieAuthentication && !options->HashedControlPassword &&
1055 !options->HashedControlSessionPassword) {
1056 /* if Tor doesn't demand any stronger authentication, then
1057 * the controller can get in with anything. */
1058 goto ok;
1061 if (options->CookieAuthentication) {
1062 int also_password = options->HashedControlPassword != NULL ||
1063 options->HashedControlSessionPassword != NULL;
1064 if (password_len != AUTHENTICATION_COOKIE_LEN) {
1065 if (!also_password) {
1066 log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
1067 "(%d)", (int)password_len);
1068 errstr = "Wrong length on authentication cookie.";
1069 goto err;
1071 bad_cookie = 1;
1072 } else if (memcmp(authentication_cookie, password, password_len)) {
1073 if (!also_password) {
1074 log_warn(LD_CONTROL, "Got mismatched authentication cookie");
1075 errstr = "Authentication cookie did not match expected value.";
1076 goto err;
1078 bad_cookie = 1;
1079 } else {
1080 goto ok;
1084 if (options->HashedControlPassword ||
1085 options->HashedControlSessionPassword) {
1086 int bad = 0;
1087 smartlist_t *sl_tmp;
1088 char received[DIGEST_LEN];
1089 int also_cookie = options->CookieAuthentication;
1090 sl = smartlist_create();
1091 if (options->HashedControlPassword) {
1092 sl_tmp = decode_hashed_passwords(options->HashedControlPassword);
1093 if (!sl_tmp)
1094 bad = 1;
1095 else {
1096 smartlist_add_all(sl, sl_tmp);
1097 smartlist_free(sl_tmp);
1100 if (options->HashedControlSessionPassword) {
1101 sl_tmp = decode_hashed_passwords(options->HashedControlSessionPassword);
1102 if (!sl_tmp)
1103 bad = 1;
1104 else {
1105 smartlist_add_all(sl, sl_tmp);
1106 smartlist_free(sl_tmp);
1109 if (bad) {
1110 if (!also_cookie) {
1111 log_warn(LD_CONTROL,
1112 "Couldn't decode HashedControlPassword: invalid base16");
1113 errstr="Couldn't decode HashedControlPassword value in configuration.";
1115 bad_password = 1;
1116 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1117 smartlist_free(sl);
1118 } else {
1119 SMARTLIST_FOREACH(sl, char *, expected,
1121 secret_to_key(received,DIGEST_LEN,password,password_len,expected);
1122 if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
1123 goto ok;
1125 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1126 smartlist_free(sl);
1128 if (used_quoted_string)
1129 errstr = "Password did not match HashedControlPassword value from "
1130 "configuration";
1131 else
1132 errstr = "Password did not match HashedControlPassword value from "
1133 "configuration. Maybe you tried a plain text password? "
1134 "If so, the standard requires that you put it in double quotes.";
1135 bad_password = 1;
1136 if (!also_cookie)
1137 goto err;
1141 /** We only get here if both kinds of authentication failed. */
1142 tor_assert(bad_password && bad_cookie);
1143 log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
1144 errstr = "Password did not match HashedControlPassword *or* authentication "
1145 "cookie.";
1147 err:
1148 tor_free(password);
1149 connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n",
1150 errstr ? errstr : "Unknown reason.");
1151 connection_mark_for_close(TO_CONN(conn));
1152 return 0;
1154 log_info(LD_CONTROL, "Authenticated control connection (%d)", conn->_base.s);
1155 send_control_done(conn);
1156 conn->_base.state = CONTROL_CONN_STATE_OPEN;
1157 tor_free(password);
1158 if (sl) { /* clean up */
1159 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1160 smartlist_free(sl);
1162 return 0;
1165 /** Called when we get a SAVECONF command. Try to flush the current options to
1166 * disk, and report success or failure. */
1167 static int
1168 handle_control_saveconf(control_connection_t *conn, uint32_t len,
1169 const char *body)
1171 (void) len;
1172 (void) body;
1173 if (options_save_current()<0) {
1174 connection_write_str_to_buf(
1175 "551 Unable to write configuration to disk.\r\n", conn);
1176 } else {
1177 send_control_done(conn);
1179 return 0;
1182 /** Called when we get a SIGNAL command. React to the provided signal, and
1183 * report success or failure. (If the signal results in a shutdown, success
1184 * may not be reported.) */
1185 static int
1186 handle_control_signal(control_connection_t *conn, uint32_t len,
1187 const char *body)
1189 int sig;
1190 int n = 0;
1191 char *s;
1193 (void) len;
1195 while (body[n] && ! TOR_ISSPACE(body[n]))
1196 ++n;
1197 s = tor_strndup(body, n);
1198 if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
1199 sig = SIGHUP;
1200 else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
1201 sig = SIGINT;
1202 else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
1203 sig = SIGUSR1;
1204 else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
1205 sig = SIGUSR2;
1206 else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
1207 sig = SIGTERM;
1208 else if (!strcasecmp(s, "NEWNYM"))
1209 sig = SIGNEWNYM;
1210 else if (!strcasecmp(s, "CLEARDNSCACHE"))
1211 sig = SIGCLEARDNSCACHE;
1212 else {
1213 connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
1215 sig = -1;
1217 tor_free(s);
1218 if (sig<0)
1219 return 0;
1221 send_control_done(conn);
1222 /* Flush the "done" first if the signal might make us shut down. */
1223 if (sig == SIGTERM || sig == SIGINT)
1224 connection_handle_write(TO_CONN(conn), 1);
1225 signal_callback(0,0,(void*)(uintptr_t)sig);
1227 return 0;
1230 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1231 * and report success or failure. */
1232 static int
1233 handle_control_mapaddress(control_connection_t *conn, uint32_t len,
1234 const char *body)
1236 smartlist_t *elts;
1237 smartlist_t *lines;
1238 smartlist_t *reply;
1239 char *r;
1240 size_t sz;
1241 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
1243 lines = smartlist_create();
1244 elts = smartlist_create();
1245 reply = smartlist_create();
1246 smartlist_split_string(lines, body, " ",
1247 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1248 SMARTLIST_FOREACH(lines, char *, line,
1250 tor_strlower(line);
1251 smartlist_split_string(elts, line, "=", 0, 2);
1252 if (smartlist_len(elts) == 2) {
1253 const char *from = smartlist_get(elts,0);
1254 const char *to = smartlist_get(elts,1);
1255 size_t anslen = strlen(line)+512;
1256 char *ans = tor_malloc(anslen);
1257 if (address_is_invalid_destination(to, 1)) {
1258 tor_snprintf(ans, anslen,
1259 "512-syntax error: invalid address '%s'", to);
1260 smartlist_add(reply, ans);
1261 log_warn(LD_CONTROL,
1262 "Skipping invalid argument '%s' in MapAddress msg", to);
1263 } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
1264 const char *address = addressmap_register_virtual_address(
1265 !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
1266 tor_strdup(to));
1267 if (!address) {
1268 tor_snprintf(ans, anslen,
1269 "451-resource exhausted: skipping '%s'", line);
1270 smartlist_add(reply, ans);
1271 log_warn(LD_CONTROL,
1272 "Unable to allocate address for '%s' in MapAddress msg",
1273 safe_str_client(line));
1274 } else {
1275 tor_snprintf(ans, anslen, "250-%s=%s", address, to);
1276 smartlist_add(reply, ans);
1278 } else {
1279 addressmap_register(from, tor_strdup(to), 1, ADDRMAPSRC_CONTROLLER);
1280 tor_snprintf(ans, anslen, "250-%s", line);
1281 smartlist_add(reply, ans);
1283 } else {
1284 size_t anslen = strlen(line)+256;
1285 char *ans = tor_malloc(anslen);
1286 tor_snprintf(ans, anslen, "512-syntax error: mapping '%s' is "
1287 "not of expected form 'foo=bar'.", line);
1288 smartlist_add(reply, ans);
1289 log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
1290 "number of items.",
1291 safe_str_client(line));
1293 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
1294 smartlist_clear(elts);
1296 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1297 smartlist_free(lines);
1298 smartlist_free(elts);
1300 if (smartlist_len(reply)) {
1301 ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
1302 r = smartlist_join_strings(reply, "\r\n", 1, &sz);
1303 connection_write_to_buf(r, sz, TO_CONN(conn));
1304 tor_free(r);
1305 } else {
1306 const char *response =
1307 "512 syntax error: not enough arguments to mapaddress.\r\n";
1308 connection_write_to_buf(response, strlen(response), TO_CONN(conn));
1311 SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
1312 smartlist_free(reply);
1313 return 0;
1316 /** Implementation helper for GETINFO: knows the answers for various
1317 * trivial-to-implement questions. */
1318 static int
1319 getinfo_helper_misc(control_connection_t *conn, const char *question,
1320 char **answer, const char **errmsg)
1322 (void) conn;
1323 if (!strcmp(question, "version")) {
1324 *answer = tor_strdup(get_version());
1325 } else if (!strcmp(question, "config-file")) {
1326 *answer = tor_strdup(get_torrc_fname());
1327 } else if (!strcmp(question, "config-text")) {
1328 *answer = options_dump(get_options(), 1);
1329 } else if (!strcmp(question, "info/names")) {
1330 *answer = list_getinfo_options();
1331 } else if (!strcmp(question, "events/names")) {
1332 *answer = tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
1333 "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
1334 "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
1335 "GUARD STREAM_BW CLIENTS_SEEN NEWCONSENSUS");
1336 } else if (!strcmp(question, "features/names")) {
1337 *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1338 } else if (!strcmp(question, "address")) {
1339 uint32_t addr;
1340 if (router_pick_published_address(get_options(), &addr) < 0) {
1341 *errmsg = "Address unknown";
1342 return -1;
1344 *answer = tor_dup_ip(addr);
1345 } else if (!strcmp(question, "dir-usage")) {
1346 *answer = directory_dump_request_log();
1347 } else if (!strcmp(question, "fingerprint")) {
1348 routerinfo_t *me = router_get_my_routerinfo();
1349 if (!me) {
1350 *errmsg = "No routerdesc known; am I really a server?";
1351 return -1;
1353 *answer = tor_malloc(HEX_DIGEST_LEN+1);
1354 base16_encode(*answer, HEX_DIGEST_LEN+1, me->cache_info.identity_digest,
1355 DIGEST_LEN);
1357 return 0;
1360 /** Awful hack: return a newly allocated string based on a routerinfo and
1361 * (possibly) an extrainfo, sticking the read-history and write-history from
1362 * <b>ei</b> into the resulting string. The thing you get back won't
1363 * necessarily have a valid signature.
1365 * New code should never use this; it's for backward compatibility.
1367 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1368 * not be NUL-terminated. */
1369 static char *
1370 munge_extrainfo_into_routerinfo(const char *ri_body, signed_descriptor_t *ri,
1371 signed_descriptor_t *ei)
1373 char *out = NULL, *outp;
1374 int i;
1375 const char *router_sig;
1376 const char *ei_body = signed_descriptor_get_body(ei);
1377 size_t ri_len = ri->signed_descriptor_len;
1378 size_t ei_len = ei->signed_descriptor_len;
1379 if (!ei_body)
1380 goto bail;
1382 outp = out = tor_malloc(ri_len+ei_len+1);
1383 if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
1384 goto bail;
1385 ++router_sig;
1386 memcpy(out, ri_body, router_sig-ri_body);
1387 outp += router_sig-ri_body;
1389 for (i=0; i < 2; ++i) {
1390 const char *kwd = i?"\nwrite-history ":"\nread-history ";
1391 const char *cp, *eol;
1392 if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
1393 continue;
1394 ++cp;
1395 eol = memchr(cp, '\n', ei_len - (cp-ei_body));
1396 memcpy(outp, cp, eol-cp+1);
1397 outp += eol-cp+1;
1399 memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
1400 *outp++ = '\0';
1401 tor_assert(outp-out < (int)(ri_len+ei_len+1));
1403 return out;
1404 bail:
1405 tor_free(out);
1406 return tor_strndup(ri_body, ri->signed_descriptor_len);
1409 /** Implementation helper for GETINFO: knows the answers for questions about
1410 * directory information. */
1411 static int
1412 getinfo_helper_dir(control_connection_t *control_conn,
1413 const char *question, char **answer,
1414 const char **errmsg)
1416 (void) control_conn;
1417 if (!strcmpstart(question, "desc/id/")) {
1418 routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
1419 if (ri) {
1420 const char *body = signed_descriptor_get_body(&ri->cache_info);
1421 if (body)
1422 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1424 } else if (!strcmpstart(question, "desc/name/")) {
1425 routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
1426 if (ri) {
1427 const char *body = signed_descriptor_get_body(&ri->cache_info);
1428 if (body)
1429 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1431 } else if (!strcmp(question, "desc/all-recent")) {
1432 routerlist_t *routerlist = router_get_routerlist();
1433 smartlist_t *sl = smartlist_create();
1434 if (routerlist && routerlist->routers) {
1435 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
1437 const char *body = signed_descriptor_get_body(&ri->cache_info);
1438 if (body)
1439 smartlist_add(sl,
1440 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1443 *answer = smartlist_join_strings(sl, "", 0, NULL);
1444 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1445 smartlist_free(sl);
1446 } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
1447 /* XXXX Remove this once Torstat asks for extrainfos. */
1448 routerlist_t *routerlist = router_get_routerlist();
1449 smartlist_t *sl = smartlist_create();
1450 if (routerlist && routerlist->routers) {
1451 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
1453 const char *body = signed_descriptor_get_body(&ri->cache_info);
1454 signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
1455 ri->cache_info.extra_info_digest);
1456 if (ei && body) {
1457 smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
1458 &ri->cache_info, ei));
1459 } else if (body) {
1460 smartlist_add(sl,
1461 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1465 *answer = smartlist_join_strings(sl, "", 0, NULL);
1466 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1467 smartlist_free(sl);
1468 } else if (!strcmpstart(question, "desc-annotations/id/")) {
1469 routerinfo_t *ri = router_get_by_hexdigest(question+
1470 strlen("desc-annotations/id/"));
1471 if (ri) {
1472 const char *annotations =
1473 signed_descriptor_get_annotations(&ri->cache_info);
1474 if (annotations)
1475 *answer = tor_strndup(annotations,
1476 ri->cache_info.annotations_len);
1478 } else if (!strcmpstart(question, "dir/server/")) {
1479 size_t answer_len = 0, url_len = strlen(question)+2;
1480 char *url = tor_malloc(url_len);
1481 smartlist_t *descs = smartlist_create();
1482 const char *msg;
1483 int res;
1484 char *cp;
1485 tor_snprintf(url, url_len, "/tor/%s", question+4);
1486 res = dirserv_get_routerdescs(descs, url, &msg);
1487 if (res) {
1488 log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
1489 smartlist_free(descs);
1490 tor_free(url);
1491 *errmsg = msg;
1492 return -1;
1494 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1495 answer_len += sd->signed_descriptor_len);
1496 cp = *answer = tor_malloc(answer_len+1);
1497 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1499 memcpy(cp, signed_descriptor_get_body(sd),
1500 sd->signed_descriptor_len);
1501 cp += sd->signed_descriptor_len;
1503 *cp = '\0';
1504 tor_free(url);
1505 smartlist_free(descs);
1506 } else if (!strcmpstart(question, "dir/status/")) {
1507 if (directory_permits_controller_requests(get_options())) {
1508 size_t len=0;
1509 char *cp;
1510 smartlist_t *status_list = smartlist_create();
1511 dirserv_get_networkstatus_v2(status_list,
1512 question+strlen("dir/status/"));
1513 SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
1514 cp = *answer = tor_malloc(len+1);
1515 SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
1516 memcpy(cp, d->dir, d->dir_len);
1517 cp += d->dir_len;
1519 *cp = '\0';
1520 smartlist_free(status_list);
1521 } else {
1522 smartlist_t *fp_list = smartlist_create();
1523 smartlist_t *status_list = smartlist_create();
1524 dirserv_get_networkstatus_v2_fingerprints(
1525 fp_list, question+strlen("dir/status/"));
1526 SMARTLIST_FOREACH(fp_list, const char *, fp, {
1527 char *s;
1528 char *fname = networkstatus_get_cache_filename(fp);
1529 s = read_file_to_str(fname, 0, NULL);
1530 if (s)
1531 smartlist_add(status_list, s);
1532 tor_free(fname);
1534 SMARTLIST_FOREACH(fp_list, char *, fp, tor_free(fp));
1535 smartlist_free(fp_list);
1536 *answer = smartlist_join_strings(status_list, "", 0, NULL);
1537 SMARTLIST_FOREACH(status_list, char *, s, tor_free(s));
1538 smartlist_free(status_list);
1540 } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
1541 if (directory_caches_dir_info(get_options())) {
1542 const cached_dir_t *consensus = dirserv_get_consensus("ns");
1543 if (consensus)
1544 *answer = tor_strdup(consensus->dir);
1546 if (!*answer) { /* try loading it from disk */
1547 char *filename = get_datadir_fname("cached-consensus");
1548 *answer = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
1549 tor_free(filename);
1551 } else if (!strcmp(question, "network-status")) { /* v1 */
1552 routerlist_t *routerlist = router_get_routerlist();
1553 if (!routerlist || !routerlist->routers ||
1554 list_server_status_v1(routerlist->routers, answer, 1) < 0) {
1555 return -1;
1557 } else if (!strcmpstart(question, "extra-info/digest/")) {
1558 question += strlen("extra-info/digest/");
1559 if (strlen(question) == HEX_DIGEST_LEN) {
1560 char d[DIGEST_LEN];
1561 signed_descriptor_t *sd = NULL;
1562 if (base16_decode(d, sizeof(d), question, strlen(question))==0) {
1563 /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
1564 * but I don't want to risk affecting other parts of the code,
1565 * especially since the rules for using our own extrainfo (including
1566 * when it might be freed) are different from those for using one
1567 * we have downloaded. */
1568 if (router_extrainfo_digest_is_me(d))
1569 sd = &(router_get_my_extrainfo()->cache_info);
1570 else
1571 sd = extrainfo_get_by_descriptor_digest(d);
1573 if (sd) {
1574 const char *body = signed_descriptor_get_body(sd);
1575 if (body)
1576 *answer = tor_strndup(body, sd->signed_descriptor_len);
1581 return 0;
1584 /** Implementation helper for GETINFO: knows how to generate summaries of the
1585 * current states of things we send events about. */
1586 static int
1587 getinfo_helper_events(control_connection_t *control_conn,
1588 const char *question, char **answer,
1589 const char **errmsg)
1591 (void) control_conn;
1592 if (!strcmp(question, "circuit-status")) {
1593 circuit_t *circ;
1594 smartlist_t *status = smartlist_create();
1595 for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
1596 char *s, *path;
1597 size_t slen;
1598 const char *state;
1599 const char *purpose;
1600 if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
1601 continue;
1603 path = circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ));
1605 if (circ->state == CIRCUIT_STATE_OPEN)
1606 state = "BUILT";
1607 else if (strlen(path))
1608 state = "EXTENDED";
1609 else
1610 state = "LAUNCHED";
1612 purpose = circuit_purpose_to_controller_string(circ->purpose);
1613 slen = strlen(path)+strlen(state)+strlen(purpose)+30;
1614 s = tor_malloc(slen+1);
1615 tor_snprintf(s, slen, "%lu %s%s%s PURPOSE=%s",
1616 (unsigned long)TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1617 state, *path ? " " : "", path, purpose);
1618 smartlist_add(status, s);
1619 tor_free(path);
1621 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1622 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1623 smartlist_free(status);
1624 } else if (!strcmp(question, "stream-status")) {
1625 smartlist_t *conns = get_connection_array();
1626 smartlist_t *status = smartlist_create();
1627 char buf[256];
1628 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1629 const char *state;
1630 edge_connection_t *conn;
1631 char *s;
1632 size_t slen;
1633 circuit_t *circ;
1634 origin_circuit_t *origin_circ = NULL;
1635 if (base_conn->type != CONN_TYPE_AP ||
1636 base_conn->marked_for_close ||
1637 base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
1638 base_conn->state == AP_CONN_STATE_NATD_WAIT)
1639 continue;
1640 conn = TO_EDGE_CONN(base_conn);
1641 switch (conn->_base.state)
1643 case AP_CONN_STATE_CONTROLLER_WAIT:
1644 case AP_CONN_STATE_CIRCUIT_WAIT:
1645 if (conn->socks_request &&
1646 SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
1647 state = "NEWRESOLVE";
1648 else
1649 state = "NEW";
1650 break;
1651 case AP_CONN_STATE_RENDDESC_WAIT:
1652 case AP_CONN_STATE_CONNECT_WAIT:
1653 state = "SENTCONNECT"; break;
1654 case AP_CONN_STATE_RESOLVE_WAIT:
1655 state = "SENTRESOLVE"; break;
1656 case AP_CONN_STATE_OPEN:
1657 state = "SUCCEEDED"; break;
1658 default:
1659 log_warn(LD_BUG, "Asked for stream in unknown state %d",
1660 conn->_base.state);
1661 continue;
1663 circ = circuit_get_by_edge_conn(conn);
1664 if (circ && CIRCUIT_IS_ORIGIN(circ))
1665 origin_circ = TO_ORIGIN_CIRCUIT(circ);
1666 write_stream_target_to_buf(conn, buf, sizeof(buf));
1667 slen = strlen(buf)+strlen(state)+32;
1668 s = tor_malloc(slen+1);
1669 tor_snprintf(s, slen, "%lu %s %lu %s",
1670 (unsigned long) conn->_base.global_identifier,state,
1671 origin_circ?
1672 (unsigned long)origin_circ->global_identifier : 0ul,
1673 buf);
1674 smartlist_add(status, s);
1675 } SMARTLIST_FOREACH_END(base_conn);
1676 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1677 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1678 smartlist_free(status);
1679 } else if (!strcmp(question, "orconn-status")) {
1680 smartlist_t *conns = get_connection_array();
1681 smartlist_t *status = smartlist_create();
1682 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1683 const char *state;
1684 char *s;
1685 char name[128];
1686 size_t slen;
1687 or_connection_t *conn;
1688 if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
1689 continue;
1690 conn = TO_OR_CONN(base_conn);
1691 if (conn->_base.state == OR_CONN_STATE_OPEN)
1692 state = "CONNECTED";
1693 else if (conn->nickname)
1694 state = "LAUNCHED";
1695 else
1696 state = "NEW";
1697 orconn_target_get_name(name, sizeof(name), conn);
1698 slen = strlen(name)+strlen(state)+2;
1699 s = tor_malloc(slen+1);
1700 tor_snprintf(s, slen, "%s %s", name, state);
1701 smartlist_add(status, s);
1702 } SMARTLIST_FOREACH_END(base_conn);
1703 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1704 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1705 smartlist_free(status);
1706 } else if (!strcmpstart(question, "address-mappings/")) {
1707 time_t min_e, max_e;
1708 smartlist_t *mappings;
1709 question += strlen("address-mappings/");
1710 if (!strcmp(question, "all")) {
1711 min_e = 0; max_e = TIME_MAX;
1712 } else if (!strcmp(question, "cache")) {
1713 min_e = 2; max_e = TIME_MAX;
1714 } else if (!strcmp(question, "config")) {
1715 min_e = 0; max_e = 0;
1716 } else if (!strcmp(question, "control")) {
1717 min_e = 1; max_e = 1;
1718 } else {
1719 return 0;
1721 mappings = smartlist_create();
1722 addressmap_get_mappings(mappings, min_e, max_e, 1);
1723 *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
1724 SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
1725 smartlist_free(mappings);
1726 } else if (!strcmpstart(question, "status/")) {
1727 /* Note that status/ is not a catch-all for events; there's only supposed
1728 * to be a status GETINFO if there's a corresponding STATUS event. */
1729 if (!strcmp(question, "status/circuit-established")) {
1730 *answer = tor_strdup(can_complete_circuit ? "1" : "0");
1731 } else if (!strcmp(question, "status/enough-dir-info")) {
1732 *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
1733 } else if (!strcmp(question, "status/good-server-descriptor") ||
1734 !strcmp(question, "status/accepted-server-descriptor")) {
1735 /* They're equivalent for now, until we can figure out how to make
1736 * good-server-descriptor be what we want. See comment in
1737 * control-spec.txt. */
1738 *answer = tor_strdup(directories_have_accepted_server_descriptor()
1739 ? "1" : "0");
1740 } else if (!strcmp(question, "status/reachability-succeeded/or")) {
1741 *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
1742 } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
1743 *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
1744 } else if (!strcmp(question, "status/reachability-succeeded")) {
1745 *answer = tor_malloc(16);
1746 tor_snprintf(*answer, 16, "OR=%d DIR=%d",
1747 check_whether_orport_reachable() ? 1 : 0,
1748 check_whether_dirport_reachable() ? 1 : 0);
1749 } else if (!strcmp(question, "status/bootstrap-phase")) {
1750 *answer = tor_strdup(last_sent_bootstrap_message);
1751 } else if (!strcmpstart(question, "status/version/")) {
1752 int is_server = server_mode(get_options());
1753 networkstatus_t *c = networkstatus_get_latest_consensus();
1754 version_status_t status;
1755 const char *recommended;
1756 if (c) {
1757 recommended = is_server ? c->server_versions : c->client_versions;
1758 status = tor_version_is_obsolete(VERSION, recommended);
1759 } else {
1760 recommended = "?";
1761 status = VS_UNKNOWN;
1764 if (!strcmp(question, "status/version/recommended")) {
1765 *answer = tor_strdup(recommended);
1766 return 0;
1768 if (!strcmp(question, "status/version/current")) {
1769 switch (status)
1771 case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
1772 case VS_OLD: *answer = tor_strdup("obsolete"); break;
1773 case VS_NEW: *answer = tor_strdup("new"); break;
1774 case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
1775 case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
1776 case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
1777 case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
1778 default: tor_fragile_assert();
1780 } else if (!strcmp(question, "status/version/num-versioning") ||
1781 !strcmp(question, "status/version/num-concurring")) {
1782 char s[33];
1783 tor_snprintf(s, sizeof(s), "%d", get_n_authorities(V3_AUTHORITY));
1784 *answer = tor_strdup(s);
1785 log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
1786 "information", question);
1788 } else if (!strcmp(question, "status/clients-seen")) {
1789 char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
1790 if (!bridge_stats) {
1791 *errmsg = "No bridge-client stats available";
1792 return -1;
1794 *answer = bridge_stats;
1795 } else {
1796 return 0;
1799 return 0;
1802 /** Callback function for GETINFO: on a given control connection, try to
1803 * answer the question <b>q</b> and store the newly-allocated answer in
1804 * *<b>a</b>. If an internal error occurs, return -1 and optionally set
1805 * *<b>error_out</b> to point to an error message to be delivered to the
1806 * controller. On success, _or if the key is not recognized_, return 0. Do not
1807 * set <b>a</b> if the key is not recognized.
1809 typedef int (*getinfo_helper_t)(control_connection_t *,
1810 const char *q, char **a,
1811 const char **error_out);
1813 /** A single item for the GETINFO question-to-answer-function table. */
1814 typedef struct getinfo_item_t {
1815 const char *varname; /**< The value (or prefix) of the question. */
1816 getinfo_helper_t fn; /**< The function that knows the answer: NULL if
1817 * this entry is documentation-only. */
1818 const char *desc; /**< Description of the variable. */
1819 int is_prefix; /** Must varname match exactly, or must it be a prefix? */
1820 } getinfo_item_t;
1822 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
1823 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
1824 #define DOC(name, desc) { name, NULL, desc, 0 }
1826 /** Table mapping questions accepted by GETINFO to the functions that know how
1827 * to answer them. */
1828 static const getinfo_item_t getinfo_items[] = {
1829 ITEM("version", misc, "The current version of Tor."),
1830 ITEM("config-file", misc, "Current location of the \"torrc\" file."),
1831 ITEM("config-text", misc,
1832 "Return the string that would be written by a saveconf command."),
1833 ITEM("accounting/bytes", accounting,
1834 "Number of bytes read/written so far in the accounting interval."),
1835 ITEM("accounting/bytes-left", accounting,
1836 "Number of bytes left to write/read so far in the accounting interval."),
1837 ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
1838 ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
1839 ITEM("accounting/interval-start", accounting,
1840 "Time when the accounting period starts."),
1841 ITEM("accounting/interval-end", accounting,
1842 "Time when the accounting period ends."),
1843 ITEM("accounting/interval-wake", accounting,
1844 "Time to wake up in this accounting period."),
1845 ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
1846 ITEM("entry-guards", entry_guards,
1847 "Which nodes are we using as entry guards?"),
1848 ITEM("fingerprint", misc, NULL),
1849 PREFIX("config/", config, "Current configuration values."),
1850 DOC("config/names",
1851 "List of configuration options, types, and documentation."),
1852 ITEM("info/names", misc,
1853 "List of GETINFO options, types, and documentation."),
1854 ITEM("events/names", misc,
1855 "Events that the controller can ask for with SETEVENTS."),
1856 ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
1857 PREFIX("desc/id/", dir, "Router descriptors by ID."),
1858 PREFIX("desc/name/", dir, "Router descriptors by nickname."),
1859 ITEM("desc/all-recent", dir,
1860 "All non-expired, non-superseded router descriptors."),
1861 ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
1862 PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
1863 ITEM("ns/all", networkstatus,
1864 "Brief summary of router status (v2 directory format)"),
1865 PREFIX("ns/id/", networkstatus,
1866 "Brief summary of router status by ID (v2 directory format)."),
1867 PREFIX("ns/name/", networkstatus,
1868 "Brief summary of router status by nickname (v2 directory format)."),
1869 PREFIX("ns/purpose/", networkstatus,
1870 "Brief summary of router status by purpose (v2 directory format)."),
1872 ITEM("network-status", dir,
1873 "Brief summary of router status (v1 directory format)"),
1874 ITEM("circuit-status", events, "List of current circuits originating here."),
1875 ITEM("stream-status", events,"List of current streams."),
1876 ITEM("orconn-status", events, "A list of current OR connections."),
1877 PREFIX("address-mappings/", events, NULL),
1878 DOC("address-mappings/all", "Current address mappings."),
1879 DOC("address-mappings/cache", "Current cached DNS replies."),
1880 DOC("address-mappings/config",
1881 "Current address mappings from configuration."),
1882 DOC("address-mappings/control", "Current address mappings from controller."),
1883 PREFIX("status/", events, NULL),
1884 DOC("status/circuit-established",
1885 "Whether we think client functionality is working."),
1886 DOC("status/enough-dir-info",
1887 "Whether we have enough up-to-date directory information to build "
1888 "circuits."),
1889 DOC("status/bootstrap-phase",
1890 "The last bootstrap phase status event that Tor sent."),
1891 DOC("status/clients-seen",
1892 "Breakdown of client countries seen by a bridge."),
1893 DOC("status/version/recommended", "List of currently recommended versions."),
1894 DOC("status/version/current", "Status of the current version."),
1895 DOC("status/version/num-versioning", "Number of versioning authorities."),
1896 DOC("status/version/num-concurring",
1897 "Number of versioning authorities agreeing on the status of the "
1898 "current version"),
1899 ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
1900 ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
1901 PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
1902 PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
1903 PREFIX("dir/status/", dir,
1904 "v2 networkstatus docs as retrieved from a DirPort."),
1905 ITEM("dir/status-vote/current/consensus", dir,
1906 "v3 Networkstatus consensus as retrieved from a DirPort."),
1907 PREFIX("exit-policy/default", policies,
1908 "The default value appended to the configured exit policy."),
1909 PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
1910 { NULL, NULL, NULL, 0 }
1913 /** Allocate and return a list of recognized GETINFO options. */
1914 static char *
1915 list_getinfo_options(void)
1917 int i;
1918 char *buf=NULL;
1919 smartlist_t *lines = smartlist_create();
1920 char *ans;
1921 for (i = 0; getinfo_items[i].varname; ++i) {
1922 if (!getinfo_items[i].desc)
1923 continue;
1925 tor_asprintf(&buf, "%s%s -- %s\n",
1926 getinfo_items[i].varname,
1927 getinfo_items[i].is_prefix ? "*" : "",
1928 getinfo_items[i].desc);
1929 smartlist_add(lines, buf);
1931 smartlist_sort_strings(lines);
1933 ans = smartlist_join_strings(lines, "", 0, NULL);
1934 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1935 smartlist_free(lines);
1937 return ans;
1940 /** Lookup the 'getinfo' entry <b>question</b>, and return
1941 * the answer in <b>*answer</b> (or NULL if key not recognized).
1942 * Return 0 if success or unrecognized, or -1 if recognized but
1943 * internal error. */
1944 static int
1945 handle_getinfo_helper(control_connection_t *control_conn,
1946 const char *question, char **answer,
1947 const char **err_out)
1949 int i;
1950 *answer = NULL; /* unrecognized key by default */
1952 for (i = 0; getinfo_items[i].varname; ++i) {
1953 int match;
1954 if (getinfo_items[i].is_prefix)
1955 match = !strcmpstart(question, getinfo_items[i].varname);
1956 else
1957 match = !strcmp(question, getinfo_items[i].varname);
1958 if (match) {
1959 tor_assert(getinfo_items[i].fn);
1960 return getinfo_items[i].fn(control_conn, question, answer, err_out);
1964 return 0; /* unrecognized */
1967 /** Called when we receive a GETINFO command. Try to fetch all requested
1968 * information, and reply with information or error message. */
1969 static int
1970 handle_control_getinfo(control_connection_t *conn, uint32_t len,
1971 const char *body)
1973 smartlist_t *questions = smartlist_create();
1974 smartlist_t *answers = smartlist_create();
1975 smartlist_t *unrecognized = smartlist_create();
1976 char *msg = NULL, *ans = NULL;
1977 int i;
1978 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
1980 smartlist_split_string(questions, body, " ",
1981 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1982 SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
1983 const char *errmsg = NULL;
1984 if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
1985 if (!errmsg)
1986 errmsg = "Internal error";
1987 connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
1988 goto done;
1990 if (!ans) {
1991 smartlist_add(unrecognized, (char*)q);
1992 } else {
1993 smartlist_add(answers, tor_strdup(q));
1994 smartlist_add(answers, ans);
1996 } SMARTLIST_FOREACH_END(q);
1997 if (smartlist_len(unrecognized)) {
1998 for (i=0; i < smartlist_len(unrecognized)-1; ++i)
1999 connection_printf_to_buf(conn,
2000 "552-Unrecognized key \"%s\"\r\n",
2001 (char*)smartlist_get(unrecognized, i));
2002 connection_printf_to_buf(conn,
2003 "552 Unrecognized key \"%s\"\r\n",
2004 (char*)smartlist_get(unrecognized, i));
2005 goto done;
2008 for (i = 0; i < smartlist_len(answers); i += 2) {
2009 char *k = smartlist_get(answers, i);
2010 char *v = smartlist_get(answers, i+1);
2011 if (!strchr(v, '\n') && !strchr(v, '\r')) {
2012 connection_printf_to_buf(conn, "250-%s=", k);
2013 connection_write_str_to_buf(v, conn);
2014 connection_write_str_to_buf("\r\n", conn);
2015 } else {
2016 char *esc = NULL;
2017 size_t esc_len;
2018 esc_len = write_escaped_data(v, strlen(v), &esc);
2019 connection_printf_to_buf(conn, "250+%s=\r\n", k);
2020 connection_write_to_buf(esc, esc_len, TO_CONN(conn));
2021 tor_free(esc);
2024 connection_write_str_to_buf("250 OK\r\n", conn);
2026 done:
2027 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
2028 smartlist_free(answers);
2029 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
2030 smartlist_free(questions);
2031 smartlist_free(unrecognized);
2032 tor_free(msg);
2034 return 0;
2037 /** Given a string, convert it to a circuit purpose. */
2038 static uint8_t
2039 circuit_purpose_from_string(const char *string)
2041 if (!strcasecmpstart(string, "purpose="))
2042 string += strlen("purpose=");
2044 if (!strcasecmp(string, "general"))
2045 return CIRCUIT_PURPOSE_C_GENERAL;
2046 else if (!strcasecmp(string, "controller"))
2047 return CIRCUIT_PURPOSE_CONTROLLER;
2048 else
2049 return CIRCUIT_PURPOSE_UNKNOWN;
2052 /** Return a newly allocated smartlist containing the arguments to the command
2053 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
2054 * or if <b>max_args</b> is nonnegative and there are more than
2055 * <b>max_args</b> arguments, send a 512 error to the controller, using
2056 * <b>command</b> as the command name in the error message. */
2057 static smartlist_t *
2058 getargs_helper(const char *command, control_connection_t *conn,
2059 const char *body, int min_args, int max_args)
2061 smartlist_t *args = smartlist_create();
2062 smartlist_split_string(args, body, " ",
2063 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2064 if (smartlist_len(args) < min_args) {
2065 connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
2066 goto err;
2067 } else if (max_args >= 0 && smartlist_len(args) > max_args) {
2068 connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
2069 goto err;
2071 return args;
2072 err:
2073 SMARTLIST_FOREACH(args, char *, s, tor_free(s));
2074 smartlist_free(args);
2075 return NULL;
2078 /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
2079 * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
2080 * such element exists. */
2081 static const char *
2082 find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
2084 int i;
2085 for (i = start_at; i < smartlist_len(sl); ++i) {
2086 const char *elt = smartlist_get(sl, i);
2087 if (!strcasecmpstart(elt, prefix))
2088 return elt;
2090 return NULL;
2093 /** Helper. Return true iff s is an argument that we should treat as a
2094 * key-value pair. */
2095 static int
2096 is_keyval_pair(const char *s)
2098 /* An argument is a key-value pair if it has an =, and it isn't of the form
2099 * $fingeprint=name */
2100 return strchr(s, '=') && s[0] != '$';
2103 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
2104 * circuit, and report success or failure. */
2105 static int
2106 handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
2107 const char *body)
2109 smartlist_t *router_nicknames=NULL, *routers=NULL;
2110 origin_circuit_t *circ = NULL;
2111 int zero_circ;
2112 uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
2113 smartlist_t *args;
2114 (void) len;
2116 router_nicknames = smartlist_create();
2118 args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
2119 if (!args)
2120 goto done;
2122 zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
2124 if (zero_circ) {
2125 const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
2127 if (purp) {
2128 intended_purpose = circuit_purpose_from_string(purp);
2129 if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
2130 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
2131 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2132 smartlist_free(args);
2133 goto done;
2137 if ((smartlist_len(args) == 1) ||
2138 (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
2139 // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
2140 circ = circuit_launch_by_router(intended_purpose, NULL,
2141 CIRCLAUNCH_NEED_CAPACITY);
2142 if (!circ) {
2143 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
2144 } else {
2145 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
2146 (unsigned long)circ->global_identifier);
2148 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2149 smartlist_free(args);
2150 goto done;
2152 // "EXTENDCIRCUIT 0 router1,router2" ||
2153 // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
2156 if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
2157 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2158 (char*)smartlist_get(args, 0));
2159 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2160 smartlist_free(args);
2161 goto done;
2164 smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
2166 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2167 smartlist_free(args);
2169 routers = smartlist_create();
2170 SMARTLIST_FOREACH(router_nicknames, const char *, n,
2172 routerinfo_t *r = router_get_by_nickname(n, 1);
2173 if (!r) {
2174 connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
2175 goto done;
2177 smartlist_add(routers, r);
2179 if (!smartlist_len(routers)) {
2180 connection_write_str_to_buf("512 No router names provided\r\n", conn);
2181 goto done;
2184 if (zero_circ) {
2185 /* start a new circuit */
2186 circ = origin_circuit_init(intended_purpose, 0);
2189 /* now circ refers to something that is ready to be extended */
2190 SMARTLIST_FOREACH(routers, routerinfo_t *, r,
2192 extend_info_t *info = extend_info_from_router(r);
2193 circuit_append_new_exit(circ, info);
2194 extend_info_free(info);
2197 /* now that we've populated the cpath, start extending */
2198 if (zero_circ) {
2199 int err_reason = 0;
2200 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
2201 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2202 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
2203 goto done;
2205 } else {
2206 if (circ->_base.state == CIRCUIT_STATE_OPEN) {
2207 int err_reason = 0;
2208 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
2209 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
2210 log_info(LD_CONTROL,
2211 "send_next_onion_skin failed; circuit marked for closing.");
2212 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2213 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
2214 goto done;
2219 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
2220 (unsigned long)circ->global_identifier);
2221 if (zero_circ) /* send a 'launched' event, for completeness */
2222 control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
2223 done:
2224 SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
2225 smartlist_free(router_nicknames);
2226 smartlist_free(routers);
2227 return 0;
2230 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
2231 * circuit and it's a valid purpose, change it. */
2232 static int
2233 handle_control_setcircuitpurpose(control_connection_t *conn,
2234 uint32_t len, const char *body)
2236 origin_circuit_t *circ = NULL;
2237 uint8_t new_purpose;
2238 smartlist_t *args;
2239 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
2241 args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
2242 if (!args)
2243 goto done;
2245 if (!(circ = get_circ(smartlist_get(args,0)))) {
2246 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2247 (char*)smartlist_get(args, 0));
2248 goto done;
2252 const char *purp = find_element_starting_with(args,1,"PURPOSE=");
2253 new_purpose = circuit_purpose_from_string(purp);
2254 if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
2255 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
2256 goto done;
2260 circ->_base.purpose = new_purpose;
2261 connection_write_str_to_buf("250 OK\r\n", conn);
2263 done:
2264 if (args) {
2265 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2266 smartlist_free(args);
2268 return 0;
2271 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
2272 * stream, and report success or failure. */
2273 static int
2274 handle_control_attachstream(control_connection_t *conn, uint32_t len,
2275 const char *body)
2277 edge_connection_t *ap_conn = NULL;
2278 origin_circuit_t *circ = NULL;
2279 int zero_circ;
2280 smartlist_t *args;
2281 crypt_path_t *cpath=NULL;
2282 int hop=0, hop_line_ok=1;
2283 (void) len;
2285 args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
2286 if (!args)
2287 return 0;
2289 zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
2291 if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
2292 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2293 (char*)smartlist_get(args, 0));
2294 } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
2295 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2296 (char*)smartlist_get(args, 1));
2297 } else if (circ) {
2298 const char *hopstring = find_element_starting_with(args,2,"HOP=");
2299 if (hopstring) {
2300 hopstring += strlen("HOP=");
2301 hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
2302 &hop_line_ok, NULL);
2303 if (!hop_line_ok) { /* broken hop line */
2304 connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
2308 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2309 smartlist_free(args);
2310 if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
2311 return 0;
2313 if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT &&
2314 ap_conn->_base.state != AP_CONN_STATE_CONNECT_WAIT &&
2315 ap_conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
2316 connection_write_str_to_buf(
2317 "555 Connection is not managed by controller.\r\n",
2318 conn);
2319 return 0;
2322 /* Do we need to detach it first? */
2323 if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT) {
2324 circuit_t *tmpcirc = circuit_get_by_edge_conn(ap_conn);
2325 connection_edge_end(ap_conn, END_STREAM_REASON_TIMEOUT);
2326 /* Un-mark it as ending, since we're going to reuse it. */
2327 ap_conn->edge_has_sent_end = 0;
2328 ap_conn->end_reason = 0;
2329 if (tmpcirc)
2330 circuit_detach_stream(tmpcirc,ap_conn);
2331 ap_conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
2334 if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
2335 connection_write_str_to_buf(
2336 "551 Can't attach stream to non-open origin circuit\r\n",
2337 conn);
2338 return 0;
2340 /* Is this a single hop circuit? */
2341 if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
2342 routerinfo_t *r = NULL;
2343 char* exit_digest;
2344 if (circ->build_state &&
2345 circ->build_state->chosen_exit &&
2346 !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
2347 exit_digest = circ->build_state->chosen_exit->identity_digest;
2348 r = router_get_by_digest(exit_digest);
2350 /* Do both the client and relay allow one-hop exit circuits? */
2351 if (!r || !r->allow_single_hop_exits ||
2352 !get_options()->AllowSingleHopCircuits) {
2353 connection_write_str_to_buf(
2354 "551 Can't attach stream to this one-hop circuit.\r\n", conn);
2355 return 0;
2357 ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
2360 if (circ && hop>0) {
2361 /* find this hop in the circuit, and set cpath */
2362 cpath = circuit_get_cpath_hop(circ, hop);
2363 if (!cpath) {
2364 connection_printf_to_buf(conn,
2365 "551 Circuit doesn't have %d hops.\r\n", hop);
2366 return 0;
2369 if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
2370 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
2371 return 0;
2373 send_control_done(conn);
2374 return 0;
2377 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
2378 * descriptor, and report success or failure. */
2379 static int
2380 handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
2381 const char *body)
2383 char *desc;
2384 const char *msg=NULL;
2385 uint8_t purpose = ROUTER_PURPOSE_GENERAL;
2386 int cache = 0; /* eventually, we may switch this to 1 */
2388 char *cp = memchr(body, '\n', len);
2389 smartlist_t *args = smartlist_create();
2390 tor_assert(cp);
2391 *cp++ = '\0';
2393 smartlist_split_string(args, body, " ",
2394 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2395 SMARTLIST_FOREACH(args, char *, option,
2397 if (!strcasecmpstart(option, "purpose=")) {
2398 option += strlen("purpose=");
2399 purpose = router_purpose_from_string(option);
2400 if (purpose == ROUTER_PURPOSE_UNKNOWN) {
2401 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
2402 option);
2403 goto done;
2405 } else if (!strcasecmpstart(option, "cache=")) {
2406 option += strlen("cache=");
2407 if (!strcasecmp(option, "no"))
2408 cache = 0;
2409 else if (!strcasecmp(option, "yes"))
2410 cache = 1;
2411 else {
2412 connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
2413 option);
2414 goto done;
2416 } else { /* unrecognized argument? */
2417 connection_printf_to_buf(conn,
2418 "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
2419 goto done;
2423 read_escaped_data(cp, len-(cp-body), &desc);
2425 switch (router_load_single_router(desc, purpose, cache, &msg)) {
2426 case -1:
2427 if (!msg) msg = "Could not parse descriptor";
2428 connection_printf_to_buf(conn, "554 %s\r\n", msg);
2429 break;
2430 case 0:
2431 if (!msg) msg = "Descriptor not added";
2432 connection_printf_to_buf(conn, "251 %s\r\n",msg);
2433 break;
2434 case 1:
2435 send_control_done(conn);
2436 break;
2439 tor_free(desc);
2440 done:
2441 SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
2442 smartlist_free(args);
2443 return 0;
2446 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
2447 * address of the named AP stream, and report success or failure. */
2448 static int
2449 handle_control_redirectstream(control_connection_t *conn, uint32_t len,
2450 const char *body)
2452 edge_connection_t *ap_conn = NULL;
2453 char *new_addr = NULL;
2454 uint16_t new_port = 0;
2455 smartlist_t *args;
2456 (void) len;
2458 args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
2459 if (!args)
2460 return 0;
2462 if (!(ap_conn = get_stream(smartlist_get(args, 0)))
2463 || !ap_conn->socks_request) {
2464 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2465 (char*)smartlist_get(args, 0));
2466 } else {
2467 int ok = 1;
2468 if (smartlist_len(args) > 2) { /* they included a port too */
2469 new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
2470 10, 1, 65535, &ok, NULL);
2472 if (!ok) {
2473 connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
2474 (char*)smartlist_get(args, 2));
2475 } else {
2476 new_addr = tor_strdup(smartlist_get(args, 1));
2480 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2481 smartlist_free(args);
2482 if (!new_addr)
2483 return 0;
2485 strlcpy(ap_conn->socks_request->address, new_addr,
2486 sizeof(ap_conn->socks_request->address));
2487 if (new_port)
2488 ap_conn->socks_request->port = new_port;
2489 tor_free(new_addr);
2490 send_control_done(conn);
2491 return 0;
2494 /** Called when we get a CLOSESTREAM command; try to close the named stream
2495 * and report success or failure. */
2496 static int
2497 handle_control_closestream(control_connection_t *conn, uint32_t len,
2498 const char *body)
2500 edge_connection_t *ap_conn=NULL;
2501 uint8_t reason=0;
2502 smartlist_t *args;
2503 int ok;
2504 (void) len;
2506 args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
2507 if (!args)
2508 return 0;
2510 else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
2511 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2512 (char*)smartlist_get(args, 0));
2513 else {
2514 reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
2515 &ok, NULL);
2516 if (!ok) {
2517 connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
2518 (char*)smartlist_get(args, 1));
2519 ap_conn = NULL;
2522 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2523 smartlist_free(args);
2524 if (!ap_conn)
2525 return 0;
2527 connection_mark_unattached_ap(ap_conn, reason);
2528 send_control_done(conn);
2529 return 0;
2532 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
2533 * and report success or failure. */
2534 static int
2535 handle_control_closecircuit(control_connection_t *conn, uint32_t len,
2536 const char *body)
2538 origin_circuit_t *circ = NULL;
2539 int safe = 0;
2540 smartlist_t *args;
2541 (void) len;
2543 args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
2544 if (!args)
2545 return 0;
2547 if (!(circ=get_circ(smartlist_get(args, 0))))
2548 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2549 (char*)smartlist_get(args, 0));
2550 else {
2551 int i;
2552 for (i=1; i < smartlist_len(args); ++i) {
2553 if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
2554 safe = 1;
2555 else
2556 log_info(LD_CONTROL, "Skipping unknown option %s",
2557 (char*)smartlist_get(args,i));
2560 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2561 smartlist_free(args);
2562 if (!circ)
2563 return 0;
2565 if (!safe || !circ->p_streams) {
2566 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
2569 send_control_done(conn);
2570 return 0;
2573 /** Called when we get a RESOLVE command: start trying to resolve
2574 * the listed addresses. */
2575 static int
2576 handle_control_resolve(control_connection_t *conn, uint32_t len,
2577 const char *body)
2579 smartlist_t *args, *failed;
2580 int is_reverse = 0;
2581 (void) len; /* body is nul-terminated; it's safe to ignore the length */
2583 if (!(conn->event_mask & ((uint32_t)1L<<EVENT_ADDRMAP))) {
2584 log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
2585 "isn't listening for ADDRMAP events. It probably won't see "
2586 "the answer.");
2588 args = smartlist_create();
2589 smartlist_split_string(args, body, " ",
2590 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2592 const char *modearg = find_element_starting_with(args, 0, "mode=");
2593 if (modearg && !strcasecmp(modearg, "mode=reverse"))
2594 is_reverse = 1;
2596 failed = smartlist_create();
2597 SMARTLIST_FOREACH(args, const char *, arg, {
2598 if (!is_keyval_pair(arg)) {
2599 if (dnsserv_launch_request(arg, is_reverse)<0)
2600 smartlist_add(failed, (char*)arg);
2604 send_control_done(conn);
2605 SMARTLIST_FOREACH(failed, const char *, arg, {
2606 control_event_address_mapped(arg, arg, time(NULL),
2607 "Unable to launch resolve request");
2610 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2611 smartlist_free(args);
2612 smartlist_free(failed);
2613 return 0;
2616 /** Called when we get a PROTOCOLINFO command: send back a reply. */
2617 static int
2618 handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
2619 const char *body)
2621 const char *bad_arg = NULL;
2622 smartlist_t *args;
2623 (void)len;
2625 conn->have_sent_protocolinfo = 1;
2626 args = smartlist_create();
2627 smartlist_split_string(args, body, " ",
2628 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2629 SMARTLIST_FOREACH(args, const char *, arg, {
2630 int ok;
2631 tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
2632 if (!ok) {
2633 bad_arg = arg;
2634 break;
2637 if (bad_arg) {
2638 connection_printf_to_buf(conn, "513 No such version %s\r\n",
2639 escaped(bad_arg));
2640 /* Don't tolerate bad arguments when not authenticated. */
2641 if (!STATE_IS_OPEN(TO_CONN(conn)->state))
2642 connection_mark_for_close(TO_CONN(conn));
2643 goto done;
2644 } else {
2645 or_options_t *options = get_options();
2646 int cookies = options->CookieAuthentication;
2647 char *cfile = get_cookie_file();
2648 char *esc_cfile = esc_for_log(cfile);
2649 char *methods;
2651 int passwd = (options->HashedControlPassword != NULL ||
2652 options->HashedControlSessionPassword != NULL);
2653 smartlist_t *mlist = smartlist_create();
2654 if (cookies)
2655 smartlist_add(mlist, (char*)"COOKIE");
2656 if (passwd)
2657 smartlist_add(mlist, (char*)"HASHEDPASSWORD");
2658 if (!cookies && !passwd)
2659 smartlist_add(mlist, (char*)"NULL");
2660 methods = smartlist_join_strings(mlist, ",", 0, NULL);
2661 smartlist_free(mlist);
2664 connection_printf_to_buf(conn,
2665 "250-PROTOCOLINFO 1\r\n"
2666 "250-AUTH METHODS=%s%s%s\r\n"
2667 "250-VERSION Tor=%s\r\n"
2668 "250 OK\r\n",
2669 methods,
2670 cookies?" COOKIEFILE=":"",
2671 cookies?esc_cfile:"",
2672 escaped(VERSION));
2673 tor_free(methods);
2674 tor_free(cfile);
2675 tor_free(esc_cfile);
2677 done:
2678 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2679 smartlist_free(args);
2680 return 0;
2683 /** Called when we get a USEFEATURE command: parse the feature list, and
2684 * set up the control_connection's options properly. */
2685 static int
2686 handle_control_usefeature(control_connection_t *conn,
2687 uint32_t len,
2688 const char *body)
2690 smartlist_t *args;
2691 int bad = 0;
2692 (void) len; /* body is nul-terminated; it's safe to ignore the length */
2693 args = smartlist_create();
2694 smartlist_split_string(args, body, " ",
2695 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2696 SMARTLIST_FOREACH(args, const char *, arg, {
2697 if (!strcasecmp(arg, "VERBOSE_NAMES"))
2699 else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
2701 else {
2702 connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
2703 arg);
2704 bad = 1;
2705 break;
2709 if (!bad) {
2710 send_control_done(conn);
2713 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2714 smartlist_free(args);
2715 return 0;
2718 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
2720 connection_control_finished_flushing(control_connection_t *conn)
2722 tor_assert(conn);
2724 connection_stop_writing(TO_CONN(conn));
2725 return 0;
2728 /** Called when <b>conn</b> has gotten its socket closed. */
2730 connection_control_reached_eof(control_connection_t *conn)
2732 tor_assert(conn);
2734 log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
2735 connection_mark_for_close(TO_CONN(conn));
2736 return 0;
2739 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
2740 * stage of the protocol. */
2741 static int
2742 is_valid_initial_command(control_connection_t *conn, const char *cmd)
2744 if (conn->_base.state == CONTROL_CONN_STATE_OPEN)
2745 return 1;
2746 if (!strcasecmp(cmd, "PROTOCOLINFO"))
2747 return !conn->have_sent_protocolinfo;
2748 if (!strcasecmp(cmd, "AUTHENTICATE") ||
2749 !strcasecmp(cmd, "QUIT"))
2750 return 1;
2751 return 0;
2754 /** Do not accept any control command of more than 1MB in length. Anything
2755 * that needs to be anywhere near this long probably means that one of our
2756 * interfaces is broken. */
2757 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
2759 /** Called when data has arrived on a v1 control connection: Try to fetch
2760 * commands from conn->inbuf, and execute them.
2763 connection_control_process_inbuf(control_connection_t *conn)
2765 size_t data_len;
2766 uint32_t cmd_data_len;
2767 int cmd_len;
2768 char *args;
2770 tor_assert(conn);
2771 tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN ||
2772 conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH);
2774 if (!conn->incoming_cmd) {
2775 conn->incoming_cmd = tor_malloc(1024);
2776 conn->incoming_cmd_len = 1024;
2777 conn->incoming_cmd_cur_len = 0;
2780 if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
2781 peek_buf_has_control0_command(conn->_base.inbuf)) {
2782 /* Detect v0 commands and send a "no more v0" message. */
2783 size_t body_len;
2784 char buf[128];
2785 set_uint16(buf+2, htons(0x0000)); /* type == error */
2786 set_uint16(buf+4, htons(0x0001)); /* code == internal error */
2787 strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
2788 "and later; upgrade your controller.",
2789 sizeof(buf)-6);
2790 body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
2791 set_uint16(buf+0, htons(body_len));
2792 connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
2793 connection_mark_for_close(TO_CONN(conn));
2794 conn->_base.hold_open_until_flushed = 1;
2795 return 0;
2798 again:
2799 while (1) {
2800 size_t last_idx;
2801 int r;
2802 /* First, fetch a line. */
2803 do {
2804 data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
2805 r = fetch_from_buf_line(conn->_base.inbuf,
2806 conn->incoming_cmd+conn->incoming_cmd_cur_len,
2807 &data_len);
2808 if (r == 0)
2809 /* Line not all here yet. Wait. */
2810 return 0;
2811 else if (r == -1) {
2812 if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
2813 connection_write_str_to_buf("500 Line too long.\r\n", conn);
2814 connection_stop_reading(TO_CONN(conn));
2815 connection_mark_for_close(TO_CONN(conn));
2816 conn->_base.hold_open_until_flushed = 1;
2818 while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
2819 conn->incoming_cmd_len *= 2;
2820 conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
2821 conn->incoming_cmd_len);
2823 } while (r != 1);
2825 tor_assert(data_len);
2827 last_idx = conn->incoming_cmd_cur_len;
2828 conn->incoming_cmd_cur_len += (int)data_len;
2830 /* We have appended a line to incoming_cmd. Is the command done? */
2831 if (last_idx == 0 && *conn->incoming_cmd != '+')
2832 /* One line command, didn't start with '+'. */
2833 break;
2834 /* XXXX this code duplication is kind of dumb. */
2835 if (last_idx+3 == conn->incoming_cmd_cur_len &&
2836 !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
2837 /* Just appended ".\r\n"; we're done. Remove it. */
2838 conn->incoming_cmd[last_idx] = '\0';
2839 conn->incoming_cmd_cur_len -= 3;
2840 break;
2841 } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
2842 !memcmp(conn->incoming_cmd + last_idx, ".\n", 2)) {
2843 /* Just appended ".\n"; we're done. Remove it. */
2844 conn->incoming_cmd[last_idx] = '\0';
2845 conn->incoming_cmd_cur_len -= 2;
2846 break;
2848 /* Otherwise, read another line. */
2850 data_len = conn->incoming_cmd_cur_len;
2851 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
2852 * recognize it.
2854 cmd_len = 0;
2855 while ((size_t)cmd_len < data_len
2856 && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
2857 ++cmd_len;
2859 conn->incoming_cmd[cmd_len]='\0';
2860 args = conn->incoming_cmd+cmd_len+1;
2861 tor_assert(data_len>(size_t)cmd_len);
2862 data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
2863 while (*args == ' ' || *args == '\t') {
2864 ++args;
2865 --data_len;
2868 /* If the connection is already closing, ignore further commands */
2869 if (TO_CONN(conn)->marked_for_close) {
2870 return 0;
2873 /* Otherwise, Quit is always valid. */
2874 if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
2875 connection_write_str_to_buf("250 closing connection\r\n", conn);
2876 connection_mark_for_close(TO_CONN(conn));
2877 conn->_base.hold_open_until_flushed = 1;
2878 return 0;
2881 if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
2882 !is_valid_initial_command(conn, conn->incoming_cmd)) {
2883 connection_write_str_to_buf("514 Authentication required.\r\n", conn);
2884 connection_mark_for_close(TO_CONN(conn));
2885 return 0;
2888 if (data_len >= UINT32_MAX) {
2889 connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
2890 connection_mark_for_close(TO_CONN(conn));
2891 return 0;
2894 cmd_data_len = (uint32_t)data_len;
2895 if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
2896 if (handle_control_setconf(conn, cmd_data_len, args))
2897 return -1;
2898 } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
2899 if (handle_control_resetconf(conn, cmd_data_len, args))
2900 return -1;
2901 } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
2902 if (handle_control_getconf(conn, cmd_data_len, args))
2903 return -1;
2904 } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
2905 if (handle_control_loadconf(conn, cmd_data_len, args))
2906 return -1;
2907 } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
2908 if (handle_control_setevents(conn, cmd_data_len, args))
2909 return -1;
2910 } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
2911 if (handle_control_authenticate(conn, cmd_data_len, args))
2912 return -1;
2913 } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
2914 if (handle_control_saveconf(conn, cmd_data_len, args))
2915 return -1;
2916 } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
2917 if (handle_control_signal(conn, cmd_data_len, args))
2918 return -1;
2919 } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
2920 if (handle_control_mapaddress(conn, cmd_data_len, args))
2921 return -1;
2922 } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
2923 if (handle_control_getinfo(conn, cmd_data_len, args))
2924 return -1;
2925 } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
2926 if (handle_control_extendcircuit(conn, cmd_data_len, args))
2927 return -1;
2928 } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
2929 if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
2930 return -1;
2931 } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
2932 connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
2933 } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
2934 if (handle_control_attachstream(conn, cmd_data_len, args))
2935 return -1;
2936 } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
2937 if (handle_control_postdescriptor(conn, cmd_data_len, args))
2938 return -1;
2939 } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
2940 if (handle_control_redirectstream(conn, cmd_data_len, args))
2941 return -1;
2942 } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
2943 if (handle_control_closestream(conn, cmd_data_len, args))
2944 return -1;
2945 } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
2946 if (handle_control_closecircuit(conn, cmd_data_len, args))
2947 return -1;
2948 } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
2949 if (handle_control_usefeature(conn, cmd_data_len, args))
2950 return -1;
2951 } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
2952 if (handle_control_resolve(conn, cmd_data_len, args))
2953 return -1;
2954 } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
2955 if (handle_control_protocolinfo(conn, cmd_data_len, args))
2956 return -1;
2957 } else {
2958 connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
2959 conn->incoming_cmd);
2962 conn->incoming_cmd_cur_len = 0;
2963 goto again;
2966 /** Something has happened to circuit <b>circ</b>: tell any interested
2967 * control connections. */
2969 control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
2970 int reason_code)
2972 const char *status;
2973 char extended_buf[96];
2974 int providing_reason=0;
2975 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
2976 return 0;
2977 tor_assert(circ);
2979 switch (tp)
2981 case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
2982 case CIRC_EVENT_BUILT: status = "BUILT"; break;
2983 case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
2984 case CIRC_EVENT_FAILED: status = "FAILED"; break;
2985 case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
2986 default:
2987 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
2988 return 0;
2991 tor_snprintf(extended_buf, sizeof(extended_buf), "PURPOSE=%s",
2992 circuit_purpose_to_controller_string(circ->_base.purpose));
2994 if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
2995 const char *reason_str = circuit_end_reason_to_control_string(reason_code);
2996 char *reason = NULL;
2997 size_t n=strlen(extended_buf);
2998 providing_reason=1;
2999 if (!reason_str) {
3000 reason = tor_malloc(16);
3001 tor_snprintf(reason, 16, "UNKNOWN_%d", reason_code);
3002 reason_str = reason;
3004 if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
3005 tor_snprintf(extended_buf+n, sizeof(extended_buf)-n,
3006 " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
3007 } else {
3008 tor_snprintf(extended_buf+n, sizeof(extended_buf)-n,
3009 " REASON=%s", reason_str);
3011 tor_free(reason);
3015 char *vpath = circuit_list_path_for_controller(circ);
3016 const char *sp = strlen(vpath) ? " " : "";
3017 send_control_event(EVENT_CIRCUIT_STATUS, ALL_FORMATS,
3018 "650 CIRC %lu %s%s%s %s\r\n",
3019 (unsigned long)circ->global_identifier,
3020 status, sp, vpath, extended_buf);
3021 tor_free(vpath);
3024 return 0;
3027 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
3028 * <b>buf</b>, determine the address:port combination requested on
3029 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
3030 * failure. */
3031 static int
3032 write_stream_target_to_buf(edge_connection_t *conn, char *buf, size_t len)
3034 char buf2[256];
3035 if (conn->chosen_exit_name)
3036 if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
3037 return -1;
3038 if (!conn->socks_request)
3039 return -1;
3040 if (tor_snprintf(buf, len, "%s%s%s:%d",
3041 conn->socks_request->address,
3042 conn->chosen_exit_name ? buf2 : "",
3043 !conn->chosen_exit_name &&
3044 connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
3045 conn->socks_request->port)<0)
3046 return -1;
3047 return 0;
3050 /** Something has happened to the stream associated with AP connection
3051 * <b>conn</b>: tell any interested control connections. */
3053 control_event_stream_status(edge_connection_t *conn, stream_status_event_t tp,
3054 int reason_code)
3056 char reason_buf[64];
3057 char addrport_buf[64];
3058 const char *status;
3059 circuit_t *circ;
3060 origin_circuit_t *origin_circ = NULL;
3061 char buf[256];
3062 const char *purpose = "";
3063 tor_assert(conn->socks_request);
3065 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
3066 return 0;
3068 if (tp == STREAM_EVENT_CLOSED &&
3069 (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
3070 return 0;
3072 write_stream_target_to_buf(conn, buf, sizeof(buf));
3074 reason_buf[0] = '\0';
3075 switch (tp)
3077 case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
3078 case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
3079 case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
3080 case STREAM_EVENT_FAILED: status = "FAILED"; break;
3081 case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
3082 case STREAM_EVENT_NEW: status = "NEW"; break;
3083 case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
3084 case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
3085 case STREAM_EVENT_REMAP: status = "REMAP"; break;
3086 default:
3087 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3088 return 0;
3090 if (reason_code && (tp == STREAM_EVENT_FAILED ||
3091 tp == STREAM_EVENT_CLOSED ||
3092 tp == STREAM_EVENT_FAILED_RETRIABLE)) {
3093 const char *reason_str = stream_end_reason_to_control_string(reason_code);
3094 char *r = NULL;
3095 if (!reason_str) {
3096 r = tor_malloc(16);
3097 tor_snprintf(r, 16, " UNKNOWN_%d", reason_code);
3098 reason_str = r;
3100 if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
3101 tor_snprintf(reason_buf, sizeof(reason_buf),
3102 " REASON=END REMOTE_REASON=%s", reason_str);
3103 else
3104 tor_snprintf(reason_buf, sizeof(reason_buf),
3105 " REASON=%s", reason_str);
3106 tor_free(r);
3107 } else if (reason_code && tp == STREAM_EVENT_REMAP) {
3108 switch (reason_code) {
3109 case REMAP_STREAM_SOURCE_CACHE:
3110 strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
3111 break;
3112 case REMAP_STREAM_SOURCE_EXIT:
3113 strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
3114 break;
3115 default:
3116 tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
3117 reason_code);
3118 /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
3119 break;
3123 if (tp == STREAM_EVENT_NEW) {
3124 tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
3125 TO_CONN(conn)->address, TO_CONN(conn)->port );
3126 } else {
3127 addrport_buf[0] = '\0';
3130 if (tp == STREAM_EVENT_NEW_RESOLVE) {
3131 purpose = " PURPOSE=DNS_REQUEST";
3132 } else if (tp == STREAM_EVENT_NEW) {
3133 if (conn->is_dns_request ||
3134 (conn->socks_request &&
3135 SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)))
3136 purpose = " PURPOSE=DNS_REQUEST";
3137 else if (conn->use_begindir) {
3138 connection_t *linked = TO_CONN(conn)->linked_conn;
3139 int linked_dir_purpose = -1;
3140 if (linked && linked->type == CONN_TYPE_DIR)
3141 linked_dir_purpose = linked->purpose;
3142 if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
3143 purpose = " PURPOSE=DIR_UPLOAD";
3144 else
3145 purpose = " PURPOSE=DIR_FETCH";
3146 } else
3147 purpose = " PURPOSE=USER";
3150 circ = circuit_get_by_edge_conn(conn);
3151 if (circ && CIRCUIT_IS_ORIGIN(circ))
3152 origin_circ = TO_ORIGIN_CIRCUIT(circ);
3153 send_control_event(EVENT_STREAM_STATUS, ALL_FORMATS,
3154 "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
3155 U64_PRINTF_ARG(conn->_base.global_identifier), status,
3156 origin_circ?
3157 (unsigned long)origin_circ->global_identifier : 0ul,
3158 buf, reason_buf, addrport_buf, purpose);
3160 /* XXX need to specify its intended exit, etc? */
3162 return 0;
3165 /** Figure out the best name for the target router of an OR connection
3166 * <b>conn</b>, and write it into the <b>len</b>-character buffer
3167 * <b>name</b>. */
3168 static void
3169 orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
3171 routerinfo_t *ri = router_get_by_digest(conn->identity_digest);
3172 if (ri) {
3173 tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
3174 router_get_verbose_nickname(name, ri);
3175 } else if (! tor_digest_is_zero(conn->identity_digest)) {
3176 name[0] = '$';
3177 base16_encode(name+1, len-1, conn->identity_digest,
3178 DIGEST_LEN);
3179 } else {
3180 tor_snprintf(name, len, "%s:%d",
3181 conn->_base.address, conn->_base.port);
3185 /** Called when the status of an OR connection <b>conn</b> changes: tell any
3186 * interested control connections. <b>tp</b> is the new status for the
3187 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
3188 * may be the reason why.
3191 control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
3192 int reason)
3194 int ncircs = 0;
3195 const char *status;
3196 char name[128];
3197 char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
3199 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
3200 return 0;
3202 switch (tp)
3204 case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
3205 case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
3206 case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
3207 case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
3208 case OR_CONN_EVENT_NEW: status = "NEW"; break;
3209 default:
3210 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3211 return 0;
3213 ncircs = circuit_count_pending_on_or_conn(conn);
3214 ncircs += conn->n_circuits;
3215 if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
3216 tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
3217 reason ? " " : "", ncircs);
3220 orconn_target_get_name(name, sizeof(name), conn);
3221 send_control_event(EVENT_OR_CONN_STATUS, ALL_FORMATS,
3222 "650 ORCONN %s %s %s%s%s\r\n",
3223 name, status,
3224 reason ? "REASON=" : "",
3225 orconn_end_reason_to_control_string(reason),
3226 ncircs_buf);
3228 return 0;
3232 * Print out STREAM_BW event for a single conn
3235 control_event_stream_bandwidth(edge_connection_t *edge_conn)
3237 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
3238 if (!edge_conn->n_read && !edge_conn->n_written)
3239 return 0;
3241 send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
3242 "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
3243 U64_PRINTF_ARG(edge_conn->_base.global_identifier),
3244 (unsigned long)edge_conn->n_read,
3245 (unsigned long)edge_conn->n_written);
3247 edge_conn->n_written = edge_conn->n_read = 0;
3250 return 0;
3253 /** A second or more has elapsed: tell any interested control
3254 * connections how much bandwidth streams have used. */
3256 control_event_stream_bandwidth_used(void)
3258 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
3259 smartlist_t *conns = get_connection_array();
3260 edge_connection_t *edge_conn;
3262 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
3264 if (conn->type != CONN_TYPE_AP)
3265 continue;
3266 edge_conn = TO_EDGE_CONN(conn);
3267 if (!edge_conn->n_read && !edge_conn->n_written)
3268 continue;
3270 send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
3271 "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
3272 U64_PRINTF_ARG(edge_conn->_base.global_identifier),
3273 (unsigned long)edge_conn->n_read,
3274 (unsigned long)edge_conn->n_written);
3276 edge_conn->n_written = edge_conn->n_read = 0;
3278 SMARTLIST_FOREACH_END(conn);
3281 return 0;
3284 /** A second or more has elapsed: tell any interested control
3285 * connections how much bandwidth we used. */
3287 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
3289 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
3290 send_control_event(EVENT_BANDWIDTH_USED, ALL_FORMATS,
3291 "650 BW %lu %lu\r\n",
3292 (unsigned long)n_read,
3293 (unsigned long)n_written);
3296 return 0;
3299 /** Called when we are sending a log message to the controllers: suspend
3300 * sending further log messages to the controllers until we're done. Used by
3301 * CONN_LOG_PROTECT. */
3302 void
3303 disable_control_logging(void)
3305 ++disable_log_messages;
3308 /** We're done sending a log message to the controllers: re-enable controller
3309 * logging. Used by CONN_LOG_PROTECT. */
3310 void
3311 enable_control_logging(void)
3313 if (--disable_log_messages < 0)
3314 tor_assert(0);
3317 /** We got a log message: tell any interested control connections. */
3318 void
3319 control_event_logmsg(int severity, uint32_t domain, const char *msg)
3321 int event;
3323 /* Don't even think of trying to add stuff to a buffer from a cpuworker
3324 * thread. */
3325 if (! in_main_thread())
3326 return;
3328 if (disable_log_messages)
3329 return;
3331 if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
3332 severity <= LOG_NOTICE) {
3333 char *esc = esc_for_log(msg);
3334 ++disable_log_messages;
3335 control_event_general_status(severity, "BUG REASON=\"%s\"", esc);
3336 --disable_log_messages;
3337 tor_free(esc);
3340 event = log_severity_to_event(severity);
3341 if (event >= 0 && EVENT_IS_INTERESTING(event)) {
3342 char *b = NULL;
3343 const char *s;
3344 if (strchr(msg, '\n')) {
3345 char *cp;
3346 b = tor_strdup(msg);
3347 for (cp = b; *cp; ++cp)
3348 if (*cp == '\r' || *cp == '\n')
3349 *cp = ' ';
3351 switch (severity) {
3352 case LOG_DEBUG: s = "DEBUG"; break;
3353 case LOG_INFO: s = "INFO"; break;
3354 case LOG_NOTICE: s = "NOTICE"; break;
3355 case LOG_WARN: s = "WARN"; break;
3356 case LOG_ERR: s = "ERR"; break;
3357 default: s = "UnknownLogSeverity"; break;
3359 ++disable_log_messages;
3360 send_control_event(event, ALL_FORMATS, "650 %s %s\r\n", s, b?b:msg);
3361 --disable_log_messages;
3362 tor_free(b);
3366 /** Called whenever we receive new router descriptors: tell any
3367 * interested control connections. <b>routers</b> is a list of
3368 * routerinfo_t's.
3371 control_event_descriptors_changed(smartlist_t *routers)
3373 char *msg;
3375 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
3376 return 0;
3379 smartlist_t *names = smartlist_create();
3380 char *ids;
3381 size_t names_len;
3382 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
3383 char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
3384 router_get_verbose_nickname(b, ri);
3385 smartlist_add(names, b);
3387 ids = smartlist_join_strings(names, " ", 0, &names_len);
3388 names_len = strlen(ids)+32;
3389 msg = tor_malloc(names_len);
3390 tor_snprintf(msg, names_len, "650 NEWDESC %s\r\n", ids);
3391 send_control_event_string(EVENT_NEW_DESC, ALL_FORMATS, msg);
3392 tor_free(ids);
3393 tor_free(msg);
3394 SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
3395 smartlist_free(names);
3397 return 0;
3400 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
3401 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
3402 * <b>error</b> is non-NULL, it is an error code describing the failure
3403 * mode of the mapping.
3406 control_event_address_mapped(const char *from, const char *to, time_t expires,
3407 const char *error)
3409 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
3410 return 0;
3412 if (expires < 3 || expires == TIME_MAX)
3413 send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
3414 "650 ADDRMAP %s %s NEVER %s\r\n", from, to,
3415 error?error:"");
3416 else {
3417 char buf[ISO_TIME_LEN+1];
3418 char buf2[ISO_TIME_LEN+1];
3419 format_local_iso_time(buf,expires);
3420 format_iso_time(buf2,expires);
3421 send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
3422 "650 ADDRMAP %s %s \"%s\""
3423 " %s%sEXPIRES=\"%s\"\r\n",
3424 from, to, buf,
3425 error?error:"", error?" ":"",
3426 buf2);
3429 return 0;
3432 /** The authoritative dirserver has received a new descriptor that
3433 * has passed basic syntax checks and is properly self-signed.
3435 * Notify any interested party of the new descriptor and what has
3436 * been done with it, and also optionally give an explanation/reason. */
3438 control_event_or_authdir_new_descriptor(const char *action,
3439 const char *desc, size_t desclen,
3440 const char *msg)
3442 char firstline[1024];
3443 char *buf;
3444 size_t totallen;
3445 char *esc = NULL;
3446 size_t esclen;
3448 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
3449 return 0;
3451 tor_snprintf(firstline, sizeof(firstline),
3452 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
3453 action,
3454 msg ? msg : "");
3456 /* Escape the server descriptor properly */
3457 esclen = write_escaped_data(desc, desclen, &esc);
3459 totallen = strlen(firstline) + esclen + 1;
3460 buf = tor_malloc(totallen);
3461 strlcpy(buf, firstline, totallen);
3462 strlcpy(buf+strlen(firstline), esc, totallen);
3463 send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
3464 buf);
3465 send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
3466 "650 OK\r\n");
3467 tor_free(esc);
3468 tor_free(buf);
3470 return 0;
3473 /** Helper function for NS-style events. Constructs and sends an event
3474 * of type <b>event</b> with string <b>event_string</b> out of the set of
3475 * networkstatuses <b>statuses</b>. Currently it is used for NS events
3476 * and NEWCONSENSUS events. */
3477 static int
3478 control_event_networkstatus_changed_helper(smartlist_t *statuses,
3479 uint16_t event,
3480 const char *event_string)
3482 smartlist_t *strs;
3483 char *s, *esc = NULL;
3484 if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
3485 return 0;
3487 strs = smartlist_create();
3488 smartlist_add(strs, tor_strdup("650+"));
3489 smartlist_add(strs, tor_strdup(event_string));
3490 smartlist_add(strs, tor_strdup("\r\n"));
3491 SMARTLIST_FOREACH(statuses, routerstatus_t *, rs,
3493 s = networkstatus_getinfo_helper_single(rs);
3494 if (!s) continue;
3495 smartlist_add(strs, s);
3498 s = smartlist_join_strings(strs, "", 0, NULL);
3499 write_escaped_data(s, strlen(s), &esc);
3500 SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
3501 smartlist_free(strs);
3502 tor_free(s);
3503 send_control_event_string(event, ALL_FORMATS, esc);
3504 send_control_event_string(event, ALL_FORMATS,
3505 "650 OK\r\n");
3507 tor_free(esc);
3508 return 0;
3511 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
3512 * an NS event to any controller that cares. */
3514 control_event_networkstatus_changed(smartlist_t *statuses)
3516 return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
3519 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
3520 * event consisting of an NS-style line for each relay in the consensus. */
3522 control_event_newconsensus(const networkstatus_t *consensus)
3524 if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
3525 return 0;
3526 return control_event_networkstatus_changed_helper(
3527 consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
3530 /** Called when we compute a new circuitbuildtimeout */
3532 control_event_buildtimeout_set(const circuit_build_times_t *cbt,
3533 buildtimeout_set_event_t type)
3535 const char *type_string = NULL;
3536 double qnt = circuit_build_times_quantile_cutoff();
3538 if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
3539 return 0;
3541 switch (type) {
3542 case BUILDTIMEOUT_SET_EVENT_COMPUTED:
3543 type_string = "COMPUTED";
3544 break;
3545 case BUILDTIMEOUT_SET_EVENT_RESET:
3546 type_string = "RESET";
3547 qnt = 1.0;
3548 break;
3549 case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
3550 type_string = "SUSPENDED";
3551 qnt = 1.0;
3552 break;
3553 case BUILDTIMEOUT_SET_EVENT_DISCARD:
3554 type_string = "DISCARD";
3555 qnt = 1.0;
3556 break;
3557 case BUILDTIMEOUT_SET_EVENT_RESUME:
3558 type_string = "RESUME";
3559 break;
3560 default:
3561 type_string = "UNKNOWN";
3562 break;
3565 send_control_event(EVENT_BUILDTIMEOUT_SET, ALL_FORMATS,
3566 "650 BUILDTIMEOUT_SET %s TOTAL_TIMES=%lu "
3567 "TIMEOUT_MS=%lu XM=%lu ALPHA=%lf CUTOFF_QUANTILE=%lf "
3568 "TIMEOUT_RATE=%lf CLOSE_MS=%lu CLOSE_RATE=%lf\r\n",
3569 type_string, (unsigned long)cbt->total_build_times,
3570 (unsigned long)cbt->timeout_ms,
3571 (unsigned long)cbt->Xm, cbt->alpha, qnt,
3572 circuit_build_times_timeout_rate(cbt),
3573 (unsigned long)cbt->close_ms,
3574 circuit_build_times_close_rate(cbt));
3576 return 0;
3579 /** Called when a single local_routerstatus_t has changed: Sends an NS event
3580 * to any controller that cares. */
3582 control_event_networkstatus_changed_single(routerstatus_t *rs)
3584 smartlist_t *statuses;
3585 int r;
3587 if (!EVENT_IS_INTERESTING(EVENT_NS))
3588 return 0;
3590 statuses = smartlist_create();
3591 smartlist_add(statuses, rs);
3592 r = control_event_networkstatus_changed(statuses);
3593 smartlist_free(statuses);
3594 return r;
3597 /** Our own router descriptor has changed; tell any controllers that care.
3600 control_event_my_descriptor_changed(void)
3602 send_control_event(EVENT_DESCCHANGED, ALL_FORMATS, "650 DESCCHANGED\r\n");
3603 return 0;
3606 /** Helper: sends a status event where <b>type</b> is one of
3607 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
3608 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
3609 * string corresponding to <b>args</b>. */
3610 static int
3611 control_event_status(int type, int severity, const char *format, va_list args)
3613 char format_buf[160];
3614 const char *status, *sev;
3616 switch (type) {
3617 case EVENT_STATUS_GENERAL:
3618 status = "STATUS_GENERAL";
3619 break;
3620 case EVENT_STATUS_CLIENT:
3621 status = "STATUS_CLIENT";
3622 break;
3623 case EVENT_STATUS_SERVER:
3624 status = "STATUS_SERVER";
3625 break;
3626 default:
3627 log_warn(LD_BUG, "Unrecognized status type %d", type);
3628 return -1;
3630 switch (severity) {
3631 case LOG_NOTICE:
3632 sev = "NOTICE";
3633 break;
3634 case LOG_WARN:
3635 sev = "WARN";
3636 break;
3637 case LOG_ERR:
3638 sev = "ERR";
3639 break;
3640 default:
3641 log_warn(LD_BUG, "Unrecognized status severity %d", severity);
3642 return -1;
3644 if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s %s\r\n",
3645 status, sev, format)<0) {
3646 log_warn(LD_BUG, "Format string too long.");
3647 return -1;
3650 send_control_event_impl(type, ALL_FORMATS, format_buf, args);
3651 return 0;
3654 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
3655 * by formatting the arguments using the printf-style <b>format</b>. */
3657 control_event_general_status(int severity, const char *format, ...)
3659 va_list ap;
3660 int r;
3661 if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
3662 return 0;
3664 va_start(ap, format);
3665 r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
3666 va_end(ap);
3667 return r;
3670 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
3671 * by formatting the arguments using the printf-style <b>format</b>. */
3673 control_event_client_status(int severity, const char *format, ...)
3675 va_list ap;
3676 int r;
3677 if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
3678 return 0;
3680 va_start(ap, format);
3681 r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
3682 va_end(ap);
3683 return r;
3686 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
3687 * by formatting the arguments using the printf-style <b>format</b>. */
3689 control_event_server_status(int severity, const char *format, ...)
3691 va_list ap;
3692 int r;
3693 if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
3694 return 0;
3696 va_start(ap, format);
3697 r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
3698 va_end(ap);
3699 return r;
3702 /** Called when the status of an entry guard with the given <b>nickname</b>
3703 * and identity <b>digest</b> has changed to <b>status</b>: tells any
3704 * controllers that care. */
3706 control_event_guard(const char *nickname, const char *digest,
3707 const char *status)
3709 char hbuf[HEX_DIGEST_LEN+1];
3710 base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
3711 if (!EVENT_IS_INTERESTING(EVENT_GUARD))
3712 return 0;
3715 char buf[MAX_VERBOSE_NICKNAME_LEN+1];
3716 routerinfo_t *ri = router_get_by_digest(digest);
3717 if (ri) {
3718 router_get_verbose_nickname(buf, ri);
3719 } else {
3720 tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
3722 send_control_event(EVENT_GUARD, ALL_FORMATS,
3723 "650 GUARD ENTRY %s %s\r\n", buf, status);
3725 return 0;
3728 /** Helper: Return a newly allocated string containing a path to the
3729 * file where we store our authentication cookie. */
3730 static char *
3731 get_cookie_file(void)
3733 or_options_t *options = get_options();
3734 if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
3735 return tor_strdup(options->CookieAuthFile);
3736 } else {
3737 return get_datadir_fname("control_auth_cookie");
3741 /** Choose a random authentication cookie and write it to disk.
3742 * Anybody who can read the cookie from disk will be considered
3743 * authorized to use the control connection. Return -1 if we can't
3744 * write the file, or 0 on success. */
3746 init_cookie_authentication(int enabled)
3748 char *fname;
3749 if (!enabled) {
3750 authentication_cookie_is_set = 0;
3751 return 0;
3754 /* We don't want to generate a new cookie every time we call
3755 * options_act(). One should be enough. */
3756 if (authentication_cookie_is_set)
3757 return 0; /* all set */
3759 fname = get_cookie_file();
3760 crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
3761 authentication_cookie_is_set = 1;
3762 if (write_bytes_to_file(fname, authentication_cookie,
3763 AUTHENTICATION_COOKIE_LEN, 1)) {
3764 log_warn(LD_FS,"Error writing authentication cookie to %s.",
3765 escaped(fname));
3766 tor_free(fname);
3767 return -1;
3769 #ifndef MS_WINDOWS
3770 if (get_options()->CookieAuthFileGroupReadable) {
3771 if (chmod(fname, 0640)) {
3772 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
3775 #endif
3777 tor_free(fname);
3778 return 0;
3781 /** Convert the name of a bootstrapping phase <b>s</b> into strings
3782 * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
3783 static int
3784 bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
3785 const char **summary)
3787 switch (s) {
3788 case BOOTSTRAP_STATUS_UNDEF:
3789 *tag = "undef";
3790 *summary = "Undefined";
3791 break;
3792 case BOOTSTRAP_STATUS_STARTING:
3793 *tag = "starting";
3794 *summary = "Starting";
3795 break;
3796 case BOOTSTRAP_STATUS_CONN_DIR:
3797 *tag = "conn_dir";
3798 *summary = "Connecting to directory server";
3799 break;
3800 case BOOTSTRAP_STATUS_HANDSHAKE:
3801 *tag = "status_handshake";
3802 *summary = "Finishing handshake";
3803 break;
3804 case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
3805 *tag = "handshake_dir";
3806 *summary = "Finishing handshake with directory server";
3807 break;
3808 case BOOTSTRAP_STATUS_ONEHOP_CREATE:
3809 *tag = "onehop_create";
3810 *summary = "Establishing an encrypted directory connection";
3811 break;
3812 case BOOTSTRAP_STATUS_REQUESTING_STATUS:
3813 *tag = "requesting_status";
3814 *summary = "Asking for networkstatus consensus";
3815 break;
3816 case BOOTSTRAP_STATUS_LOADING_STATUS:
3817 *tag = "loading_status";
3818 *summary = "Loading networkstatus consensus";
3819 break;
3820 case BOOTSTRAP_STATUS_LOADING_KEYS:
3821 *tag = "loading_keys";
3822 *summary = "Loading authority key certs";
3823 break;
3824 case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
3825 *tag = "requesting_descriptors";
3826 *summary = "Asking for relay descriptors";
3827 break;
3828 case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
3829 *tag = "loading_descriptors";
3830 *summary = "Loading relay descriptors";
3831 break;
3832 case BOOTSTRAP_STATUS_CONN_OR:
3833 *tag = "conn_or";
3834 *summary = "Connecting to the Tor network";
3835 break;
3836 case BOOTSTRAP_STATUS_HANDSHAKE_OR:
3837 *tag = "handshake_or";
3838 *summary = "Finishing handshake with first hop";
3839 break;
3840 case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
3841 *tag = "circuit_create";
3842 *summary = "Establishing a Tor circuit";
3843 break;
3844 case BOOTSTRAP_STATUS_DONE:
3845 *tag = "done";
3846 *summary = "Done";
3847 break;
3848 default:
3849 // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
3850 *tag = *summary = "unknown";
3851 return -1;
3853 return 0;
3856 /** What percentage through the bootstrap process are we? We remember
3857 * this so we can avoid sending redundant bootstrap status events, and
3858 * so we can guess context for the bootstrap messages which are
3859 * ambiguous. It starts at 'undef', but gets set to 'starting' while
3860 * Tor initializes. */
3861 static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
3863 /** How many problems have we had getting to the next bootstrapping phase?
3864 * These include failure to establish a connection to a Tor relay,
3865 * failures to finish the TLS handshake, failures to validate the
3866 * consensus document, etc. */
3867 static int bootstrap_problems = 0;
3869 /* We only tell the controller once we've hit a threshold of problems
3870 * for the current phase. */
3871 #define BOOTSTRAP_PROBLEM_THRESHOLD 10
3873 /** Called when Tor has made progress at bootstrapping its directory
3874 * information and initial circuits.
3876 * <b>status</b> is the new status, that is, what task we will be doing
3877 * next. <b>percent</b> is zero if we just started this task, else it
3878 * represents progress on the task. */
3879 void
3880 control_event_bootstrap(bootstrap_status_t status, int progress)
3882 const char *tag, *summary;
3883 char buf[BOOTSTRAP_MSG_LEN];
3885 if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
3886 return; /* already bootstrapped; nothing to be done here. */
3888 /* special case for handshaking status, since our TLS handshaking code
3889 * can't distinguish what the connection is going to be for. */
3890 if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
3891 if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
3892 status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
3893 } else {
3894 status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
3898 if (status > bootstrap_percent ||
3899 (progress && progress > bootstrap_percent)) {
3900 bootstrap_status_to_string(status, &tag, &summary);
3901 log(status ? LOG_NOTICE : LOG_INFO, LD_CONTROL,
3902 "Bootstrapped %d%%: %s.", progress ? progress : status, summary);
3903 tor_snprintf(buf, sizeof(buf),
3904 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
3905 progress ? progress : status, tag, summary);
3906 tor_snprintf(last_sent_bootstrap_message,
3907 sizeof(last_sent_bootstrap_message),
3908 "NOTICE %s", buf);
3909 control_event_client_status(LOG_NOTICE, "%s", buf);
3910 if (status > bootstrap_percent) {
3911 bootstrap_percent = status; /* new milestone reached */
3913 if (progress > bootstrap_percent) {
3914 /* incremental progress within a milestone */
3915 bootstrap_percent = progress;
3916 bootstrap_problems = 0; /* Progress! Reset our problem counter. */
3921 /** Called when Tor has failed to make bootstrapping progress in a way
3922 * that indicates a problem. <b>warn</b> gives a hint as to why, and
3923 * <b>reason</b> provides an "or_conn_end_reason" tag.
3925 void
3926 control_event_bootstrap_problem(const char *warn, int reason)
3928 int status = bootstrap_percent;
3929 const char *tag, *summary;
3930 char buf[BOOTSTRAP_MSG_LEN];
3931 const char *recommendation = "ignore";
3933 if (bootstrap_percent == 100)
3934 return; /* already bootstrapped; nothing to be done here. */
3936 bootstrap_problems++;
3938 if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
3939 recommendation = "warn";
3941 if (reason == END_OR_CONN_REASON_NO_ROUTE)
3942 recommendation = "warn";
3944 if (get_options()->UseBridges &&
3945 !any_bridge_descriptors_known() &&
3946 !any_pending_bridge_descriptor_fetches())
3947 recommendation = "warn";
3949 while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
3950 status--; /* find a recognized status string based on current progress */
3951 status = bootstrap_percent; /* set status back to the actual number */
3953 log_fn(!strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO,
3954 LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
3955 "count %d; recommendation %s)",
3956 status, summary, warn,
3957 orconn_end_reason_to_control_string(reason),
3958 bootstrap_problems, recommendation);
3959 tor_snprintf(buf, sizeof(buf),
3960 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
3961 "COUNT=%d RECOMMENDATION=%s",
3962 bootstrap_percent, tag, summary, warn,
3963 orconn_end_reason_to_control_string(reason), bootstrap_problems,
3964 recommendation);
3965 tor_snprintf(last_sent_bootstrap_message,
3966 sizeof(last_sent_bootstrap_message),
3967 "WARN %s", buf);
3968 control_event_client_status(LOG_WARN, "%s", buf);
3971 /** We just generated a new summary of which countries we've seen clients
3972 * from recently. Send a copy to the controller in case it wants to
3973 * display it for the user. */
3974 void
3975 control_event_clients_seen(const char *controller_str)
3977 send_control_event(EVENT_CLIENTS_SEEN, 0,
3978 "650 CLIENTS_SEEN %s\r\n", controller_str);