Send control port events for timeouts.
[tor.git] / src / or / control.c
blob4d505a98fb4c26e60fe6db441c30be0d4c30db33
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2010, 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 control_signal_act(sig);
1226 return 0;
1229 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1230 * and report success or failure. */
1231 static int
1232 handle_control_mapaddress(control_connection_t *conn, uint32_t len,
1233 const char *body)
1235 smartlist_t *elts;
1236 smartlist_t *lines;
1237 smartlist_t *reply;
1238 char *r;
1239 size_t sz;
1240 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
1242 lines = smartlist_create();
1243 elts = smartlist_create();
1244 reply = smartlist_create();
1245 smartlist_split_string(lines, body, " ",
1246 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1247 SMARTLIST_FOREACH(lines, char *, line,
1249 tor_strlower(line);
1250 smartlist_split_string(elts, line, "=", 0, 2);
1251 if (smartlist_len(elts) == 2) {
1252 const char *from = smartlist_get(elts,0);
1253 const char *to = smartlist_get(elts,1);
1254 size_t anslen = strlen(line)+512;
1255 char *ans = tor_malloc(anslen);
1256 if (address_is_invalid_destination(to, 1)) {
1257 tor_snprintf(ans, anslen,
1258 "512-syntax error: invalid address '%s'", to);
1259 smartlist_add(reply, ans);
1260 log_warn(LD_CONTROL,
1261 "Skipping invalid argument '%s' in MapAddress msg", to);
1262 } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
1263 const char *address = addressmap_register_virtual_address(
1264 !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
1265 tor_strdup(to));
1266 if (!address) {
1267 tor_snprintf(ans, anslen,
1268 "451-resource exhausted: skipping '%s'", line);
1269 smartlist_add(reply, ans);
1270 log_warn(LD_CONTROL,
1271 "Unable to allocate address for '%s' in MapAddress msg",
1272 safe_str_client(line));
1273 } else {
1274 tor_snprintf(ans, anslen, "250-%s=%s", address, to);
1275 smartlist_add(reply, ans);
1277 } else {
1278 addressmap_register(from, tor_strdup(to), 1, ADDRMAPSRC_CONTROLLER);
1279 tor_snprintf(ans, anslen, "250-%s", line);
1280 smartlist_add(reply, ans);
1282 } else {
1283 size_t anslen = strlen(line)+256;
1284 char *ans = tor_malloc(anslen);
1285 tor_snprintf(ans, anslen, "512-syntax error: mapping '%s' is "
1286 "not of expected form 'foo=bar'.", line);
1287 smartlist_add(reply, ans);
1288 log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
1289 "number of items.",
1290 safe_str_client(line));
1292 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
1293 smartlist_clear(elts);
1295 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1296 smartlist_free(lines);
1297 smartlist_free(elts);
1299 if (smartlist_len(reply)) {
1300 ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
1301 r = smartlist_join_strings(reply, "\r\n", 1, &sz);
1302 connection_write_to_buf(r, sz, TO_CONN(conn));
1303 tor_free(r);
1304 } else {
1305 const char *response =
1306 "512 syntax error: not enough arguments to mapaddress.\r\n";
1307 connection_write_to_buf(response, strlen(response), TO_CONN(conn));
1310 SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
1311 smartlist_free(reply);
1312 return 0;
1315 /** Implementation helper for GETINFO: knows the answers for various
1316 * trivial-to-implement questions. */
1317 static int
1318 getinfo_helper_misc(control_connection_t *conn, const char *question,
1319 char **answer, const char **errmsg)
1321 (void) conn;
1322 if (!strcmp(question, "version")) {
1323 *answer = tor_strdup(get_version());
1324 } else if (!strcmp(question, "config-file")) {
1325 *answer = tor_strdup(get_torrc_fname());
1326 } else if (!strcmp(question, "config-text")) {
1327 *answer = options_dump(get_options(), 1);
1328 } else if (!strcmp(question, "info/names")) {
1329 *answer = list_getinfo_options();
1330 } else if (!strcmp(question, "events/names")) {
1331 *answer = tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
1332 "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
1333 "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
1334 "GUARD STREAM_BW CLIENTS_SEEN NEWCONSENSUS");
1335 } else if (!strcmp(question, "features/names")) {
1336 *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1337 } else if (!strcmp(question, "address")) {
1338 uint32_t addr;
1339 if (router_pick_published_address(get_options(), &addr) < 0) {
1340 *errmsg = "Address unknown";
1341 return -1;
1343 *answer = tor_dup_ip(addr);
1344 } else if (!strcmp(question, "dir-usage")) {
1345 *answer = directory_dump_request_log();
1346 } else if (!strcmp(question, "fingerprint")) {
1347 routerinfo_t *me = router_get_my_routerinfo();
1348 if (!me) {
1349 *errmsg = "No routerdesc known; am I really a server?";
1350 return -1;
1352 *answer = tor_malloc(HEX_DIGEST_LEN+1);
1353 base16_encode(*answer, HEX_DIGEST_LEN+1, me->cache_info.identity_digest,
1354 DIGEST_LEN);
1356 return 0;
1359 /** Awful hack: return a newly allocated string based on a routerinfo and
1360 * (possibly) an extrainfo, sticking the read-history and write-history from
1361 * <b>ei</b> into the resulting string. The thing you get back won't
1362 * necessarily have a valid signature.
1364 * New code should never use this; it's for backward compatibility.
1366 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1367 * not be NUL-terminated. */
1368 static char *
1369 munge_extrainfo_into_routerinfo(const char *ri_body, signed_descriptor_t *ri,
1370 signed_descriptor_t *ei)
1372 char *out = NULL, *outp;
1373 int i;
1374 const char *router_sig;
1375 const char *ei_body = signed_descriptor_get_body(ei);
1376 size_t ri_len = ri->signed_descriptor_len;
1377 size_t ei_len = ei->signed_descriptor_len;
1378 if (!ei_body)
1379 goto bail;
1381 outp = out = tor_malloc(ri_len+ei_len+1);
1382 if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
1383 goto bail;
1384 ++router_sig;
1385 memcpy(out, ri_body, router_sig-ri_body);
1386 outp += router_sig-ri_body;
1388 for (i=0; i < 2; ++i) {
1389 const char *kwd = i?"\nwrite-history ":"\nread-history ";
1390 const char *cp, *eol;
1391 if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
1392 continue;
1393 ++cp;
1394 eol = memchr(cp, '\n', ei_len - (cp-ei_body));
1395 memcpy(outp, cp, eol-cp+1);
1396 outp += eol-cp+1;
1398 memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
1399 *outp++ = '\0';
1400 tor_assert(outp-out < (int)(ri_len+ei_len+1));
1402 return out;
1403 bail:
1404 tor_free(out);
1405 return tor_strndup(ri_body, ri->signed_descriptor_len);
1408 /** Implementation helper for GETINFO: knows the answers for questions about
1409 * directory information. */
1410 static int
1411 getinfo_helper_dir(control_connection_t *control_conn,
1412 const char *question, char **answer,
1413 const char **errmsg)
1415 (void) control_conn;
1416 if (!strcmpstart(question, "desc/id/")) {
1417 routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
1418 if (ri) {
1419 const char *body = signed_descriptor_get_body(&ri->cache_info);
1420 if (body)
1421 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1423 } else if (!strcmpstart(question, "desc/name/")) {
1424 routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
1425 if (ri) {
1426 const char *body = signed_descriptor_get_body(&ri->cache_info);
1427 if (body)
1428 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1430 } else if (!strcmp(question, "desc/all-recent")) {
1431 routerlist_t *routerlist = router_get_routerlist();
1432 smartlist_t *sl = smartlist_create();
1433 if (routerlist && routerlist->routers) {
1434 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
1436 const char *body = signed_descriptor_get_body(&ri->cache_info);
1437 if (body)
1438 smartlist_add(sl,
1439 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1442 *answer = smartlist_join_strings(sl, "", 0, NULL);
1443 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1444 smartlist_free(sl);
1445 } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
1446 /* XXXX Remove this once Torstat asks for extrainfos. */
1447 routerlist_t *routerlist = router_get_routerlist();
1448 smartlist_t *sl = smartlist_create();
1449 if (routerlist && routerlist->routers) {
1450 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
1452 const char *body = signed_descriptor_get_body(&ri->cache_info);
1453 signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
1454 ri->cache_info.extra_info_digest);
1455 if (ei && body) {
1456 smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
1457 &ri->cache_info, ei));
1458 } else if (body) {
1459 smartlist_add(sl,
1460 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1464 *answer = smartlist_join_strings(sl, "", 0, NULL);
1465 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1466 smartlist_free(sl);
1467 } else if (!strcmpstart(question, "desc-annotations/id/")) {
1468 routerinfo_t *ri = router_get_by_hexdigest(question+
1469 strlen("desc-annotations/id/"));
1470 if (ri) {
1471 const char *annotations =
1472 signed_descriptor_get_annotations(&ri->cache_info);
1473 if (annotations)
1474 *answer = tor_strndup(annotations,
1475 ri->cache_info.annotations_len);
1477 } else if (!strcmpstart(question, "dir/server/")) {
1478 size_t answer_len = 0, url_len = strlen(question)+2;
1479 char *url = tor_malloc(url_len);
1480 smartlist_t *descs = smartlist_create();
1481 const char *msg;
1482 int res;
1483 char *cp;
1484 tor_snprintf(url, url_len, "/tor/%s", question+4);
1485 res = dirserv_get_routerdescs(descs, url, &msg);
1486 if (res) {
1487 log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
1488 smartlist_free(descs);
1489 tor_free(url);
1490 *errmsg = msg;
1491 return -1;
1493 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1494 answer_len += sd->signed_descriptor_len);
1495 cp = *answer = tor_malloc(answer_len+1);
1496 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1498 memcpy(cp, signed_descriptor_get_body(sd),
1499 sd->signed_descriptor_len);
1500 cp += sd->signed_descriptor_len;
1502 *cp = '\0';
1503 tor_free(url);
1504 smartlist_free(descs);
1505 } else if (!strcmpstart(question, "dir/status/")) {
1506 if (directory_permits_controller_requests(get_options())) {
1507 size_t len=0;
1508 char *cp;
1509 smartlist_t *status_list = smartlist_create();
1510 dirserv_get_networkstatus_v2(status_list,
1511 question+strlen("dir/status/"));
1512 SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
1513 cp = *answer = tor_malloc(len+1);
1514 SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
1515 memcpy(cp, d->dir, d->dir_len);
1516 cp += d->dir_len;
1518 *cp = '\0';
1519 smartlist_free(status_list);
1520 } else {
1521 smartlist_t *fp_list = smartlist_create();
1522 smartlist_t *status_list = smartlist_create();
1523 dirserv_get_networkstatus_v2_fingerprints(
1524 fp_list, question+strlen("dir/status/"));
1525 SMARTLIST_FOREACH(fp_list, const char *, fp, {
1526 char *s;
1527 char *fname = networkstatus_get_cache_filename(fp);
1528 s = read_file_to_str(fname, 0, NULL);
1529 if (s)
1530 smartlist_add(status_list, s);
1531 tor_free(fname);
1533 SMARTLIST_FOREACH(fp_list, char *, fp, tor_free(fp));
1534 smartlist_free(fp_list);
1535 *answer = smartlist_join_strings(status_list, "", 0, NULL);
1536 SMARTLIST_FOREACH(status_list, char *, s, tor_free(s));
1537 smartlist_free(status_list);
1539 } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
1540 if (directory_caches_dir_info(get_options())) {
1541 const cached_dir_t *consensus = dirserv_get_consensus("ns");
1542 if (consensus)
1543 *answer = tor_strdup(consensus->dir);
1545 if (!*answer) { /* try loading it from disk */
1546 char *filename = get_datadir_fname("cached-consensus");
1547 *answer = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
1548 tor_free(filename);
1550 } else if (!strcmp(question, "network-status")) { /* v1 */
1551 routerlist_t *routerlist = router_get_routerlist();
1552 if (!routerlist || !routerlist->routers ||
1553 list_server_status_v1(routerlist->routers, answer, 1) < 0) {
1554 return -1;
1556 } else if (!strcmpstart(question, "extra-info/digest/")) {
1557 question += strlen("extra-info/digest/");
1558 if (strlen(question) == HEX_DIGEST_LEN) {
1559 char d[DIGEST_LEN];
1560 signed_descriptor_t *sd = NULL;
1561 if (base16_decode(d, sizeof(d), question, strlen(question))==0) {
1562 /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
1563 * but I don't want to risk affecting other parts of the code,
1564 * especially since the rules for using our own extrainfo (including
1565 * when it might be freed) are different from those for using one
1566 * we have downloaded. */
1567 if (router_extrainfo_digest_is_me(d))
1568 sd = &(router_get_my_extrainfo()->cache_info);
1569 else
1570 sd = extrainfo_get_by_descriptor_digest(d);
1572 if (sd) {
1573 const char *body = signed_descriptor_get_body(sd);
1574 if (body)
1575 *answer = tor_strndup(body, sd->signed_descriptor_len);
1580 return 0;
1583 /** Implementation helper for GETINFO: knows how to generate summaries of the
1584 * current states of things we send events about. */
1585 static int
1586 getinfo_helper_events(control_connection_t *control_conn,
1587 const char *question, char **answer,
1588 const char **errmsg)
1590 (void) control_conn;
1591 if (!strcmp(question, "circuit-status")) {
1592 circuit_t *circ;
1593 smartlist_t *status = smartlist_create();
1594 for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
1595 char *s, *path;
1596 size_t slen;
1597 const char *state;
1598 const char *purpose;
1599 if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
1600 continue;
1602 path = circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ));
1604 if (circ->state == CIRCUIT_STATE_OPEN)
1605 state = "BUILT";
1606 else if (strlen(path))
1607 state = "EXTENDED";
1608 else
1609 state = "LAUNCHED";
1611 purpose = circuit_purpose_to_controller_string(circ->purpose);
1612 slen = strlen(path)+strlen(state)+strlen(purpose)+30;
1613 s = tor_malloc(slen+1);
1614 tor_snprintf(s, slen, "%lu %s%s%s PURPOSE=%s",
1615 (unsigned long)TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1616 state, *path ? " " : "", path, purpose);
1617 smartlist_add(status, s);
1618 tor_free(path);
1620 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1621 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1622 smartlist_free(status);
1623 } else if (!strcmp(question, "stream-status")) {
1624 smartlist_t *conns = get_connection_array();
1625 smartlist_t *status = smartlist_create();
1626 char buf[256];
1627 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1628 const char *state;
1629 edge_connection_t *conn;
1630 char *s;
1631 size_t slen;
1632 circuit_t *circ;
1633 origin_circuit_t *origin_circ = NULL;
1634 if (base_conn->type != CONN_TYPE_AP ||
1635 base_conn->marked_for_close ||
1636 base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
1637 base_conn->state == AP_CONN_STATE_NATD_WAIT)
1638 continue;
1639 conn = TO_EDGE_CONN(base_conn);
1640 switch (conn->_base.state)
1642 case AP_CONN_STATE_CONTROLLER_WAIT:
1643 case AP_CONN_STATE_CIRCUIT_WAIT:
1644 if (conn->socks_request &&
1645 SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
1646 state = "NEWRESOLVE";
1647 else
1648 state = "NEW";
1649 break;
1650 case AP_CONN_STATE_RENDDESC_WAIT:
1651 case AP_CONN_STATE_CONNECT_WAIT:
1652 state = "SENTCONNECT"; break;
1653 case AP_CONN_STATE_RESOLVE_WAIT:
1654 state = "SENTRESOLVE"; break;
1655 case AP_CONN_STATE_OPEN:
1656 state = "SUCCEEDED"; break;
1657 default:
1658 log_warn(LD_BUG, "Asked for stream in unknown state %d",
1659 conn->_base.state);
1660 continue;
1662 circ = circuit_get_by_edge_conn(conn);
1663 if (circ && CIRCUIT_IS_ORIGIN(circ))
1664 origin_circ = TO_ORIGIN_CIRCUIT(circ);
1665 write_stream_target_to_buf(conn, buf, sizeof(buf));
1666 slen = strlen(buf)+strlen(state)+32;
1667 s = tor_malloc(slen+1);
1668 tor_snprintf(s, slen, "%lu %s %lu %s",
1669 (unsigned long) conn->_base.global_identifier,state,
1670 origin_circ?
1671 (unsigned long)origin_circ->global_identifier : 0ul,
1672 buf);
1673 smartlist_add(status, s);
1674 } SMARTLIST_FOREACH_END(base_conn);
1675 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1676 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1677 smartlist_free(status);
1678 } else if (!strcmp(question, "orconn-status")) {
1679 smartlist_t *conns = get_connection_array();
1680 smartlist_t *status = smartlist_create();
1681 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1682 const char *state;
1683 char *s;
1684 char name[128];
1685 size_t slen;
1686 or_connection_t *conn;
1687 if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
1688 continue;
1689 conn = TO_OR_CONN(base_conn);
1690 if (conn->_base.state == OR_CONN_STATE_OPEN)
1691 state = "CONNECTED";
1692 else if (conn->nickname)
1693 state = "LAUNCHED";
1694 else
1695 state = "NEW";
1696 orconn_target_get_name(name, sizeof(name), conn);
1697 slen = strlen(name)+strlen(state)+2;
1698 s = tor_malloc(slen+1);
1699 tor_snprintf(s, slen, "%s %s", name, state);
1700 smartlist_add(status, s);
1701 } SMARTLIST_FOREACH_END(base_conn);
1702 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1703 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1704 smartlist_free(status);
1705 } else if (!strcmpstart(question, "address-mappings/")) {
1706 time_t min_e, max_e;
1707 smartlist_t *mappings;
1708 question += strlen("address-mappings/");
1709 if (!strcmp(question, "all")) {
1710 min_e = 0; max_e = TIME_MAX;
1711 } else if (!strcmp(question, "cache")) {
1712 min_e = 2; max_e = TIME_MAX;
1713 } else if (!strcmp(question, "config")) {
1714 min_e = 0; max_e = 0;
1715 } else if (!strcmp(question, "control")) {
1716 min_e = 1; max_e = 1;
1717 } else {
1718 return 0;
1720 mappings = smartlist_create();
1721 addressmap_get_mappings(mappings, min_e, max_e, 1);
1722 *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
1723 SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
1724 smartlist_free(mappings);
1725 } else if (!strcmpstart(question, "status/")) {
1726 /* Note that status/ is not a catch-all for events; there's only supposed
1727 * to be a status GETINFO if there's a corresponding STATUS event. */
1728 if (!strcmp(question, "status/circuit-established")) {
1729 *answer = tor_strdup(can_complete_circuit ? "1" : "0");
1730 } else if (!strcmp(question, "status/enough-dir-info")) {
1731 *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
1732 } else if (!strcmp(question, "status/good-server-descriptor") ||
1733 !strcmp(question, "status/accepted-server-descriptor")) {
1734 /* They're equivalent for now, until we can figure out how to make
1735 * good-server-descriptor be what we want. See comment in
1736 * control-spec.txt. */
1737 *answer = tor_strdup(directories_have_accepted_server_descriptor()
1738 ? "1" : "0");
1739 } else if (!strcmp(question, "status/reachability-succeeded/or")) {
1740 *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
1741 } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
1742 *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
1743 } else if (!strcmp(question, "status/reachability-succeeded")) {
1744 *answer = tor_malloc(16);
1745 tor_snprintf(*answer, 16, "OR=%d DIR=%d",
1746 check_whether_orport_reachable() ? 1 : 0,
1747 check_whether_dirport_reachable() ? 1 : 0);
1748 } else if (!strcmp(question, "status/bootstrap-phase")) {
1749 *answer = tor_strdup(last_sent_bootstrap_message);
1750 } else if (!strcmpstart(question, "status/version/")) {
1751 int is_server = server_mode(get_options());
1752 networkstatus_t *c = networkstatus_get_latest_consensus();
1753 version_status_t status;
1754 const char *recommended;
1755 if (c) {
1756 recommended = is_server ? c->server_versions : c->client_versions;
1757 status = tor_version_is_obsolete(VERSION, recommended);
1758 } else {
1759 recommended = "?";
1760 status = VS_UNKNOWN;
1763 if (!strcmp(question, "status/version/recommended")) {
1764 *answer = tor_strdup(recommended);
1765 return 0;
1767 if (!strcmp(question, "status/version/current")) {
1768 switch (status)
1770 case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
1771 case VS_OLD: *answer = tor_strdup("obsolete"); break;
1772 case VS_NEW: *answer = tor_strdup("new"); break;
1773 case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
1774 case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
1775 case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
1776 case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
1777 default: tor_fragile_assert();
1779 } else if (!strcmp(question, "status/version/num-versioning") ||
1780 !strcmp(question, "status/version/num-concurring")) {
1781 char s[33];
1782 tor_snprintf(s, sizeof(s), "%d", get_n_authorities(V3_AUTHORITY));
1783 *answer = tor_strdup(s);
1784 log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
1785 "information", question);
1787 } else if (!strcmp(question, "status/clients-seen")) {
1788 const char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
1789 if (!bridge_stats) {
1790 *errmsg = "No bridge-client stats available";
1791 return -1;
1793 *answer = tor_strdup(bridge_stats);
1794 } else {
1795 return 0;
1798 return 0;
1801 /** Callback function for GETINFO: on a given control connection, try to
1802 * answer the question <b>q</b> and store the newly-allocated answer in
1803 * *<b>a</b>. If an internal error occurs, return -1 and optionally set
1804 * *<b>error_out</b> to point to an error message to be delivered to the
1805 * controller. On success, _or if the key is not recognized_, return 0. Do not
1806 * set <b>a</b> if the key is not recognized.
1808 typedef int (*getinfo_helper_t)(control_connection_t *,
1809 const char *q, char **a,
1810 const char **error_out);
1812 /** A single item for the GETINFO question-to-answer-function table. */
1813 typedef struct getinfo_item_t {
1814 const char *varname; /**< The value (or prefix) of the question. */
1815 getinfo_helper_t fn; /**< The function that knows the answer: NULL if
1816 * this entry is documentation-only. */
1817 const char *desc; /**< Description of the variable. */
1818 int is_prefix; /** Must varname match exactly, or must it be a prefix? */
1819 } getinfo_item_t;
1821 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
1822 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
1823 #define DOC(name, desc) { name, NULL, desc, 0 }
1825 /** Table mapping questions accepted by GETINFO to the functions that know how
1826 * to answer them. */
1827 static const getinfo_item_t getinfo_items[] = {
1828 ITEM("version", misc, "The current version of Tor."),
1829 ITEM("config-file", misc, "Current location of the \"torrc\" file."),
1830 ITEM("config-text", misc,
1831 "Return the string that would be written by a saveconf command."),
1832 ITEM("accounting/bytes", accounting,
1833 "Number of bytes read/written so far in the accounting interval."),
1834 ITEM("accounting/bytes-left", accounting,
1835 "Number of bytes left to write/read so far in the accounting interval."),
1836 ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
1837 ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
1838 ITEM("accounting/interval-start", accounting,
1839 "Time when the accounting period starts."),
1840 ITEM("accounting/interval-end", accounting,
1841 "Time when the accounting period ends."),
1842 ITEM("accounting/interval-wake", accounting,
1843 "Time to wake up in this accounting period."),
1844 ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
1845 ITEM("entry-guards", entry_guards,
1846 "Which nodes are we using as entry guards?"),
1847 ITEM("fingerprint", misc, NULL),
1848 PREFIX("config/", config, "Current configuration values."),
1849 DOC("config/names",
1850 "List of configuration options, types, and documentation."),
1851 ITEM("info/names", misc,
1852 "List of GETINFO options, types, and documentation."),
1853 ITEM("events/names", misc,
1854 "Events that the controller can ask for with SETEVENTS."),
1855 ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
1856 PREFIX("desc/id/", dir, "Router descriptors by ID."),
1857 PREFIX("desc/name/", dir, "Router descriptors by nickname."),
1858 ITEM("desc/all-recent", dir,
1859 "All non-expired, non-superseded router descriptors."),
1860 ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
1861 PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
1862 ITEM("ns/all", networkstatus,
1863 "Brief summary of router status (v2 directory format)"),
1864 PREFIX("ns/id/", networkstatus,
1865 "Brief summary of router status by ID (v2 directory format)."),
1866 PREFIX("ns/name/", networkstatus,
1867 "Brief summary of router status by nickname (v2 directory format)."),
1868 PREFIX("ns/purpose/", networkstatus,
1869 "Brief summary of router status by purpose (v2 directory format)."),
1871 ITEM("network-status", dir,
1872 "Brief summary of router status (v1 directory format)"),
1873 ITEM("circuit-status", events, "List of current circuits originating here."),
1874 ITEM("stream-status", events,"List of current streams."),
1875 ITEM("orconn-status", events, "A list of current OR connections."),
1876 PREFIX("address-mappings/", events, NULL),
1877 DOC("address-mappings/all", "Current address mappings."),
1878 DOC("address-mappings/cache", "Current cached DNS replies."),
1879 DOC("address-mappings/config",
1880 "Current address mappings from configuration."),
1881 DOC("address-mappings/control", "Current address mappings from controller."),
1882 PREFIX("status/", events, NULL),
1883 DOC("status/circuit-established",
1884 "Whether we think client functionality is working."),
1885 DOC("status/enough-dir-info",
1886 "Whether we have enough up-to-date directory information to build "
1887 "circuits."),
1888 DOC("status/bootstrap-phase",
1889 "The last bootstrap phase status event that Tor sent."),
1890 DOC("status/clients-seen",
1891 "Breakdown of client countries seen by a bridge."),
1892 DOC("status/version/recommended", "List of currently recommended versions."),
1893 DOC("status/version/current", "Status of the current version."),
1894 DOC("status/version/num-versioning", "Number of versioning authorities."),
1895 DOC("status/version/num-concurring",
1896 "Number of versioning authorities agreeing on the status of the "
1897 "current version"),
1898 ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
1899 ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
1900 PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
1901 PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
1902 PREFIX("dir/status/", dir,
1903 "v2 networkstatus docs as retrieved from a DirPort."),
1904 ITEM("dir/status-vote/current/consensus", dir,
1905 "v3 Networkstatus consensus as retrieved from a DirPort."),
1906 PREFIX("exit-policy/default", policies,
1907 "The default value appended to the configured exit policy."),
1908 PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
1909 { NULL, NULL, NULL, 0 }
1912 /** Allocate and return a list of recognized GETINFO options. */
1913 static char *
1914 list_getinfo_options(void)
1916 int i;
1917 char *buf=NULL;
1918 smartlist_t *lines = smartlist_create();
1919 char *ans;
1920 for (i = 0; getinfo_items[i].varname; ++i) {
1921 if (!getinfo_items[i].desc)
1922 continue;
1924 tor_asprintf(&buf, "%s%s -- %s\n",
1925 getinfo_items[i].varname,
1926 getinfo_items[i].is_prefix ? "*" : "",
1927 getinfo_items[i].desc);
1928 smartlist_add(lines, buf);
1930 smartlist_sort_strings(lines);
1932 ans = smartlist_join_strings(lines, "", 0, NULL);
1933 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1934 smartlist_free(lines);
1936 return ans;
1939 /** Lookup the 'getinfo' entry <b>question</b>, and return
1940 * the answer in <b>*answer</b> (or NULL if key not recognized).
1941 * Return 0 if success or unrecognized, or -1 if recognized but
1942 * internal error. */
1943 static int
1944 handle_getinfo_helper(control_connection_t *control_conn,
1945 const char *question, char **answer,
1946 const char **err_out)
1948 int i;
1949 *answer = NULL; /* unrecognized key by default */
1951 for (i = 0; getinfo_items[i].varname; ++i) {
1952 int match;
1953 if (getinfo_items[i].is_prefix)
1954 match = !strcmpstart(question, getinfo_items[i].varname);
1955 else
1956 match = !strcmp(question, getinfo_items[i].varname);
1957 if (match) {
1958 tor_assert(getinfo_items[i].fn);
1959 return getinfo_items[i].fn(control_conn, question, answer, err_out);
1963 return 0; /* unrecognized */
1966 /** Called when we receive a GETINFO command. Try to fetch all requested
1967 * information, and reply with information or error message. */
1968 static int
1969 handle_control_getinfo(control_connection_t *conn, uint32_t len,
1970 const char *body)
1972 smartlist_t *questions = smartlist_create();
1973 smartlist_t *answers = smartlist_create();
1974 smartlist_t *unrecognized = smartlist_create();
1975 char *msg = NULL, *ans = NULL;
1976 int i;
1977 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
1979 smartlist_split_string(questions, body, " ",
1980 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1981 SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
1982 const char *errmsg = NULL;
1983 if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
1984 if (!errmsg)
1985 errmsg = "Internal error";
1986 connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
1987 goto done;
1989 if (!ans) {
1990 smartlist_add(unrecognized, (char*)q);
1991 } else {
1992 smartlist_add(answers, tor_strdup(q));
1993 smartlist_add(answers, ans);
1995 } SMARTLIST_FOREACH_END(q);
1996 if (smartlist_len(unrecognized)) {
1997 for (i=0; i < smartlist_len(unrecognized)-1; ++i)
1998 connection_printf_to_buf(conn,
1999 "552-Unrecognized key \"%s\"\r\n",
2000 (char*)smartlist_get(unrecognized, i));
2001 connection_printf_to_buf(conn,
2002 "552 Unrecognized key \"%s\"\r\n",
2003 (char*)smartlist_get(unrecognized, i));
2004 goto done;
2007 for (i = 0; i < smartlist_len(answers); i += 2) {
2008 char *k = smartlist_get(answers, i);
2009 char *v = smartlist_get(answers, i+1);
2010 if (!strchr(v, '\n') && !strchr(v, '\r')) {
2011 connection_printf_to_buf(conn, "250-%s=", k);
2012 connection_write_str_to_buf(v, conn);
2013 connection_write_str_to_buf("\r\n", conn);
2014 } else {
2015 char *esc = NULL;
2016 size_t esc_len;
2017 esc_len = write_escaped_data(v, strlen(v), &esc);
2018 connection_printf_to_buf(conn, "250+%s=\r\n", k);
2019 connection_write_to_buf(esc, esc_len, TO_CONN(conn));
2020 tor_free(esc);
2023 connection_write_str_to_buf("250 OK\r\n", conn);
2025 done:
2026 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
2027 smartlist_free(answers);
2028 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
2029 smartlist_free(questions);
2030 smartlist_free(unrecognized);
2031 tor_free(msg);
2033 return 0;
2036 /** Given a string, convert it to a circuit purpose. */
2037 static uint8_t
2038 circuit_purpose_from_string(const char *string)
2040 if (!strcasecmpstart(string, "purpose="))
2041 string += strlen("purpose=");
2043 if (!strcasecmp(string, "general"))
2044 return CIRCUIT_PURPOSE_C_GENERAL;
2045 else if (!strcasecmp(string, "controller"))
2046 return CIRCUIT_PURPOSE_CONTROLLER;
2047 else
2048 return CIRCUIT_PURPOSE_UNKNOWN;
2051 /** Return a newly allocated smartlist containing the arguments to the command
2052 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
2053 * or if <b>max_args</b> is nonnegative and there are more than
2054 * <b>max_args</b> arguments, send a 512 error to the controller, using
2055 * <b>command</b> as the command name in the error message. */
2056 static smartlist_t *
2057 getargs_helper(const char *command, control_connection_t *conn,
2058 const char *body, int min_args, int max_args)
2060 smartlist_t *args = smartlist_create();
2061 smartlist_split_string(args, body, " ",
2062 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2063 if (smartlist_len(args) < min_args) {
2064 connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
2065 goto err;
2066 } else if (max_args >= 0 && smartlist_len(args) > max_args) {
2067 connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
2068 goto err;
2070 return args;
2071 err:
2072 SMARTLIST_FOREACH(args, char *, s, tor_free(s));
2073 smartlist_free(args);
2074 return NULL;
2077 /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
2078 * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
2079 * such element exists. */
2080 static const char *
2081 find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
2083 int i;
2084 for (i = start_at; i < smartlist_len(sl); ++i) {
2085 const char *elt = smartlist_get(sl, i);
2086 if (!strcasecmpstart(elt, prefix))
2087 return elt;
2089 return NULL;
2092 /** Helper. Return true iff s is an argument that we should treat as a
2093 * key-value pair. */
2094 static int
2095 is_keyval_pair(const char *s)
2097 /* An argument is a key-value pair if it has an =, and it isn't of the form
2098 * $fingeprint=name */
2099 return strchr(s, '=') && s[0] != '$';
2102 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
2103 * circuit, and report success or failure. */
2104 static int
2105 handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
2106 const char *body)
2108 smartlist_t *router_nicknames=NULL, *routers=NULL;
2109 origin_circuit_t *circ = NULL;
2110 int zero_circ;
2111 uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
2112 smartlist_t *args;
2113 (void) len;
2115 router_nicknames = smartlist_create();
2117 args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
2118 if (!args)
2119 goto done;
2121 zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
2123 if (zero_circ) {
2124 const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
2126 if (purp) {
2127 intended_purpose = circuit_purpose_from_string(purp);
2128 if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
2129 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
2130 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2131 smartlist_free(args);
2132 goto done;
2136 if ((smartlist_len(args) == 1) ||
2137 (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
2138 // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
2139 circ = circuit_launch_by_router(intended_purpose, NULL,
2140 CIRCLAUNCH_NEED_CAPACITY);
2141 if (!circ) {
2142 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
2143 } else {
2144 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
2145 (unsigned long)circ->global_identifier);
2147 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2148 smartlist_free(args);
2149 goto done;
2151 // "EXTENDCIRCUIT 0 router1,router2" ||
2152 // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
2155 if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
2156 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2157 (char*)smartlist_get(args, 0));
2158 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2159 smartlist_free(args);
2160 goto done;
2163 smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
2165 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2166 smartlist_free(args);
2168 routers = smartlist_create();
2169 SMARTLIST_FOREACH(router_nicknames, const char *, n,
2171 routerinfo_t *r = router_get_by_nickname(n, 1);
2172 if (!r) {
2173 connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
2174 goto done;
2176 smartlist_add(routers, r);
2178 if (!smartlist_len(routers)) {
2179 connection_write_str_to_buf("512 No router names provided\r\n", conn);
2180 goto done;
2183 if (zero_circ) {
2184 /* start a new circuit */
2185 circ = origin_circuit_init(intended_purpose, 0);
2188 /* now circ refers to something that is ready to be extended */
2189 SMARTLIST_FOREACH(routers, routerinfo_t *, r,
2191 extend_info_t *info = extend_info_from_router(r);
2192 circuit_append_new_exit(circ, info);
2193 extend_info_free(info);
2196 /* now that we've populated the cpath, start extending */
2197 if (zero_circ) {
2198 int err_reason = 0;
2199 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
2200 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2201 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
2202 goto done;
2204 } else {
2205 if (circ->_base.state == CIRCUIT_STATE_OPEN) {
2206 int err_reason = 0;
2207 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
2208 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
2209 log_info(LD_CONTROL,
2210 "send_next_onion_skin failed; circuit marked for closing.");
2211 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2212 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
2213 goto done;
2218 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
2219 (unsigned long)circ->global_identifier);
2220 if (zero_circ) /* send a 'launched' event, for completeness */
2221 control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
2222 done:
2223 SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
2224 smartlist_free(router_nicknames);
2225 smartlist_free(routers);
2226 return 0;
2229 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
2230 * circuit and it's a valid purpose, change it. */
2231 static int
2232 handle_control_setcircuitpurpose(control_connection_t *conn,
2233 uint32_t len, const char *body)
2235 origin_circuit_t *circ = NULL;
2236 uint8_t new_purpose;
2237 smartlist_t *args;
2238 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
2240 args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
2241 if (!args)
2242 goto done;
2244 if (!(circ = get_circ(smartlist_get(args,0)))) {
2245 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2246 (char*)smartlist_get(args, 0));
2247 goto done;
2251 const char *purp = find_element_starting_with(args,1,"PURPOSE=");
2252 new_purpose = circuit_purpose_from_string(purp);
2253 if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
2254 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
2255 goto done;
2259 circ->_base.purpose = new_purpose;
2260 connection_write_str_to_buf("250 OK\r\n", conn);
2262 done:
2263 if (args) {
2264 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2265 smartlist_free(args);
2267 return 0;
2270 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
2271 * stream, and report success or failure. */
2272 static int
2273 handle_control_attachstream(control_connection_t *conn, uint32_t len,
2274 const char *body)
2276 edge_connection_t *ap_conn = NULL;
2277 origin_circuit_t *circ = NULL;
2278 int zero_circ;
2279 smartlist_t *args;
2280 crypt_path_t *cpath=NULL;
2281 int hop=0, hop_line_ok=1;
2282 (void) len;
2284 args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
2285 if (!args)
2286 return 0;
2288 zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
2290 if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
2291 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2292 (char*)smartlist_get(args, 0));
2293 } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
2294 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2295 (char*)smartlist_get(args, 1));
2296 } else if (circ) {
2297 const char *hopstring = find_element_starting_with(args,2,"HOP=");
2298 if (hopstring) {
2299 hopstring += strlen("HOP=");
2300 hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
2301 &hop_line_ok, NULL);
2302 if (!hop_line_ok) { /* broken hop line */
2303 connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
2307 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2308 smartlist_free(args);
2309 if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
2310 return 0;
2312 if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT &&
2313 ap_conn->_base.state != AP_CONN_STATE_CONNECT_WAIT &&
2314 ap_conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
2315 connection_write_str_to_buf(
2316 "555 Connection is not managed by controller.\r\n",
2317 conn);
2318 return 0;
2321 /* Do we need to detach it first? */
2322 if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT) {
2323 circuit_t *tmpcirc = circuit_get_by_edge_conn(ap_conn);
2324 connection_edge_end(ap_conn, END_STREAM_REASON_TIMEOUT);
2325 /* Un-mark it as ending, since we're going to reuse it. */
2326 ap_conn->edge_has_sent_end = 0;
2327 ap_conn->end_reason = 0;
2328 if (tmpcirc)
2329 circuit_detach_stream(tmpcirc,ap_conn);
2330 ap_conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
2333 if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
2334 connection_write_str_to_buf(
2335 "551 Can't attach stream to non-open origin circuit\r\n",
2336 conn);
2337 return 0;
2339 /* Is this a single hop circuit? */
2340 if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
2341 routerinfo_t *r = NULL;
2342 char* exit_digest;
2343 if (circ->build_state &&
2344 circ->build_state->chosen_exit &&
2345 !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
2346 exit_digest = circ->build_state->chosen_exit->identity_digest;
2347 r = router_get_by_digest(exit_digest);
2349 /* Do both the client and relay allow one-hop exit circuits? */
2350 if (!r || !r->allow_single_hop_exits ||
2351 !get_options()->AllowSingleHopCircuits) {
2352 connection_write_str_to_buf(
2353 "551 Can't attach stream to this one-hop circuit.\r\n", conn);
2354 return 0;
2356 ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
2359 if (circ && hop>0) {
2360 /* find this hop in the circuit, and set cpath */
2361 cpath = circuit_get_cpath_hop(circ, hop);
2362 if (!cpath) {
2363 connection_printf_to_buf(conn,
2364 "551 Circuit doesn't have %d hops.\r\n", hop);
2365 return 0;
2368 if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
2369 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
2370 return 0;
2372 send_control_done(conn);
2373 return 0;
2376 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
2377 * descriptor, and report success or failure. */
2378 static int
2379 handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
2380 const char *body)
2382 char *desc;
2383 const char *msg=NULL;
2384 uint8_t purpose = ROUTER_PURPOSE_GENERAL;
2385 int cache = 0; /* eventually, we may switch this to 1 */
2387 char *cp = memchr(body, '\n', len);
2388 smartlist_t *args = smartlist_create();
2389 tor_assert(cp);
2390 *cp++ = '\0';
2392 smartlist_split_string(args, body, " ",
2393 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2394 SMARTLIST_FOREACH(args, char *, option,
2396 if (!strcasecmpstart(option, "purpose=")) {
2397 option += strlen("purpose=");
2398 purpose = router_purpose_from_string(option);
2399 if (purpose == ROUTER_PURPOSE_UNKNOWN) {
2400 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
2401 option);
2402 goto done;
2404 } else if (!strcasecmpstart(option, "cache=")) {
2405 option += strlen("cache=");
2406 if (!strcasecmp(option, "no"))
2407 cache = 0;
2408 else if (!strcasecmp(option, "yes"))
2409 cache = 1;
2410 else {
2411 connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
2412 option);
2413 goto done;
2415 } else { /* unrecognized argument? */
2416 connection_printf_to_buf(conn,
2417 "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
2418 goto done;
2422 read_escaped_data(cp, len-(cp-body), &desc);
2424 switch (router_load_single_router(desc, purpose, cache, &msg)) {
2425 case -1:
2426 if (!msg) msg = "Could not parse descriptor";
2427 connection_printf_to_buf(conn, "554 %s\r\n", msg);
2428 break;
2429 case 0:
2430 if (!msg) msg = "Descriptor not added";
2431 connection_printf_to_buf(conn, "251 %s\r\n",msg);
2432 break;
2433 case 1:
2434 send_control_done(conn);
2435 break;
2438 tor_free(desc);
2439 done:
2440 SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
2441 smartlist_free(args);
2442 return 0;
2445 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
2446 * address of the named AP stream, and report success or failure. */
2447 static int
2448 handle_control_redirectstream(control_connection_t *conn, uint32_t len,
2449 const char *body)
2451 edge_connection_t *ap_conn = NULL;
2452 char *new_addr = NULL;
2453 uint16_t new_port = 0;
2454 smartlist_t *args;
2455 (void) len;
2457 args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
2458 if (!args)
2459 return 0;
2461 if (!(ap_conn = get_stream(smartlist_get(args, 0)))
2462 || !ap_conn->socks_request) {
2463 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2464 (char*)smartlist_get(args, 0));
2465 } else {
2466 int ok = 1;
2467 if (smartlist_len(args) > 2) { /* they included a port too */
2468 new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
2469 10, 1, 65535, &ok, NULL);
2471 if (!ok) {
2472 connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
2473 (char*)smartlist_get(args, 2));
2474 } else {
2475 new_addr = tor_strdup(smartlist_get(args, 1));
2479 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2480 smartlist_free(args);
2481 if (!new_addr)
2482 return 0;
2484 strlcpy(ap_conn->socks_request->address, new_addr,
2485 sizeof(ap_conn->socks_request->address));
2486 if (new_port)
2487 ap_conn->socks_request->port = new_port;
2488 tor_free(new_addr);
2489 send_control_done(conn);
2490 return 0;
2493 /** Called when we get a CLOSESTREAM command; try to close the named stream
2494 * and report success or failure. */
2495 static int
2496 handle_control_closestream(control_connection_t *conn, uint32_t len,
2497 const char *body)
2499 edge_connection_t *ap_conn=NULL;
2500 uint8_t reason=0;
2501 smartlist_t *args;
2502 int ok;
2503 (void) len;
2505 args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
2506 if (!args)
2507 return 0;
2509 else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
2510 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2511 (char*)smartlist_get(args, 0));
2512 else {
2513 reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
2514 &ok, NULL);
2515 if (!ok) {
2516 connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
2517 (char*)smartlist_get(args, 1));
2518 ap_conn = NULL;
2521 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2522 smartlist_free(args);
2523 if (!ap_conn)
2524 return 0;
2526 connection_mark_unattached_ap(ap_conn, reason);
2527 send_control_done(conn);
2528 return 0;
2531 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
2532 * and report success or failure. */
2533 static int
2534 handle_control_closecircuit(control_connection_t *conn, uint32_t len,
2535 const char *body)
2537 origin_circuit_t *circ = NULL;
2538 int safe = 0;
2539 smartlist_t *args;
2540 (void) len;
2542 args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
2543 if (!args)
2544 return 0;
2546 if (!(circ=get_circ(smartlist_get(args, 0))))
2547 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2548 (char*)smartlist_get(args, 0));
2549 else {
2550 int i;
2551 for (i=1; i < smartlist_len(args); ++i) {
2552 if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
2553 safe = 1;
2554 else
2555 log_info(LD_CONTROL, "Skipping unknown option %s",
2556 (char*)smartlist_get(args,i));
2559 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2560 smartlist_free(args);
2561 if (!circ)
2562 return 0;
2564 if (!safe || !circ->p_streams) {
2565 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
2568 send_control_done(conn);
2569 return 0;
2572 /** Called when we get a RESOLVE command: start trying to resolve
2573 * the listed addresses. */
2574 static int
2575 handle_control_resolve(control_connection_t *conn, uint32_t len,
2576 const char *body)
2578 smartlist_t *args, *failed;
2579 int is_reverse = 0;
2580 (void) len; /* body is nul-terminated; it's safe to ignore the length */
2582 if (!(conn->event_mask & ((uint32_t)1L<<EVENT_ADDRMAP))) {
2583 log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
2584 "isn't listening for ADDRMAP events. It probably won't see "
2585 "the answer.");
2587 args = smartlist_create();
2588 smartlist_split_string(args, body, " ",
2589 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2591 const char *modearg = find_element_starting_with(args, 0, "mode=");
2592 if (modearg && !strcasecmp(modearg, "mode=reverse"))
2593 is_reverse = 1;
2595 failed = smartlist_create();
2596 SMARTLIST_FOREACH(args, const char *, arg, {
2597 if (!is_keyval_pair(arg)) {
2598 if (dnsserv_launch_request(arg, is_reverse)<0)
2599 smartlist_add(failed, (char*)arg);
2603 send_control_done(conn);
2604 SMARTLIST_FOREACH(failed, const char *, arg, {
2605 control_event_address_mapped(arg, arg, time(NULL),
2606 "Unable to launch resolve request");
2609 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2610 smartlist_free(args);
2611 smartlist_free(failed);
2612 return 0;
2615 /** Called when we get a PROTOCOLINFO command: send back a reply. */
2616 static int
2617 handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
2618 const char *body)
2620 const char *bad_arg = NULL;
2621 smartlist_t *args;
2622 (void)len;
2624 conn->have_sent_protocolinfo = 1;
2625 args = smartlist_create();
2626 smartlist_split_string(args, body, " ",
2627 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2628 SMARTLIST_FOREACH(args, const char *, arg, {
2629 int ok;
2630 tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
2631 if (!ok) {
2632 bad_arg = arg;
2633 break;
2636 if (bad_arg) {
2637 connection_printf_to_buf(conn, "513 No such version %s\r\n",
2638 escaped(bad_arg));
2639 /* Don't tolerate bad arguments when not authenticated. */
2640 if (!STATE_IS_OPEN(TO_CONN(conn)->state))
2641 connection_mark_for_close(TO_CONN(conn));
2642 goto done;
2643 } else {
2644 or_options_t *options = get_options();
2645 int cookies = options->CookieAuthentication;
2646 char *cfile = get_cookie_file();
2647 char *esc_cfile = esc_for_log(cfile);
2648 char *methods;
2650 int passwd = (options->HashedControlPassword != NULL ||
2651 options->HashedControlSessionPassword != NULL);
2652 smartlist_t *mlist = smartlist_create();
2653 if (cookies)
2654 smartlist_add(mlist, (char*)"COOKIE");
2655 if (passwd)
2656 smartlist_add(mlist, (char*)"HASHEDPASSWORD");
2657 if (!cookies && !passwd)
2658 smartlist_add(mlist, (char*)"NULL");
2659 methods = smartlist_join_strings(mlist, ",", 0, NULL);
2660 smartlist_free(mlist);
2663 connection_printf_to_buf(conn,
2664 "250-PROTOCOLINFO 1\r\n"
2665 "250-AUTH METHODS=%s%s%s\r\n"
2666 "250-VERSION Tor=%s\r\n"
2667 "250 OK\r\n",
2668 methods,
2669 cookies?" COOKIEFILE=":"",
2670 cookies?esc_cfile:"",
2671 escaped(VERSION));
2672 tor_free(methods);
2673 tor_free(cfile);
2674 tor_free(esc_cfile);
2676 done:
2677 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2678 smartlist_free(args);
2679 return 0;
2682 /** Called when we get a USEFEATURE command: parse the feature list, and
2683 * set up the control_connection's options properly. */
2684 static int
2685 handle_control_usefeature(control_connection_t *conn,
2686 uint32_t len,
2687 const char *body)
2689 smartlist_t *args;
2690 int bad = 0;
2691 (void) len; /* body is nul-terminated; it's safe to ignore the length */
2692 args = smartlist_create();
2693 smartlist_split_string(args, body, " ",
2694 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2695 SMARTLIST_FOREACH(args, const char *, arg, {
2696 if (!strcasecmp(arg, "VERBOSE_NAMES"))
2698 else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
2700 else {
2701 connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
2702 arg);
2703 bad = 1;
2704 break;
2708 if (!bad) {
2709 send_control_done(conn);
2712 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2713 smartlist_free(args);
2714 return 0;
2717 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
2719 connection_control_finished_flushing(control_connection_t *conn)
2721 tor_assert(conn);
2723 connection_stop_writing(TO_CONN(conn));
2724 return 0;
2727 /** Called when <b>conn</b> has gotten its socket closed. */
2729 connection_control_reached_eof(control_connection_t *conn)
2731 tor_assert(conn);
2733 log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
2734 connection_mark_for_close(TO_CONN(conn));
2735 return 0;
2738 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
2739 * stage of the protocol. */
2740 static int
2741 is_valid_initial_command(control_connection_t *conn, const char *cmd)
2743 if (conn->_base.state == CONTROL_CONN_STATE_OPEN)
2744 return 1;
2745 if (!strcasecmp(cmd, "PROTOCOLINFO"))
2746 return !conn->have_sent_protocolinfo;
2747 if (!strcasecmp(cmd, "AUTHENTICATE") ||
2748 !strcasecmp(cmd, "QUIT"))
2749 return 1;
2750 return 0;
2753 /** Do not accept any control command of more than 1MB in length. Anything
2754 * that needs to be anywhere near this long probably means that one of our
2755 * interfaces is broken. */
2756 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
2758 /** Called when data has arrived on a v1 control connection: Try to fetch
2759 * commands from conn->inbuf, and execute them.
2762 connection_control_process_inbuf(control_connection_t *conn)
2764 size_t data_len;
2765 uint32_t cmd_data_len;
2766 int cmd_len;
2767 char *args;
2769 tor_assert(conn);
2770 tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN ||
2771 conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH);
2773 if (!conn->incoming_cmd) {
2774 conn->incoming_cmd = tor_malloc(1024);
2775 conn->incoming_cmd_len = 1024;
2776 conn->incoming_cmd_cur_len = 0;
2779 if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
2780 peek_buf_has_control0_command(conn->_base.inbuf)) {
2781 /* Detect v0 commands and send a "no more v0" message. */
2782 size_t body_len;
2783 char buf[128];
2784 set_uint16(buf+2, htons(0x0000)); /* type == error */
2785 set_uint16(buf+4, htons(0x0001)); /* code == internal error */
2786 strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
2787 "and later; upgrade your controller.",
2788 sizeof(buf)-6);
2789 body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
2790 set_uint16(buf+0, htons(body_len));
2791 connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
2792 connection_mark_for_close(TO_CONN(conn));
2793 conn->_base.hold_open_until_flushed = 1;
2794 return 0;
2797 again:
2798 while (1) {
2799 size_t last_idx;
2800 int r;
2801 /* First, fetch a line. */
2802 do {
2803 data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
2804 r = fetch_from_buf_line(conn->_base.inbuf,
2805 conn->incoming_cmd+conn->incoming_cmd_cur_len,
2806 &data_len);
2807 if (r == 0)
2808 /* Line not all here yet. Wait. */
2809 return 0;
2810 else if (r == -1) {
2811 if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
2812 connection_write_str_to_buf("500 Line too long.\r\n", conn);
2813 connection_stop_reading(TO_CONN(conn));
2814 connection_mark_for_close(TO_CONN(conn));
2815 conn->_base.hold_open_until_flushed = 1;
2817 while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
2818 conn->incoming_cmd_len *= 2;
2819 conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
2820 conn->incoming_cmd_len);
2822 } while (r != 1);
2824 tor_assert(data_len);
2826 last_idx = conn->incoming_cmd_cur_len;
2827 conn->incoming_cmd_cur_len += (int)data_len;
2829 /* We have appended a line to incoming_cmd. Is the command done? */
2830 if (last_idx == 0 && *conn->incoming_cmd != '+')
2831 /* One line command, didn't start with '+'. */
2832 break;
2833 /* XXXX this code duplication is kind of dumb. */
2834 if (last_idx+3 == conn->incoming_cmd_cur_len &&
2835 !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
2836 /* Just appended ".\r\n"; we're done. Remove it. */
2837 conn->incoming_cmd[last_idx] = '\0';
2838 conn->incoming_cmd_cur_len -= 3;
2839 break;
2840 } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
2841 !memcmp(conn->incoming_cmd + last_idx, ".\n", 2)) {
2842 /* Just appended ".\n"; we're done. Remove it. */
2843 conn->incoming_cmd[last_idx] = '\0';
2844 conn->incoming_cmd_cur_len -= 2;
2845 break;
2847 /* Otherwise, read another line. */
2849 data_len = conn->incoming_cmd_cur_len;
2850 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
2851 * recognize it.
2853 cmd_len = 0;
2854 while ((size_t)cmd_len < data_len
2855 && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
2856 ++cmd_len;
2858 data_len -= cmd_len;
2859 conn->incoming_cmd[cmd_len]='\0';
2860 args = conn->incoming_cmd+cmd_len+1;
2861 while (*args == ' ' || *args == '\t') {
2862 ++args;
2863 --data_len;
2866 /* If the connection is already closing, ignore further commands */
2867 if (TO_CONN(conn)->marked_for_close) {
2868 return 0;
2871 /* Otherwise, Quit is always valid. */
2872 if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
2873 connection_write_str_to_buf("250 closing connection\r\n", conn);
2874 connection_mark_for_close(TO_CONN(conn));
2875 conn->_base.hold_open_until_flushed = 1;
2876 return 0;
2879 if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
2880 !is_valid_initial_command(conn, conn->incoming_cmd)) {
2881 connection_write_str_to_buf("514 Authentication required.\r\n", conn);
2882 connection_mark_for_close(TO_CONN(conn));
2883 return 0;
2886 if (data_len >= UINT32_MAX) {
2887 connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
2888 connection_mark_for_close(TO_CONN(conn));
2889 return 0;
2892 cmd_data_len = (uint32_t)data_len;
2893 if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
2894 if (handle_control_setconf(conn, cmd_data_len, args))
2895 return -1;
2896 } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
2897 if (handle_control_resetconf(conn, cmd_data_len, args))
2898 return -1;
2899 } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
2900 if (handle_control_getconf(conn, cmd_data_len, args))
2901 return -1;
2902 } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
2903 if (handle_control_loadconf(conn, cmd_data_len, args))
2904 return -1;
2905 } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
2906 if (handle_control_setevents(conn, cmd_data_len, args))
2907 return -1;
2908 } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
2909 if (handle_control_authenticate(conn, cmd_data_len, args))
2910 return -1;
2911 } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
2912 if (handle_control_saveconf(conn, cmd_data_len, args))
2913 return -1;
2914 } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
2915 if (handle_control_signal(conn, cmd_data_len, args))
2916 return -1;
2917 } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
2918 if (handle_control_mapaddress(conn, cmd_data_len, args))
2919 return -1;
2920 } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
2921 if (handle_control_getinfo(conn, cmd_data_len, args))
2922 return -1;
2923 } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
2924 if (handle_control_extendcircuit(conn, cmd_data_len, args))
2925 return -1;
2926 } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
2927 if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
2928 return -1;
2929 } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
2930 connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
2931 } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
2932 if (handle_control_attachstream(conn, cmd_data_len, args))
2933 return -1;
2934 } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
2935 if (handle_control_postdescriptor(conn, cmd_data_len, args))
2936 return -1;
2937 } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
2938 if (handle_control_redirectstream(conn, cmd_data_len, args))
2939 return -1;
2940 } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
2941 if (handle_control_closestream(conn, cmd_data_len, args))
2942 return -1;
2943 } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
2944 if (handle_control_closecircuit(conn, cmd_data_len, args))
2945 return -1;
2946 } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
2947 if (handle_control_usefeature(conn, cmd_data_len, args))
2948 return -1;
2949 } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
2950 if (handle_control_resolve(conn, cmd_data_len, args))
2951 return -1;
2952 } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
2953 if (handle_control_protocolinfo(conn, cmd_data_len, args))
2954 return -1;
2955 } else {
2956 connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
2957 conn->incoming_cmd);
2960 conn->incoming_cmd_cur_len = 0;
2961 goto again;
2964 /** Something has happened to circuit <b>circ</b>: tell any interested
2965 * control connections. */
2967 control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
2968 int reason_code)
2970 const char *status;
2971 char extended_buf[96];
2972 int providing_reason=0;
2973 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
2974 return 0;
2975 tor_assert(circ);
2977 switch (tp)
2979 case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
2980 case CIRC_EVENT_BUILT: status = "BUILT"; break;
2981 case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
2982 case CIRC_EVENT_FAILED: status = "FAILED"; break;
2983 case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
2984 default:
2985 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
2986 return 0;
2989 tor_snprintf(extended_buf, sizeof(extended_buf), "PURPOSE=%s",
2990 circuit_purpose_to_controller_string(circ->_base.purpose));
2992 if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
2993 const char *reason_str = circuit_end_reason_to_control_string(reason_code);
2994 char *reason = NULL;
2995 size_t n=strlen(extended_buf);
2996 providing_reason=1;
2997 if (!reason_str) {
2998 reason = tor_malloc(16);
2999 tor_snprintf(reason, 16, "UNKNOWN_%d", reason_code);
3000 reason_str = reason;
3002 if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
3003 tor_snprintf(extended_buf+n, sizeof(extended_buf)-n,
3004 " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
3005 } else {
3006 tor_snprintf(extended_buf+n, sizeof(extended_buf)-n,
3007 " REASON=%s", reason_str);
3009 tor_free(reason);
3013 char *vpath = circuit_list_path_for_controller(circ);
3014 const char *sp = strlen(vpath) ? " " : "";
3015 send_control_event(EVENT_CIRCUIT_STATUS, ALL_FORMATS,
3016 "650 CIRC %lu %s%s%s %s\r\n",
3017 (unsigned long)circ->global_identifier,
3018 status, sp, vpath, extended_buf);
3019 tor_free(vpath);
3022 return 0;
3025 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
3026 * <b>buf</b>, determine the address:port combination requested on
3027 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
3028 * failure. */
3029 static int
3030 write_stream_target_to_buf(edge_connection_t *conn, char *buf, size_t len)
3032 char buf2[256];
3033 if (conn->chosen_exit_name)
3034 if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
3035 return -1;
3036 if (!conn->socks_request)
3037 return -1;
3038 if (tor_snprintf(buf, len, "%s%s%s:%d",
3039 conn->socks_request->address,
3040 conn->chosen_exit_name ? buf2 : "",
3041 !conn->chosen_exit_name &&
3042 connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
3043 conn->socks_request->port)<0)
3044 return -1;
3045 return 0;
3048 /** Something has happened to the stream associated with AP connection
3049 * <b>conn</b>: tell any interested control connections. */
3051 control_event_stream_status(edge_connection_t *conn, stream_status_event_t tp,
3052 int reason_code)
3054 char reason_buf[64];
3055 char addrport_buf[64];
3056 const char *status;
3057 circuit_t *circ;
3058 origin_circuit_t *origin_circ = NULL;
3059 char buf[256];
3060 const char *purpose = "";
3061 tor_assert(conn->socks_request);
3063 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
3064 return 0;
3066 if (tp == STREAM_EVENT_CLOSED &&
3067 (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
3068 return 0;
3070 write_stream_target_to_buf(conn, buf, sizeof(buf));
3072 reason_buf[0] = '\0';
3073 switch (tp)
3075 case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
3076 case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
3077 case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
3078 case STREAM_EVENT_FAILED: status = "FAILED"; break;
3079 case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
3080 case STREAM_EVENT_NEW: status = "NEW"; break;
3081 case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
3082 case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
3083 case STREAM_EVENT_REMAP: status = "REMAP"; break;
3084 default:
3085 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3086 return 0;
3088 if (reason_code && (tp == STREAM_EVENT_FAILED ||
3089 tp == STREAM_EVENT_CLOSED ||
3090 tp == STREAM_EVENT_FAILED_RETRIABLE)) {
3091 const char *reason_str = stream_end_reason_to_control_string(reason_code);
3092 char *r = NULL;
3093 if (!reason_str) {
3094 r = tor_malloc(16);
3095 tor_snprintf(r, 16, " UNKNOWN_%d", reason_code);
3096 reason_str = r;
3098 if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
3099 tor_snprintf(reason_buf, sizeof(reason_buf),
3100 " REASON=END REMOTE_REASON=%s", reason_str);
3101 else
3102 tor_snprintf(reason_buf, sizeof(reason_buf),
3103 " REASON=%s", reason_str);
3104 tor_free(r);
3105 } else if (reason_code && tp == STREAM_EVENT_REMAP) {
3106 switch (reason_code) {
3107 case REMAP_STREAM_SOURCE_CACHE:
3108 strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
3109 break;
3110 case REMAP_STREAM_SOURCE_EXIT:
3111 strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
3112 break;
3113 default:
3114 tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
3115 reason_code);
3116 /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
3117 break;
3121 if (tp == STREAM_EVENT_NEW) {
3122 tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
3123 TO_CONN(conn)->address, TO_CONN(conn)->port );
3124 } else {
3125 addrport_buf[0] = '\0';
3128 if (tp == STREAM_EVENT_NEW_RESOLVE) {
3129 purpose = " PURPOSE=DNS_REQUEST";
3130 } else if (tp == STREAM_EVENT_NEW) {
3131 if (conn->is_dns_request ||
3132 (conn->socks_request &&
3133 SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)))
3134 purpose = " PURPOSE=DNS_REQUEST";
3135 else if (conn->use_begindir) {
3136 connection_t *linked = TO_CONN(conn)->linked_conn;
3137 int linked_dir_purpose = -1;
3138 if (linked && linked->type == CONN_TYPE_DIR)
3139 linked_dir_purpose = linked->purpose;
3140 if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
3141 purpose = " PURPOSE=DIR_UPLOAD";
3142 else
3143 purpose = " PURPOSE=DIR_FETCH";
3144 } else
3145 purpose = " PURPOSE=USER";
3148 circ = circuit_get_by_edge_conn(conn);
3149 if (circ && CIRCUIT_IS_ORIGIN(circ))
3150 origin_circ = TO_ORIGIN_CIRCUIT(circ);
3151 send_control_event(EVENT_STREAM_STATUS, ALL_FORMATS,
3152 "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
3153 U64_PRINTF_ARG(conn->_base.global_identifier), status,
3154 origin_circ?
3155 (unsigned long)origin_circ->global_identifier : 0ul,
3156 buf, reason_buf, addrport_buf, purpose);
3158 /* XXX need to specify its intended exit, etc? */
3160 return 0;
3163 /** Figure out the best name for the target router of an OR connection
3164 * <b>conn</b>, and write it into the <b>len</b>-character buffer
3165 * <b>name</b>. */
3166 static void
3167 orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
3169 routerinfo_t *ri = router_get_by_digest(conn->identity_digest);
3170 if (ri) {
3171 tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
3172 router_get_verbose_nickname(name, ri);
3173 } else if (! tor_digest_is_zero(conn->identity_digest)) {
3174 name[0] = '$';
3175 base16_encode(name+1, len-1, conn->identity_digest,
3176 DIGEST_LEN);
3177 } else {
3178 tor_snprintf(name, len, "%s:%d",
3179 conn->_base.address, conn->_base.port);
3183 /** Called when the status of an OR connection <b>conn</b> changes: tell any
3184 * interested control connections. <b>tp</b> is the new status for the
3185 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
3186 * may be the reason why.
3189 control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
3190 int reason)
3192 int ncircs = 0;
3193 const char *status;
3194 char name[128];
3195 char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
3197 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
3198 return 0;
3200 switch (tp)
3202 case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
3203 case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
3204 case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
3205 case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
3206 case OR_CONN_EVENT_NEW: status = "NEW"; break;
3207 default:
3208 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3209 return 0;
3211 ncircs = circuit_count_pending_on_or_conn(conn);
3212 ncircs += conn->n_circuits;
3213 if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
3214 tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
3215 reason ? " " : "", ncircs);
3218 orconn_target_get_name(name, sizeof(name), conn);
3219 send_control_event(EVENT_OR_CONN_STATUS, ALL_FORMATS,
3220 "650 ORCONN %s %s %s%s%s\r\n",
3221 name, status,
3222 reason ? "REASON=" : "",
3223 orconn_end_reason_to_control_string(reason),
3224 ncircs_buf);
3226 return 0;
3230 * Print out STREAM_BW event for a single conn
3233 control_event_stream_bandwidth(edge_connection_t *edge_conn)
3235 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
3236 if (!edge_conn->n_read && !edge_conn->n_written)
3237 return 0;
3239 send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
3240 "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
3241 U64_PRINTF_ARG(edge_conn->_base.global_identifier),
3242 (unsigned long)edge_conn->n_read,
3243 (unsigned long)edge_conn->n_written);
3245 edge_conn->n_written = edge_conn->n_read = 0;
3248 return 0;
3251 /** A second or more has elapsed: tell any interested control
3252 * connections how much bandwidth streams have used. */
3254 control_event_stream_bandwidth_used(void)
3256 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
3257 smartlist_t *conns = get_connection_array();
3258 edge_connection_t *edge_conn;
3260 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
3262 if (conn->type != CONN_TYPE_AP)
3263 continue;
3264 edge_conn = TO_EDGE_CONN(conn);
3265 if (!edge_conn->n_read && !edge_conn->n_written)
3266 continue;
3268 send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
3269 "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
3270 U64_PRINTF_ARG(edge_conn->_base.global_identifier),
3271 (unsigned long)edge_conn->n_read,
3272 (unsigned long)edge_conn->n_written);
3274 edge_conn->n_written = edge_conn->n_read = 0;
3276 SMARTLIST_FOREACH_END(conn);
3279 return 0;
3282 /** A second or more has elapsed: tell any interested control
3283 * connections how much bandwidth we used. */
3285 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
3287 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
3288 send_control_event(EVENT_BANDWIDTH_USED, ALL_FORMATS,
3289 "650 BW %lu %lu\r\n",
3290 (unsigned long)n_read,
3291 (unsigned long)n_written);
3294 return 0;
3297 /** Called when we are sending a log message to the controllers: suspend
3298 * sending further log messages to the controllers until we're done. Used by
3299 * CONN_LOG_PROTECT. */
3300 void
3301 disable_control_logging(void)
3303 ++disable_log_messages;
3306 /** We're done sending a log message to the controllers: re-enable controller
3307 * logging. Used by CONN_LOG_PROTECT. */
3308 void
3309 enable_control_logging(void)
3311 if (--disable_log_messages < 0)
3312 tor_assert(0);
3315 /** We got a log message: tell any interested control connections. */
3316 void
3317 control_event_logmsg(int severity, uint32_t domain, const char *msg)
3319 int event;
3321 /* Don't even think of trying to add stuff to a buffer from a cpuworker
3322 * thread. */
3323 if (! in_main_thread())
3324 return;
3326 if (disable_log_messages)
3327 return;
3329 if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
3330 severity <= LOG_NOTICE) {
3331 char *esc = esc_for_log(msg);
3332 ++disable_log_messages;
3333 control_event_general_status(severity, "BUG REASON=\"%s\"", esc);
3334 --disable_log_messages;
3335 tor_free(esc);
3338 event = log_severity_to_event(severity);
3339 if (event >= 0 && EVENT_IS_INTERESTING(event)) {
3340 char *b = NULL;
3341 const char *s;
3342 if (strchr(msg, '\n')) {
3343 char *cp;
3344 b = tor_strdup(msg);
3345 for (cp = b; *cp; ++cp)
3346 if (*cp == '\r' || *cp == '\n')
3347 *cp = ' ';
3349 switch (severity) {
3350 case LOG_DEBUG: s = "DEBUG"; break;
3351 case LOG_INFO: s = "INFO"; break;
3352 case LOG_NOTICE: s = "NOTICE"; break;
3353 case LOG_WARN: s = "WARN"; break;
3354 case LOG_ERR: s = "ERR"; break;
3355 default: s = "UnknownLogSeverity"; break;
3357 ++disable_log_messages;
3358 send_control_event(event, ALL_FORMATS, "650 %s %s\r\n", s, b?b:msg);
3359 --disable_log_messages;
3360 tor_free(b);
3364 /** Called whenever we receive new router descriptors: tell any
3365 * interested control connections. <b>routers</b> is a list of
3366 * routerinfo_t's.
3369 control_event_descriptors_changed(smartlist_t *routers)
3371 char *msg;
3373 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
3374 return 0;
3377 smartlist_t *names = smartlist_create();
3378 char *ids;
3379 size_t names_len;
3380 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
3381 char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
3382 router_get_verbose_nickname(b, ri);
3383 smartlist_add(names, b);
3385 ids = smartlist_join_strings(names, " ", 0, &names_len);
3386 names_len = strlen(ids)+32;
3387 msg = tor_malloc(names_len);
3388 tor_snprintf(msg, names_len, "650 NEWDESC %s\r\n", ids);
3389 send_control_event_string(EVENT_NEW_DESC, ALL_FORMATS, msg);
3390 tor_free(ids);
3391 tor_free(msg);
3392 SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
3393 smartlist_free(names);
3395 return 0;
3398 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
3399 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
3400 * <b>error</b> is non-NULL, it is an error code describing the failure
3401 * mode of the mapping.
3404 control_event_address_mapped(const char *from, const char *to, time_t expires,
3405 const char *error)
3407 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
3408 return 0;
3410 if (expires < 3 || expires == TIME_MAX)
3411 send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
3412 "650 ADDRMAP %s %s NEVER %s\r\n", from, to,
3413 error?error:"");
3414 else {
3415 char buf[ISO_TIME_LEN+1];
3416 char buf2[ISO_TIME_LEN+1];
3417 format_local_iso_time(buf,expires);
3418 format_iso_time(buf2,expires);
3419 send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
3420 "650 ADDRMAP %s %s \"%s\""
3421 " %s%sEXPIRES=\"%s\"\r\n",
3422 from, to, buf,
3423 error?error:"", error?" ":"",
3424 buf2);
3427 return 0;
3430 /** The authoritative dirserver has received a new descriptor that
3431 * has passed basic syntax checks and is properly self-signed.
3433 * Notify any interested party of the new descriptor and what has
3434 * been done with it, and also optionally give an explanation/reason. */
3436 control_event_or_authdir_new_descriptor(const char *action,
3437 const char *desc, size_t desclen,
3438 const char *msg)
3440 char firstline[1024];
3441 char *buf;
3442 size_t totallen;
3443 char *esc = NULL;
3444 size_t esclen;
3446 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
3447 return 0;
3449 tor_snprintf(firstline, sizeof(firstline),
3450 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
3451 action,
3452 msg ? msg : "");
3454 /* Escape the server descriptor properly */
3455 esclen = write_escaped_data(desc, desclen, &esc);
3457 totallen = strlen(firstline) + esclen + 1;
3458 buf = tor_malloc(totallen);
3459 strlcpy(buf, firstline, totallen);
3460 strlcpy(buf+strlen(firstline), esc, totallen);
3461 send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
3462 buf);
3463 send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
3464 "650 OK\r\n");
3465 tor_free(esc);
3466 tor_free(buf);
3468 return 0;
3471 /** Helper function for NS-style events. Constructs and sends an event
3472 * of type <b>event</b> with string <b>event_string</b> out of the set of
3473 * networkstatuses <b>statuses</b>. Currently it is used for NS events
3474 * and NEWCONSENSUS events. */
3475 static int
3476 control_event_networkstatus_changed_helper(smartlist_t *statuses,
3477 uint16_t event,
3478 const char *event_string)
3480 smartlist_t *strs;
3481 char *s, *esc = NULL;
3482 if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
3483 return 0;
3485 strs = smartlist_create();
3486 smartlist_add(strs, tor_strdup("650+"));
3487 smartlist_add(strs, tor_strdup(event_string));
3488 smartlist_add(strs, tor_strdup("\r\n"));
3489 SMARTLIST_FOREACH(statuses, routerstatus_t *, rs,
3491 s = networkstatus_getinfo_helper_single(rs);
3492 if (!s) continue;
3493 smartlist_add(strs, s);
3496 s = smartlist_join_strings(strs, "", 0, NULL);
3497 write_escaped_data(s, strlen(s), &esc);
3498 SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
3499 smartlist_free(strs);
3500 tor_free(s);
3501 send_control_event_string(event, ALL_FORMATS, esc);
3502 send_control_event_string(event, ALL_FORMATS,
3503 "650 OK\r\n");
3505 tor_free(esc);
3506 return 0;
3509 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
3510 * an NS event to any controller that cares. */
3512 control_event_networkstatus_changed(smartlist_t *statuses)
3514 return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
3517 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
3518 * event consisting of an NS-style line for each relay in the consensus. */
3520 control_event_newconsensus(const networkstatus_t *consensus)
3522 if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
3523 return 0;
3524 return control_event_networkstatus_changed_helper(
3525 consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
3528 /** Called when we compute a new circuitbuildtimeout */
3530 control_event_buildtimeout_set(const circuit_build_times_t *cbt,
3531 buildtimeout_set_event_t type)
3533 const char *type_string = NULL;
3534 double qnt = circuit_build_times_quantile_cutoff();
3536 if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
3537 return 0;
3539 switch (type) {
3540 case BUILDTIMEOUT_SET_EVENT_COMPUTED:
3541 type_string = "COMPUTED";
3542 break;
3543 case BUILDTIMEOUT_SET_EVENT_RESET:
3544 type_string = "RESET";
3545 qnt = 1.0;
3546 break;
3547 case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
3548 type_string = "SUSPENDED";
3549 qnt = 1.0;
3550 break;
3551 case BUILDTIMEOUT_SET_EVENT_DISCARD:
3552 type_string = "DISCARD";
3553 qnt = 1.0;
3554 break;
3555 case BUILDTIMEOUT_SET_EVENT_RESUME:
3556 type_string = "RESUME";
3557 break;
3558 default:
3559 type_string = "UNKNOWN";
3560 break;
3563 send_control_event(EVENT_BUILDTIMEOUT_SET, ALL_FORMATS,
3564 "650 BUILDTIMEOUT_SET %s TOTAL_TIMES=%lu "
3565 "TIMEOUT_MS=%lu XM=%lu ALPHA=%lf CUTOFF_QUANTILE=%lf "
3566 "TIMEOUT_RATE=%lf CLOSE_MS=%lu CLOSE_RATE=%lf\r\n",
3567 type_string, (unsigned long)cbt->total_build_times,
3568 (unsigned long)cbt->timeout_ms,
3569 (unsigned long)cbt->Xm, cbt->alpha, qnt,
3570 circuit_build_times_timeout_rate(cbt),
3571 (unsigned long)cbt->close_ms,
3572 circuit_build_times_close_rate(cbt));
3574 return 0;
3577 /** Called when a single local_routerstatus_t has changed: Sends an NS event
3578 * to any controller that cares. */
3580 control_event_networkstatus_changed_single(routerstatus_t *rs)
3582 smartlist_t *statuses;
3583 int r;
3585 if (!EVENT_IS_INTERESTING(EVENT_NS))
3586 return 0;
3588 statuses = smartlist_create();
3589 smartlist_add(statuses, rs);
3590 r = control_event_networkstatus_changed(statuses);
3591 smartlist_free(statuses);
3592 return r;
3595 /** Our own router descriptor has changed; tell any controllers that care.
3598 control_event_my_descriptor_changed(void)
3600 send_control_event(EVENT_DESCCHANGED, ALL_FORMATS, "650 DESCCHANGED\r\n");
3601 return 0;
3604 /** Helper: sends a status event where <b>type</b> is one of
3605 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
3606 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
3607 * string corresponding to <b>args</b>. */
3608 static int
3609 control_event_status(int type, int severity, const char *format, va_list args)
3611 char format_buf[160];
3612 const char *status, *sev;
3614 switch (type) {
3615 case EVENT_STATUS_GENERAL:
3616 status = "STATUS_GENERAL";
3617 break;
3618 case EVENT_STATUS_CLIENT:
3619 status = "STATUS_CLIENT";
3620 break;
3621 case EVENT_STATUS_SERVER:
3622 status = "STATUS_SERVER";
3623 break;
3624 default:
3625 log_warn(LD_BUG, "Unrecognized status type %d", type);
3626 return -1;
3628 switch (severity) {
3629 case LOG_NOTICE:
3630 sev = "NOTICE";
3631 break;
3632 case LOG_WARN:
3633 sev = "WARN";
3634 break;
3635 case LOG_ERR:
3636 sev = "ERR";
3637 break;
3638 default:
3639 log_warn(LD_BUG, "Unrecognized status severity %d", severity);
3640 return -1;
3642 if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s %s\r\n",
3643 status, sev, format)<0) {
3644 log_warn(LD_BUG, "Format string too long.");
3645 return -1;
3648 send_control_event_impl(type, ALL_FORMATS, format_buf, args);
3649 return 0;
3652 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
3653 * by formatting the arguments using the printf-style <b>format</b>. */
3655 control_event_general_status(int severity, const char *format, ...)
3657 va_list ap;
3658 int r;
3659 if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
3660 return 0;
3662 va_start(ap, format);
3663 r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
3664 va_end(ap);
3665 return r;
3668 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
3669 * by formatting the arguments using the printf-style <b>format</b>. */
3671 control_event_client_status(int severity, const char *format, ...)
3673 va_list ap;
3674 int r;
3675 if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
3676 return 0;
3678 va_start(ap, format);
3679 r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
3680 va_end(ap);
3681 return r;
3684 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
3685 * by formatting the arguments using the printf-style <b>format</b>. */
3687 control_event_server_status(int severity, const char *format, ...)
3689 va_list ap;
3690 int r;
3691 if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
3692 return 0;
3694 va_start(ap, format);
3695 r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
3696 va_end(ap);
3697 return r;
3700 /** Called when the status of an entry guard with the given <b>nickname</b>
3701 * and identity <b>digest</b> has changed to <b>status</b>: tells any
3702 * controllers that care. */
3704 control_event_guard(const char *nickname, const char *digest,
3705 const char *status)
3707 char hbuf[HEX_DIGEST_LEN+1];
3708 base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
3709 if (!EVENT_IS_INTERESTING(EVENT_GUARD))
3710 return 0;
3713 char buf[MAX_VERBOSE_NICKNAME_LEN+1];
3714 routerinfo_t *ri = router_get_by_digest(digest);
3715 if (ri) {
3716 router_get_verbose_nickname(buf, ri);
3717 } else {
3718 tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
3720 send_control_event(EVENT_GUARD, ALL_FORMATS,
3721 "650 GUARD ENTRY %s %s\r\n", buf, status);
3723 return 0;
3726 /** Helper: Return a newly allocated string containing a path to the
3727 * file where we store our authentication cookie. */
3728 static char *
3729 get_cookie_file(void)
3731 or_options_t *options = get_options();
3732 if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
3733 return tor_strdup(options->CookieAuthFile);
3734 } else {
3735 return get_datadir_fname("control_auth_cookie");
3739 /** Choose a random authentication cookie and write it to disk.
3740 * Anybody who can read the cookie from disk will be considered
3741 * authorized to use the control connection. Return -1 if we can't
3742 * write the file, or 0 on success. */
3744 init_cookie_authentication(int enabled)
3746 char *fname;
3747 if (!enabled) {
3748 authentication_cookie_is_set = 0;
3749 return 0;
3752 /* We don't want to generate a new cookie every time we call
3753 * options_act(). One should be enough. */
3754 if (authentication_cookie_is_set)
3755 return 0; /* all set */
3757 fname = get_cookie_file();
3758 crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
3759 authentication_cookie_is_set = 1;
3760 if (write_bytes_to_file(fname, authentication_cookie,
3761 AUTHENTICATION_COOKIE_LEN, 1)) {
3762 log_warn(LD_FS,"Error writing authentication cookie to %s.",
3763 escaped(fname));
3764 tor_free(fname);
3765 return -1;
3767 #ifndef MS_WINDOWS
3768 if (get_options()->CookieAuthFileGroupReadable) {
3769 if (chmod(fname, 0640)) {
3770 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
3773 #endif
3775 tor_free(fname);
3776 return 0;
3779 /** Convert the name of a bootstrapping phase <b>s</b> into strings
3780 * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
3781 static int
3782 bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
3783 const char **summary)
3785 switch (s) {
3786 case BOOTSTRAP_STATUS_UNDEF:
3787 *tag = "undef";
3788 *summary = "Undefined";
3789 break;
3790 case BOOTSTRAP_STATUS_STARTING:
3791 *tag = "starting";
3792 *summary = "Starting";
3793 break;
3794 case BOOTSTRAP_STATUS_CONN_DIR:
3795 *tag = "conn_dir";
3796 *summary = "Connecting to directory server";
3797 break;
3798 case BOOTSTRAP_STATUS_HANDSHAKE:
3799 *tag = "status_handshake";
3800 *summary = "Finishing handshake";
3801 break;
3802 case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
3803 *tag = "handshake_dir";
3804 *summary = "Finishing handshake with directory server";
3805 break;
3806 case BOOTSTRAP_STATUS_ONEHOP_CREATE:
3807 *tag = "onehop_create";
3808 *summary = "Establishing an encrypted directory connection";
3809 break;
3810 case BOOTSTRAP_STATUS_REQUESTING_STATUS:
3811 *tag = "requesting_status";
3812 *summary = "Asking for networkstatus consensus";
3813 break;
3814 case BOOTSTRAP_STATUS_LOADING_STATUS:
3815 *tag = "loading_status";
3816 *summary = "Loading networkstatus consensus";
3817 break;
3818 case BOOTSTRAP_STATUS_LOADING_KEYS:
3819 *tag = "loading_keys";
3820 *summary = "Loading authority key certs";
3821 break;
3822 case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
3823 *tag = "requesting_descriptors";
3824 *summary = "Asking for relay descriptors";
3825 break;
3826 case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
3827 *tag = "loading_descriptors";
3828 *summary = "Loading relay descriptors";
3829 break;
3830 case BOOTSTRAP_STATUS_CONN_OR:
3831 *tag = "conn_or";
3832 *summary = "Connecting to the Tor network";
3833 break;
3834 case BOOTSTRAP_STATUS_HANDSHAKE_OR:
3835 *tag = "handshake_or";
3836 *summary = "Finishing handshake with first hop";
3837 break;
3838 case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
3839 *tag = "circuit_create";
3840 *summary = "Establishing a Tor circuit";
3841 break;
3842 case BOOTSTRAP_STATUS_DONE:
3843 *tag = "done";
3844 *summary = "Done";
3845 break;
3846 default:
3847 // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
3848 *tag = *summary = "unknown";
3849 return -1;
3851 return 0;
3854 /** What percentage through the bootstrap process are we? We remember
3855 * this so we can avoid sending redundant bootstrap status events, and
3856 * so we can guess context for the bootstrap messages which are
3857 * ambiguous. It starts at 'undef', but gets set to 'starting' while
3858 * Tor initializes. */
3859 static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
3861 /** How many problems have we had getting to the next bootstrapping phase?
3862 * These include failure to establish a connection to a Tor relay,
3863 * failures to finish the TLS handshake, failures to validate the
3864 * consensus document, etc. */
3865 static int bootstrap_problems = 0;
3867 /* We only tell the controller once we've hit a threshold of problems
3868 * for the current phase. */
3869 #define BOOTSTRAP_PROBLEM_THRESHOLD 10
3871 /** Called when Tor has made progress at bootstrapping its directory
3872 * information and initial circuits.
3874 * <b>status</b> is the new status, that is, what task we will be doing
3875 * next. <b>percent</b> is zero if we just started this task, else it
3876 * represents progress on the task. */
3877 void
3878 control_event_bootstrap(bootstrap_status_t status, int progress)
3880 const char *tag, *summary;
3881 char buf[BOOTSTRAP_MSG_LEN];
3883 if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
3884 return; /* already bootstrapped; nothing to be done here. */
3886 /* special case for handshaking status, since our TLS handshaking code
3887 * can't distinguish what the connection is going to be for. */
3888 if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
3889 if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
3890 status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
3891 } else {
3892 status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
3896 if (status > bootstrap_percent ||
3897 (progress && progress > bootstrap_percent)) {
3898 bootstrap_status_to_string(status, &tag, &summary);
3899 log(status ? LOG_NOTICE : LOG_INFO, LD_CONTROL,
3900 "Bootstrapped %d%%: %s.", progress ? progress : status, summary);
3901 tor_snprintf(buf, sizeof(buf),
3902 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
3903 progress ? progress : status, tag, summary);
3904 tor_snprintf(last_sent_bootstrap_message,
3905 sizeof(last_sent_bootstrap_message),
3906 "NOTICE %s", buf);
3907 control_event_client_status(LOG_NOTICE, "%s", buf);
3908 if (status > bootstrap_percent) {
3909 bootstrap_percent = status; /* new milestone reached */
3911 if (progress > bootstrap_percent) {
3912 /* incremental progress within a milestone */
3913 bootstrap_percent = progress;
3914 bootstrap_problems = 0; /* Progress! Reset our problem counter. */
3919 /** Called when Tor has failed to make bootstrapping progress in a way
3920 * that indicates a problem. <b>warn</b> gives a hint as to why, and
3921 * <b>reason</b> provides an "or_conn_end_reason" tag.
3923 void
3924 control_event_bootstrap_problem(const char *warn, int reason)
3926 int status = bootstrap_percent;
3927 const char *tag, *summary;
3928 char buf[BOOTSTRAP_MSG_LEN];
3929 const char *recommendation = "ignore";
3931 if (bootstrap_percent == 100)
3932 return; /* already bootstrapped; nothing to be done here. */
3934 bootstrap_problems++;
3936 if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
3937 recommendation = "warn";
3939 if (reason == END_OR_CONN_REASON_NO_ROUTE)
3940 recommendation = "warn";
3942 if (get_options()->UseBridges &&
3943 !any_bridge_descriptors_known() &&
3944 !any_pending_bridge_descriptor_fetches())
3945 recommendation = "warn";
3947 while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
3948 status--; /* find a recognized status string based on current progress */
3949 status = bootstrap_percent; /* set status back to the actual number */
3951 log_fn(!strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO,
3952 LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
3953 "count %d; recommendation %s)",
3954 status, summary, warn,
3955 orconn_end_reason_to_control_string(reason),
3956 bootstrap_problems, recommendation);
3957 tor_snprintf(buf, sizeof(buf),
3958 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
3959 "COUNT=%d RECOMMENDATION=%s",
3960 bootstrap_percent, tag, summary, warn,
3961 orconn_end_reason_to_control_string(reason), bootstrap_problems,
3962 recommendation);
3963 tor_snprintf(last_sent_bootstrap_message,
3964 sizeof(last_sent_bootstrap_message),
3965 "WARN %s", buf);
3966 control_event_client_status(LOG_WARN, "%s", buf);
3969 /** We just generated a new summary of which countries we've seen clients
3970 * from recently. Send a copy to the controller in case it wants to
3971 * display it for the user. */
3972 void
3973 control_event_clients_seen(const char *controller_str)
3975 send_control_event(EVENT_CLIENTS_SEEN, 0,
3976 "650 CLIENTS_SEEN %s\r\n", controller_str);