Use a 64-bit type to hold sockets on win64.
[tor.git] / src / or / control.c
bloba595b2a638b73cb9fad09d64e519ef4ed0305a7d
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2011, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file control.c
7 * \brief Implementation for Tor's control-socket interface.
8 * See doc/spec/control-spec.txt for full details on protocol.
9 **/
11 #define CONTROL_PRIVATE
13 #include "or.h"
14 #include "buffers.h"
15 #include "circuitbuild.h"
16 #include "circuitlist.h"
17 #include "circuituse.h"
18 #include "config.h"
19 #include "connection.h"
20 #include "connection_edge.h"
21 #include "control.h"
22 #include "directory.h"
23 #include "dirserv.h"
24 #include "dnsserv.h"
25 #include "geoip.h"
26 #include "hibernate.h"
27 #include "main.h"
28 #include "networkstatus.h"
29 #include "policies.h"
30 #include "reasons.h"
31 #include "router.h"
32 #include "routerlist.h"
33 #include "routerparse.h"
35 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
36 * finished authentication and is accepting commands. */
37 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
39 /* Recognized asynchronous event types. It's okay to expand this list
40 * because it is used both as a list of v0 event types, and as indices
41 * into the bitfield to determine which controllers want which events.
43 #define _EVENT_MIN 0x0001
44 #define EVENT_CIRCUIT_STATUS 0x0001
45 #define EVENT_STREAM_STATUS 0x0002
46 #define EVENT_OR_CONN_STATUS 0x0003
47 #define EVENT_BANDWIDTH_USED 0x0004
48 #define EVENT_LOG_OBSOLETE 0x0005 /* Can reclaim this. */
49 #define EVENT_NEW_DESC 0x0006
50 #define EVENT_DEBUG_MSG 0x0007
51 #define EVENT_INFO_MSG 0x0008
52 #define EVENT_NOTICE_MSG 0x0009
53 #define EVENT_WARN_MSG 0x000A
54 #define EVENT_ERR_MSG 0x000B
55 #define EVENT_ADDRMAP 0x000C
56 // #define EVENT_AUTHDIR_NEWDESCS 0x000D
57 #define EVENT_DESCCHANGED 0x000E
58 // #define EVENT_NS 0x000F
59 #define EVENT_STATUS_CLIENT 0x0010
60 #define EVENT_STATUS_SERVER 0x0011
61 #define EVENT_STATUS_GENERAL 0x0012
62 #define EVENT_GUARD 0x0013
63 #define EVENT_STREAM_BANDWIDTH_USED 0x0014
64 #define EVENT_CLIENTS_SEEN 0x0015
65 #define EVENT_NEWCONSENSUS 0x0016
66 #define EVENT_BUILDTIMEOUT_SET 0x0017
67 #define _EVENT_MAX 0x0017
68 /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
70 /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
71 * connection is interested in events of type <b>e</b>. We use this
72 * so that we can decide to skip generating event messages that nobody
73 * has interest in without having to walk over the global connection
74 * list to find out.
75 **/
76 typedef uint32_t event_mask_t;
78 /** An event mask of all the events that any controller is interested in
79 * receiving. */
80 static event_mask_t global_event_mask = 0;
82 /** True iff we have disabled log messages from being sent to the controller */
83 static int disable_log_messages = 0;
85 /** Macro: true if any control connection is interested in events of type
86 * <b>e</b>. */
87 #define EVENT_IS_INTERESTING(e) \
88 (global_event_mask & (1<<(e)))
90 /** If we're using cookie-type authentication, how long should our cookies be?
92 #define AUTHENTICATION_COOKIE_LEN 32
94 /** If true, we've set authentication_cookie to a secret code and
95 * stored it to disk. */
96 static int authentication_cookie_is_set = 0;
97 /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
98 * and which we're using to authenticate controllers. (If the controller can
99 * read it off disk, it has permission to connect. */
100 static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
102 /** A sufficiently large size to record the last bootstrap phase string. */
103 #define BOOTSTRAP_MSG_LEN 1024
105 /** What was the last bootstrap phase message we sent? We keep track
106 * of this so we can respond to getinfo status/bootstrap-phase queries. */
107 static char last_sent_bootstrap_message[BOOTSTRAP_MSG_LEN];
109 /** Flag for event_format_t. Indicates that we should use the one standard
110 format.
112 #define ALL_FORMATS 1
114 /** Bit field of flags to select how to format a controller event. Recognized
115 * flag is ALL_FORMATS. */
116 typedef int event_format_t;
118 static void connection_printf_to_buf(control_connection_t *conn,
119 const char *format, ...)
120 CHECK_PRINTF(2,3);
121 static void send_control_done(control_connection_t *conn);
122 static void send_control_event(uint16_t event, event_format_t which,
123 const char *format, ...)
124 CHECK_PRINTF(3,4);
125 static int handle_control_setconf(control_connection_t *conn, uint32_t len,
126 char *body);
127 static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
128 char *body);
129 static int handle_control_getconf(control_connection_t *conn, uint32_t len,
130 const char *body);
131 static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
132 const char *body);
133 static int handle_control_setevents(control_connection_t *conn, uint32_t len,
134 const char *body);
135 static int handle_control_authenticate(control_connection_t *conn,
136 uint32_t len,
137 const char *body);
138 static int handle_control_signal(control_connection_t *conn, uint32_t len,
139 const char *body);
140 static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
141 const char *body);
142 static char *list_getinfo_options(void);
143 static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
144 const char *body);
145 static int handle_control_extendcircuit(control_connection_t *conn,
146 uint32_t len,
147 const char *body);
148 static int handle_control_setcircuitpurpose(control_connection_t *conn,
149 uint32_t len, const char *body);
150 static int handle_control_attachstream(control_connection_t *conn,
151 uint32_t len,
152 const char *body);
153 static int handle_control_postdescriptor(control_connection_t *conn,
154 uint32_t len,
155 const char *body);
156 static int handle_control_redirectstream(control_connection_t *conn,
157 uint32_t len,
158 const char *body);
159 static int handle_control_closestream(control_connection_t *conn, uint32_t len,
160 const char *body);
161 static int handle_control_closecircuit(control_connection_t *conn,
162 uint32_t len,
163 const char *body);
164 static int handle_control_resolve(control_connection_t *conn, uint32_t len,
165 const char *body);
166 static int handle_control_usefeature(control_connection_t *conn,
167 uint32_t len,
168 const char *body);
169 static int write_stream_target_to_buf(edge_connection_t *conn, char *buf,
170 size_t len);
171 static void orconn_target_get_name(char *buf, size_t len,
172 or_connection_t *conn);
173 static char *get_cookie_file(void);
175 /** Given a control event code for a message event, return the corresponding
176 * log severity. */
177 static INLINE int
178 event_to_log_severity(int event)
180 switch (event) {
181 case EVENT_DEBUG_MSG: return LOG_DEBUG;
182 case EVENT_INFO_MSG: return LOG_INFO;
183 case EVENT_NOTICE_MSG: return LOG_NOTICE;
184 case EVENT_WARN_MSG: return LOG_WARN;
185 case EVENT_ERR_MSG: return LOG_ERR;
186 default: return -1;
190 /** Given a log severity, return the corresponding control event code. */
191 static INLINE int
192 log_severity_to_event(int severity)
194 switch (severity) {
195 case LOG_DEBUG: return EVENT_DEBUG_MSG;
196 case LOG_INFO: return EVENT_INFO_MSG;
197 case LOG_NOTICE: return EVENT_NOTICE_MSG;
198 case LOG_WARN: return EVENT_WARN_MSG;
199 case LOG_ERR: return EVENT_ERR_MSG;
200 default: return -1;
204 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
205 * connection's event_mask field. */
206 void
207 control_update_global_event_mask(void)
209 smartlist_t *conns = get_connection_array();
210 event_mask_t old_mask, new_mask;
211 old_mask = global_event_mask;
213 global_event_mask = 0;
214 SMARTLIST_FOREACH(conns, connection_t *, _conn,
216 if (_conn->type == CONN_TYPE_CONTROL &&
217 STATE_IS_OPEN(_conn->state)) {
218 control_connection_t *conn = TO_CONTROL_CONN(_conn);
219 global_event_mask |= conn->event_mask;
223 new_mask = global_event_mask;
225 /* Handle the aftermath. Set up the log callback to tell us only what
226 * we want to hear...*/
227 control_adjust_event_log_severity();
229 /* ...then, if we've started logging stream bw, clear the appropriate
230 * fields. */
231 if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
232 (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
233 SMARTLIST_FOREACH(conns, connection_t *, conn,
235 if (conn->type == CONN_TYPE_AP) {
236 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
237 edge_conn->n_written = edge_conn->n_read = 0;
243 /** Adjust the log severities that result in control_event_logmsg being called
244 * to match the severity of log messages that any controllers are interested
245 * in. */
246 void
247 control_adjust_event_log_severity(void)
249 int i;
250 int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
252 for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
253 if (EVENT_IS_INTERESTING(i)) {
254 min_log_event = i;
255 break;
258 for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
259 if (EVENT_IS_INTERESTING(i)) {
260 max_log_event = i;
261 break;
264 if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE) ||
265 EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
266 if (min_log_event > EVENT_NOTICE_MSG)
267 min_log_event = EVENT_NOTICE_MSG;
268 if (max_log_event < EVENT_ERR_MSG)
269 max_log_event = EVENT_ERR_MSG;
271 if (min_log_event <= max_log_event)
272 change_callback_log_severity(event_to_log_severity(min_log_event),
273 event_to_log_severity(max_log_event),
274 control_event_logmsg);
275 else
276 change_callback_log_severity(LOG_ERR, LOG_ERR,
277 control_event_logmsg);
280 /** Return true iff the event with code <b>c</b> is being sent to any current
281 * control connection. This is useful if the amount of work needed to prepare
282 * to call the appropriate control_event_...() function is high.
285 control_event_is_interesting(int event)
287 return EVENT_IS_INTERESTING(event);
290 /** Append a NUL-terminated string <b>s</b> to the end of
291 * <b>conn</b>-\>outbuf.
293 static INLINE void
294 connection_write_str_to_buf(const char *s, control_connection_t *conn)
296 size_t len = strlen(s);
297 connection_write_to_buf(s, len, TO_CONN(conn));
300 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
301 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
302 * contents of <b>data</b> into *<b>out</b>, adding a period before any period
303 * that appears at the start of a line, and adding a period-CRLF line at
304 * the end. Replace all LF characters sequences with CRLF. Return the number
305 * of bytes in *<b>out</b>.
307 /* static */ size_t
308 write_escaped_data(const char *data, size_t len, char **out)
310 size_t sz_out = len+8;
311 char *outp;
312 const char *start = data, *end;
313 int i;
314 int start_of_line;
315 for (i=0; i<(int)len; ++i) {
316 if (data[i]== '\n')
317 sz_out += 2; /* Maybe add a CR; maybe add a dot. */
319 *out = outp = tor_malloc(sz_out+1);
320 end = data+len;
321 start_of_line = 1;
322 while (data < end) {
323 if (*data == '\n') {
324 if (data > start && data[-1] != '\r')
325 *outp++ = '\r';
326 start_of_line = 1;
327 } else if (*data == '.') {
328 if (start_of_line) {
329 start_of_line = 0;
330 *outp++ = '.';
332 } else {
333 start_of_line = 0;
335 *outp++ = *data++;
337 if (outp < *out+2 || fast_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 (fast_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 /** Write all of the open control ports to ControlPortWriteToFile */
512 void
513 control_ports_write_to_file(void)
515 smartlist_t *lines;
516 char *joined = NULL;
517 or_options_t *options = get_options();
519 if (!options->ControlPortWriteToFile)
520 return;
522 lines = smartlist_create();
524 SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t *, conn) {
525 char *port_str = NULL;
526 if (conn->type != CONN_TYPE_CONTROL_LISTENER || conn->marked_for_close)
527 continue;
528 #ifdef AF_UNIX
529 if (conn->socket_family == AF_UNIX) {
530 tor_asprintf(&port_str, "UNIX_PORT=%s\n", conn->address);
531 smartlist_add(lines, port_str);
532 continue;
534 #endif
535 tor_asprintf(&port_str, "PORT=%s:%d\n", conn->address, conn->port);
536 smartlist_add(lines, port_str);
537 } SMARTLIST_FOREACH_END(conn);
539 joined = smartlist_join_strings(lines, "", 0, NULL);
541 if (write_str_to_file(options->ControlPortWriteToFile, joined, 0) < 0) {
542 log_warn(LD_CONTROL, "Writing %s failed: %s",
543 options->ControlPortWriteToFile, strerror(errno));
545 #ifndef MS_WINDOWS
546 if (options->ControlPortFileGroupReadable) {
547 if (chmod(options->ControlPortWriteToFile, 0640)) {
548 log_warn(LD_FS,"Unable to make %s group-readable.",
549 options->ControlPortWriteToFile);
552 #endif
553 tor_free(joined);
554 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
555 smartlist_free(lines);
558 /** Send a "DONE" message down the control connection <b>conn</b>. */
559 static void
560 send_control_done(control_connection_t *conn)
562 connection_write_str_to_buf("250 OK\r\n", conn);
565 /** Send an event to all v1 controllers that are listening for code
566 * <b>event</b>. The event's body is given by <b>msg</b>.
568 * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
569 * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
570 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
571 * to controllers that <em>have</em> enabled VERBOSE_NAMES.
573 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
574 * respect to the EXTENDED_EVENTS feature. */
575 static void
576 send_control_event_string(uint16_t event, event_format_t which,
577 const char *msg)
579 smartlist_t *conns = get_connection_array();
580 (void)which;
581 tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);
583 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
584 if (conn->type == CONN_TYPE_CONTROL &&
585 !conn->marked_for_close &&
586 conn->state == CONTROL_CONN_STATE_OPEN) {
587 control_connection_t *control_conn = TO_CONTROL_CONN(conn);
589 if (control_conn->event_mask & (1<<event)) {
590 int is_err = 0;
591 connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
592 if (event == EVENT_ERR_MSG)
593 is_err = 1;
594 else if (event == EVENT_STATUS_GENERAL)
595 is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
596 else if (event == EVENT_STATUS_CLIENT)
597 is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
598 else if (event == EVENT_STATUS_SERVER)
599 is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
600 if (is_err)
601 connection_handle_write(TO_CONN(control_conn), 1);
604 } SMARTLIST_FOREACH_END(conn);
607 /** Helper for send_control1_event and send_control1_event_extended:
608 * Send an event to all v1 controllers that are listening for code
609 * <b>event</b>. The event's body is created by the printf-style format in
610 * <b>format</b>, and other arguments as provided.
612 * Currently the length of the message is limited to 1024 (including the
613 * ending \\r\\n\\0). */
614 static void
615 send_control_event_impl(uint16_t event, event_format_t which,
616 const char *format, va_list ap)
618 /* This is just a little longer than the longest allowed log message */
619 #define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
620 int r;
621 char buf[SEND_CONTROL1_EVENT_BUFFERSIZE];
622 size_t len;
624 r = tor_vsnprintf(buf, sizeof(buf), format, ap);
625 if (r<0) {
626 log_warn(LD_BUG, "Unable to format event for controller.");
627 return;
630 len = strlen(buf);
631 if (fast_memcmp("\r\n\0", buf+len-2, 3)) {
632 /* if it is not properly terminated, do it now */
633 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-1] = '\0';
634 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-2] = '\n';
635 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-3] = '\r';
638 send_control_event_string(event, which|ALL_FORMATS, buf);
641 /** Send an event to all v1 controllers that are listening for code
642 * <b>event</b>. The event's body is created by the printf-style format in
643 * <b>format</b>, and other arguments as provided.
645 * Currently the length of the message is limited to 1024 (including the
646 * ending \\n\\r\\0. */
647 static void
648 send_control_event(uint16_t event, event_format_t which,
649 const char *format, ...)
651 va_list ap;
652 va_start(ap, format);
653 send_control_event_impl(event, which, format, ap);
654 va_end(ap);
657 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
658 static origin_circuit_t *
659 get_circ(const char *id)
661 uint32_t n_id;
662 int ok;
663 n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
664 if (!ok)
665 return NULL;
666 return circuit_get_by_global_id(n_id);
669 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
670 static edge_connection_t *
671 get_stream(const char *id)
673 uint64_t n_id;
674 int ok;
675 connection_t *conn;
676 n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
677 if (!ok)
678 return NULL;
679 conn = connection_get_by_global_id(n_id);
680 if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
681 return NULL;
682 return TO_EDGE_CONN(conn);
685 /** Helper for setconf and resetconf. Acts like setconf, except
686 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
687 * contents of body.
689 static int
690 control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
691 int use_defaults)
693 setopt_err_t opt_err;
694 config_line_t *lines=NULL;
695 char *start = body;
696 char *errstring = NULL;
697 const int clear_first = 1;
699 char *config;
700 smartlist_t *entries = smartlist_create();
702 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
703 * separated by space. break it into a list of configuration entries. */
704 while (*body) {
705 char *eq = body;
706 char *key;
707 char *entry;
708 while (!TOR_ISSPACE(*eq) && *eq != '=')
709 ++eq;
710 key = tor_strndup(body, eq-body);
711 body = eq+1;
712 if (*eq == '=') {
713 char *val=NULL;
714 size_t val_len=0;
715 size_t ent_len;
716 if (*body != '\"') {
717 char *val_start = body;
718 while (!TOR_ISSPACE(*body))
719 body++;
720 val = tor_strndup(val_start, body-val_start);
721 val_len = strlen(val);
722 } else {
723 body = (char*)extract_escaped_string(body, (len - (body-start)),
724 &val, &val_len);
725 if (!body) {
726 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
727 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
728 smartlist_free(entries);
729 tor_free(key);
730 return 0;
733 ent_len = strlen(key)+val_len+3;
734 entry = tor_malloc(ent_len+1);
735 tor_snprintf(entry, ent_len, "%s %s", key, val);
736 tor_free(key);
737 tor_free(val);
738 } else {
739 entry = key;
741 smartlist_add(entries, entry);
742 while (TOR_ISSPACE(*body))
743 ++body;
746 smartlist_add(entries, tor_strdup(""));
747 config = smartlist_join_strings(entries, "\n", 0, NULL);
748 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
749 smartlist_free(entries);
751 if (config_get_lines(config, &lines) < 0) {
752 log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
753 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
754 conn);
755 tor_free(config);
756 return 0;
758 tor_free(config);
760 opt_err = options_trial_assign(lines, use_defaults, clear_first, &errstring);
762 const char *msg;
763 switch (opt_err) {
764 case SETOPT_ERR_MISC:
765 msg = "552 Unrecognized option";
766 break;
767 case SETOPT_ERR_PARSE:
768 msg = "513 Unacceptable option value";
769 break;
770 case SETOPT_ERR_TRANSITION:
771 msg = "553 Transition not allowed";
772 break;
773 case SETOPT_ERR_SETTING:
774 default:
775 msg = "553 Unable to set option";
776 break;
777 case SETOPT_OK:
778 config_free_lines(lines);
779 send_control_done(conn);
780 return 0;
782 log_warn(LD_CONTROL,
783 "Controller gave us config lines that didn't validate: %s",
784 errstring);
785 connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
786 config_free_lines(lines);
787 tor_free(errstring);
788 return 0;
792 /** Called when we receive a SETCONF message: parse the body and try
793 * to update our configuration. Reply with a DONE or ERROR message.
794 * Modifies the contents of body.*/
795 static int
796 handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
798 return control_setconf_helper(conn, len, body, 0);
801 /** Called when we receive a RESETCONF message: parse the body and try
802 * to update our configuration. Reply with a DONE or ERROR message.
803 * Modifies the contents of body. */
804 static int
805 handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
807 return control_setconf_helper(conn, len, body, 1);
810 /** Called when we receive a GETCONF message. Parse the request, and
811 * reply with a CONFVALUE or an ERROR message */
812 static int
813 handle_control_getconf(control_connection_t *conn, uint32_t body_len,
814 const char *body)
816 smartlist_t *questions = smartlist_create();
817 smartlist_t *answers = smartlist_create();
818 smartlist_t *unrecognized = smartlist_create();
819 char *msg = NULL;
820 size_t msg_len;
821 or_options_t *options = get_options();
822 int i, len;
824 (void) body_len; /* body is NUL-terminated; so we can ignore len. */
825 smartlist_split_string(questions, body, " ",
826 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
827 SMARTLIST_FOREACH(questions, const char *, q,
829 if (!option_is_recognized(q)) {
830 smartlist_add(unrecognized, (char*) q);
831 } else {
832 config_line_t *answer = option_get_assignment(options,q);
833 if (!answer) {
834 const char *name = option_get_canonical_name(q);
835 size_t alen = strlen(name)+8;
836 char *astr = tor_malloc(alen);
837 tor_snprintf(astr, alen, "250-%s\r\n", name);
838 smartlist_add(answers, astr);
841 while (answer) {
842 config_line_t *next;
843 size_t alen = strlen(answer->key)+strlen(answer->value)+8;
844 char *astr = tor_malloc(alen);
845 tor_snprintf(astr, alen, "250-%s=%s\r\n",
846 answer->key, answer->value);
847 smartlist_add(answers, astr);
849 next = answer->next;
850 tor_free(answer->key);
851 tor_free(answer->value);
852 tor_free(answer);
853 answer = next;
858 if ((len = smartlist_len(unrecognized))) {
859 for (i=0; i < len-1; ++i)
860 connection_printf_to_buf(conn,
861 "552-Unrecognized configuration key \"%s\"\r\n",
862 (char*)smartlist_get(unrecognized, i));
863 connection_printf_to_buf(conn,
864 "552 Unrecognized configuration key \"%s\"\r\n",
865 (char*)smartlist_get(unrecognized, len-1));
866 } else if ((len = smartlist_len(answers))) {
867 char *tmp = smartlist_get(answers, len-1);
868 tor_assert(strlen(tmp)>4);
869 tmp[3] = ' ';
870 msg = smartlist_join_strings(answers, "", 0, &msg_len);
871 connection_write_to_buf(msg, msg_len, TO_CONN(conn));
872 } else {
873 connection_write_str_to_buf("250 OK\r\n", conn);
876 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
877 smartlist_free(answers);
878 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
879 smartlist_free(questions);
880 smartlist_free(unrecognized);
882 tor_free(msg);
884 return 0;
887 /** Called when we get a +LOADCONF message. */
888 static int
889 handle_control_loadconf(control_connection_t *conn, uint32_t len,
890 const char *body)
892 setopt_err_t retval;
893 char *errstring = NULL;
894 const char *msg = NULL;
895 (void) len;
897 retval = options_init_from_string(body, CMD_RUN_TOR, NULL, &errstring);
899 if (retval != SETOPT_OK)
900 log_warn(LD_CONTROL,
901 "Controller gave us config file that didn't validate: %s",
902 errstring);
904 switch (retval) {
905 case SETOPT_ERR_PARSE:
906 msg = "552 Invalid config file";
907 break;
908 case SETOPT_ERR_TRANSITION:
909 msg = "553 Transition not allowed";
910 break;
911 case SETOPT_ERR_SETTING:
912 msg = "553 Unable to set option";
913 break;
914 case SETOPT_ERR_MISC:
915 default:
916 msg = "550 Unable to load config";
917 break;
918 case SETOPT_OK:
919 break;
921 if (msg) {
922 if (errstring)
923 connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
924 else
925 connection_printf_to_buf(conn, "%s\r\n", msg);
926 } else {
927 send_control_done(conn);
929 tor_free(errstring);
930 return 0;
933 /** Called when we get a SETEVENTS message: update conn->event_mask,
934 * and reply with DONE or ERROR. */
935 static int
936 handle_control_setevents(control_connection_t *conn, uint32_t len,
937 const char *body)
939 uint16_t event_code;
940 uint32_t event_mask = 0;
941 smartlist_t *events = smartlist_create();
943 (void) len;
945 smartlist_split_string(events, body, " ",
946 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
947 SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
949 if (!strcasecmp(ev, "EXTENDED")) {
950 continue;
951 } else if (!strcasecmp(ev, "CIRC"))
952 event_code = EVENT_CIRCUIT_STATUS;
953 else if (!strcasecmp(ev, "STREAM"))
954 event_code = EVENT_STREAM_STATUS;
955 else if (!strcasecmp(ev, "ORCONN"))
956 event_code = EVENT_OR_CONN_STATUS;
957 else if (!strcasecmp(ev, "BW"))
958 event_code = EVENT_BANDWIDTH_USED;
959 else if (!strcasecmp(ev, "DEBUG"))
960 event_code = EVENT_DEBUG_MSG;
961 else if (!strcasecmp(ev, "INFO"))
962 event_code = EVENT_INFO_MSG;
963 else if (!strcasecmp(ev, "NOTICE"))
964 event_code = EVENT_NOTICE_MSG;
965 else if (!strcasecmp(ev, "WARN"))
966 event_code = EVENT_WARN_MSG;
967 else if (!strcasecmp(ev, "ERR"))
968 event_code = EVENT_ERR_MSG;
969 else if (!strcasecmp(ev, "NEWDESC"))
970 event_code = EVENT_NEW_DESC;
971 else if (!strcasecmp(ev, "ADDRMAP"))
972 event_code = EVENT_ADDRMAP;
973 else if (!strcasecmp(ev, "AUTHDIR_NEWDESCS"))
974 event_code = EVENT_AUTHDIR_NEWDESCS;
975 else if (!strcasecmp(ev, "DESCCHANGED"))
976 event_code = EVENT_DESCCHANGED;
977 else if (!strcasecmp(ev, "NS"))
978 event_code = EVENT_NS;
979 else if (!strcasecmp(ev, "STATUS_GENERAL"))
980 event_code = EVENT_STATUS_GENERAL;
981 else if (!strcasecmp(ev, "STATUS_CLIENT"))
982 event_code = EVENT_STATUS_CLIENT;
983 else if (!strcasecmp(ev, "STATUS_SERVER"))
984 event_code = EVENT_STATUS_SERVER;
985 else if (!strcasecmp(ev, "GUARD"))
986 event_code = EVENT_GUARD;
987 else if (!strcasecmp(ev, "STREAM_BW"))
988 event_code = EVENT_STREAM_BANDWIDTH_USED;
989 else if (!strcasecmp(ev, "CLIENTS_SEEN"))
990 event_code = EVENT_CLIENTS_SEEN;
991 else if (!strcasecmp(ev, "NEWCONSENSUS"))
992 event_code = EVENT_NEWCONSENSUS;
993 else if (!strcasecmp(ev, "BUILDTIMEOUT_SET"))
994 event_code = EVENT_BUILDTIMEOUT_SET;
995 else {
996 connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
997 ev);
998 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
999 smartlist_free(events);
1000 return 0;
1002 event_mask |= (1 << event_code);
1004 SMARTLIST_FOREACH_END(ev);
1005 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
1006 smartlist_free(events);
1008 conn->event_mask = event_mask;
1010 control_update_global_event_mask();
1011 send_control_done(conn);
1012 return 0;
1015 /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
1016 * Return a smartlist of acceptable passwords (unterminated strings of
1017 * length S2K_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on failure.
1019 smartlist_t *
1020 decode_hashed_passwords(config_line_t *passwords)
1022 char decoded[64];
1023 config_line_t *cl;
1024 smartlist_t *sl = smartlist_create();
1026 tor_assert(passwords);
1028 for (cl = passwords; cl; cl = cl->next) {
1029 const char *hashed = cl->value;
1031 if (!strcmpstart(hashed, "16:")) {
1032 if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
1033 || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
1034 goto err;
1036 } else {
1037 if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
1038 != S2K_SPECIFIER_LEN+DIGEST_LEN) {
1039 goto err;
1042 smartlist_add(sl, tor_memdup(decoded, S2K_SPECIFIER_LEN+DIGEST_LEN));
1045 return sl;
1047 err:
1048 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
1049 smartlist_free(sl);
1050 return NULL;
1053 /** Called when we get an AUTHENTICATE message. Check whether the
1054 * authentication is valid, and if so, update the connection's state to
1055 * OPEN. Reply with DONE or ERROR.
1057 static int
1058 handle_control_authenticate(control_connection_t *conn, uint32_t len,
1059 const char *body)
1061 int used_quoted_string = 0;
1062 or_options_t *options = get_options();
1063 const char *errstr = NULL;
1064 char *password;
1065 size_t password_len;
1066 const char *cp;
1067 int i;
1068 int bad_cookie=0, bad_password=0;
1069 smartlist_t *sl = NULL;
1071 if (TOR_ISXDIGIT(body[0])) {
1072 cp = body;
1073 while (TOR_ISXDIGIT(*cp))
1074 ++cp;
1075 i = (int)(cp - body);
1076 tor_assert(i>0);
1077 password_len = i/2;
1078 password = tor_malloc(password_len + 1);
1079 if (base16_decode(password, password_len+1, body, i)<0) {
1080 connection_write_str_to_buf(
1081 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1082 "password? If so, the standard requires that you put it in "
1083 "double quotes.\r\n", conn);
1084 connection_mark_for_close(TO_CONN(conn));
1085 tor_free(password);
1086 return 0;
1088 } else if (TOR_ISSPACE(body[0])) {
1089 password = tor_strdup("");
1090 password_len = 0;
1091 } else {
1092 if (!decode_escaped_string(body, len, &password, &password_len)) {
1093 connection_write_str_to_buf("551 Invalid quoted string. You need "
1094 "to put the password in double quotes.\r\n", conn);
1095 connection_mark_for_close(TO_CONN(conn));
1096 return 0;
1098 used_quoted_string = 1;
1101 if (!options->CookieAuthentication && !options->HashedControlPassword &&
1102 !options->HashedControlSessionPassword) {
1103 /* if Tor doesn't demand any stronger authentication, then
1104 * the controller can get in with anything. */
1105 goto ok;
1108 if (options->CookieAuthentication) {
1109 int also_password = options->HashedControlPassword != NULL ||
1110 options->HashedControlSessionPassword != NULL;
1111 if (password_len != AUTHENTICATION_COOKIE_LEN) {
1112 if (!also_password) {
1113 log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
1114 "(%d)", (int)password_len);
1115 errstr = "Wrong length on authentication cookie.";
1116 goto err;
1118 bad_cookie = 1;
1119 } else if (tor_memneq(authentication_cookie, password, password_len)) {
1120 if (!also_password) {
1121 log_warn(LD_CONTROL, "Got mismatched authentication cookie");
1122 errstr = "Authentication cookie did not match expected value.";
1123 goto err;
1125 bad_cookie = 1;
1126 } else {
1127 goto ok;
1131 if (options->HashedControlPassword ||
1132 options->HashedControlSessionPassword) {
1133 int bad = 0;
1134 smartlist_t *sl_tmp;
1135 char received[DIGEST_LEN];
1136 int also_cookie = options->CookieAuthentication;
1137 sl = smartlist_create();
1138 if (options->HashedControlPassword) {
1139 sl_tmp = decode_hashed_passwords(options->HashedControlPassword);
1140 if (!sl_tmp)
1141 bad = 1;
1142 else {
1143 smartlist_add_all(sl, sl_tmp);
1144 smartlist_free(sl_tmp);
1147 if (options->HashedControlSessionPassword) {
1148 sl_tmp = decode_hashed_passwords(options->HashedControlSessionPassword);
1149 if (!sl_tmp)
1150 bad = 1;
1151 else {
1152 smartlist_add_all(sl, sl_tmp);
1153 smartlist_free(sl_tmp);
1156 if (bad) {
1157 if (!also_cookie) {
1158 log_warn(LD_CONTROL,
1159 "Couldn't decode HashedControlPassword: invalid base16");
1160 errstr="Couldn't decode HashedControlPassword value in configuration.";
1162 bad_password = 1;
1163 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1164 smartlist_free(sl);
1165 } else {
1166 SMARTLIST_FOREACH(sl, char *, expected,
1168 secret_to_key(received,DIGEST_LEN,password,password_len,expected);
1169 if (tor_memeq(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
1170 goto ok;
1172 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1173 smartlist_free(sl);
1175 if (used_quoted_string)
1176 errstr = "Password did not match HashedControlPassword value from "
1177 "configuration";
1178 else
1179 errstr = "Password did not match HashedControlPassword value from "
1180 "configuration. Maybe you tried a plain text password? "
1181 "If so, the standard requires that you put it in double quotes.";
1182 bad_password = 1;
1183 if (!also_cookie)
1184 goto err;
1188 /** We only get here if both kinds of authentication failed. */
1189 tor_assert(bad_password && bad_cookie);
1190 log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
1191 errstr = "Password did not match HashedControlPassword *or* authentication "
1192 "cookie.";
1194 err:
1195 tor_free(password);
1196 connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n",
1197 errstr ? errstr : "Unknown reason.");
1198 connection_mark_for_close(TO_CONN(conn));
1199 return 0;
1201 log_info(LD_CONTROL, "Authenticated control connection (%d)", conn->_base.s);
1202 send_control_done(conn);
1203 conn->_base.state = CONTROL_CONN_STATE_OPEN;
1204 tor_free(password);
1205 if (sl) { /* clean up */
1206 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1207 smartlist_free(sl);
1209 return 0;
1212 /** Called when we get a SAVECONF command. Try to flush the current options to
1213 * disk, and report success or failure. */
1214 static int
1215 handle_control_saveconf(control_connection_t *conn, uint32_t len,
1216 const char *body)
1218 (void) len;
1219 (void) body;
1220 if (options_save_current()<0) {
1221 connection_write_str_to_buf(
1222 "551 Unable to write configuration to disk.\r\n", conn);
1223 } else {
1224 send_control_done(conn);
1226 return 0;
1229 /** Called when we get a SIGNAL command. React to the provided signal, and
1230 * report success or failure. (If the signal results in a shutdown, success
1231 * may not be reported.) */
1232 static int
1233 handle_control_signal(control_connection_t *conn, uint32_t len,
1234 const char *body)
1236 int sig;
1237 int n = 0;
1238 char *s;
1240 (void) len;
1242 while (body[n] && ! TOR_ISSPACE(body[n]))
1243 ++n;
1244 s = tor_strndup(body, n);
1245 if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
1246 sig = SIGHUP;
1247 else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
1248 sig = SIGINT;
1249 else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
1250 sig = SIGUSR1;
1251 else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
1252 sig = SIGUSR2;
1253 else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
1254 sig = SIGTERM;
1255 else if (!strcasecmp(s, "NEWNYM"))
1256 sig = SIGNEWNYM;
1257 else if (!strcasecmp(s, "CLEARDNSCACHE"))
1258 sig = SIGCLEARDNSCACHE;
1259 else {
1260 connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
1262 sig = -1;
1264 tor_free(s);
1265 if (sig<0)
1266 return 0;
1268 send_control_done(conn);
1269 /* Flush the "done" first if the signal might make us shut down. */
1270 if (sig == SIGTERM || sig == SIGINT)
1271 connection_handle_write(TO_CONN(conn), 1);
1273 process_signal(sig);
1275 return 0;
1278 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1279 * and report success or failure. */
1280 static int
1281 handle_control_mapaddress(control_connection_t *conn, uint32_t len,
1282 const char *body)
1284 smartlist_t *elts;
1285 smartlist_t *lines;
1286 smartlist_t *reply;
1287 char *r;
1288 size_t sz;
1289 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
1291 lines = smartlist_create();
1292 elts = smartlist_create();
1293 reply = smartlist_create();
1294 smartlist_split_string(lines, body, " ",
1295 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1296 SMARTLIST_FOREACH(lines, char *, line,
1298 tor_strlower(line);
1299 smartlist_split_string(elts, line, "=", 0, 2);
1300 if (smartlist_len(elts) == 2) {
1301 const char *from = smartlist_get(elts,0);
1302 const char *to = smartlist_get(elts,1);
1303 size_t anslen = strlen(line)+512;
1304 char *ans = tor_malloc(anslen);
1305 if (address_is_invalid_destination(to, 1)) {
1306 tor_snprintf(ans, anslen,
1307 "512-syntax error: invalid address '%s'", to);
1308 smartlist_add(reply, ans);
1309 log_warn(LD_CONTROL,
1310 "Skipping invalid argument '%s' in MapAddress msg", to);
1311 } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
1312 const char *address = addressmap_register_virtual_address(
1313 !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
1314 tor_strdup(to));
1315 if (!address) {
1316 tor_snprintf(ans, anslen,
1317 "451-resource exhausted: skipping '%s'", line);
1318 smartlist_add(reply, ans);
1319 log_warn(LD_CONTROL,
1320 "Unable to allocate address for '%s' in MapAddress msg",
1321 safe_str_client(line));
1322 } else {
1323 tor_snprintf(ans, anslen, "250-%s=%s", address, to);
1324 smartlist_add(reply, ans);
1326 } else {
1327 addressmap_register(from, tor_strdup(to), 1, ADDRMAPSRC_CONTROLLER);
1328 tor_snprintf(ans, anslen, "250-%s", line);
1329 smartlist_add(reply, ans);
1331 } else {
1332 size_t anslen = strlen(line)+256;
1333 char *ans = tor_malloc(anslen);
1334 tor_snprintf(ans, anslen, "512-syntax error: mapping '%s' is "
1335 "not of expected form 'foo=bar'.", line);
1336 smartlist_add(reply, ans);
1337 log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
1338 "number of items.",
1339 safe_str_client(line));
1341 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
1342 smartlist_clear(elts);
1344 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1345 smartlist_free(lines);
1346 smartlist_free(elts);
1348 if (smartlist_len(reply)) {
1349 ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
1350 r = smartlist_join_strings(reply, "\r\n", 1, &sz);
1351 connection_write_to_buf(r, sz, TO_CONN(conn));
1352 tor_free(r);
1353 } else {
1354 const char *response =
1355 "512 syntax error: not enough arguments to mapaddress.\r\n";
1356 connection_write_to_buf(response, strlen(response), TO_CONN(conn));
1359 SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
1360 smartlist_free(reply);
1361 return 0;
1364 /** Implementation helper for GETINFO: knows the answers for various
1365 * trivial-to-implement questions. */
1366 static int
1367 getinfo_helper_misc(control_connection_t *conn, const char *question,
1368 char **answer, const char **errmsg)
1370 (void) conn;
1371 if (!strcmp(question, "version")) {
1372 *answer = tor_strdup(get_version());
1373 } else if (!strcmp(question, "config-file")) {
1374 *answer = tor_strdup(get_torrc_fname());
1375 } else if (!strcmp(question, "config-text")) {
1376 *answer = options_dump(get_options(), 1);
1377 } else if (!strcmp(question, "info/names")) {
1378 *answer = list_getinfo_options();
1379 } else if (!strcmp(question, "events/names")) {
1380 *answer = tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
1381 "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
1382 "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
1383 "GUARD STREAM_BW CLIENTS_SEEN NEWCONSENSUS");
1384 } else if (!strcmp(question, "features/names")) {
1385 *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1386 } else if (!strcmp(question, "address")) {
1387 uint32_t addr;
1388 if (router_pick_published_address(get_options(), &addr) < 0) {
1389 *errmsg = "Address unknown";
1390 return -1;
1392 *answer = tor_dup_ip(addr);
1393 } else if (!strcmp(question, "dir-usage")) {
1394 *answer = directory_dump_request_log();
1395 } else if (!strcmp(question, "fingerprint")) {
1396 routerinfo_t *me = router_get_my_routerinfo();
1397 if (!me) {
1398 *errmsg = "No routerdesc known; am I really a server?";
1399 return -1;
1401 *answer = tor_malloc(HEX_DIGEST_LEN+1);
1402 base16_encode(*answer, HEX_DIGEST_LEN+1, me->cache_info.identity_digest,
1403 DIGEST_LEN);
1405 return 0;
1408 /** Awful hack: return a newly allocated string based on a routerinfo and
1409 * (possibly) an extrainfo, sticking the read-history and write-history from
1410 * <b>ei</b> into the resulting string. The thing you get back won't
1411 * necessarily have a valid signature.
1413 * New code should never use this; it's for backward compatibility.
1415 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1416 * not be NUL-terminated. */
1417 static char *
1418 munge_extrainfo_into_routerinfo(const char *ri_body, signed_descriptor_t *ri,
1419 signed_descriptor_t *ei)
1421 char *out = NULL, *outp;
1422 int i;
1423 const char *router_sig;
1424 const char *ei_body = signed_descriptor_get_body(ei);
1425 size_t ri_len = ri->signed_descriptor_len;
1426 size_t ei_len = ei->signed_descriptor_len;
1427 if (!ei_body)
1428 goto bail;
1430 outp = out = tor_malloc(ri_len+ei_len+1);
1431 if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
1432 goto bail;
1433 ++router_sig;
1434 memcpy(out, ri_body, router_sig-ri_body);
1435 outp += router_sig-ri_body;
1437 for (i=0; i < 2; ++i) {
1438 const char *kwd = i?"\nwrite-history ":"\nread-history ";
1439 const char *cp, *eol;
1440 if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
1441 continue;
1442 ++cp;
1443 eol = memchr(cp, '\n', ei_len - (cp-ei_body));
1444 memcpy(outp, cp, eol-cp+1);
1445 outp += eol-cp+1;
1447 memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
1448 *outp++ = '\0';
1449 tor_assert(outp-out < (int)(ri_len+ei_len+1));
1451 return out;
1452 bail:
1453 tor_free(out);
1454 return tor_strndup(ri_body, ri->signed_descriptor_len);
1457 /** Implementation helper for GETINFO: answers requests for information about
1458 * which ports are bound. */
1459 static int
1460 getinfo_helper_listeners(control_connection_t *control_conn,
1461 const char *question,
1462 char **answer, const char **errmsg)
1464 int type;
1465 smartlist_t *res;
1467 (void)control_conn;
1468 (void)errmsg;
1470 if (!strcmp(question, "net/listeners/or"))
1471 type = CONN_TYPE_OR_LISTENER;
1472 else if (!strcmp(question, "net/listeners/dir"))
1473 type = CONN_TYPE_DIR_LISTENER;
1474 else if (!strcmp(question, "net/listeners/socks"))
1475 type = CONN_TYPE_AP_LISTENER;
1476 else if (!strcmp(question, "net/listeners/trans"))
1477 type = CONN_TYPE_AP_TRANS_LISTENER;
1478 else if (!strcmp(question, "net/listeners/natd"))
1479 type = CONN_TYPE_AP_NATD_LISTENER;
1480 else if (!strcmp(question, "net/listeners/dns"))
1481 type = CONN_TYPE_AP_DNS_LISTENER;
1482 else if (!strcmp(question, "net/listeners/control"))
1483 type = CONN_TYPE_CONTROL_LISTENER;
1484 else
1485 return 0; /* unknown key */
1487 res = smartlist_create();
1488 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
1489 char *addr;
1490 struct sockaddr_storage ss;
1491 socklen_t ss_len = sizeof(ss);
1493 if (conn->type != type || conn->marked_for_close || !SOCKET_OK(conn->s))
1494 continue;
1496 if (getsockname(conn->s, (struct sockaddr *)&ss, &ss_len) < 0) {
1497 tor_asprintf(&addr, "%s:%d", conn->address, (int)conn->port);
1498 } else {
1499 char *tmp = tor_sockaddr_to_str((struct sockaddr *)&ss);
1500 addr = esc_for_log(tmp);
1501 tor_free(tmp);
1503 if (addr)
1504 smartlist_add(res, addr);
1505 } SMARTLIST_FOREACH_END(conn);
1507 *answer = smartlist_join_strings(res, " ", 0, NULL);
1509 SMARTLIST_FOREACH(res, char *, cp, tor_free(cp));
1510 smartlist_free(res);
1511 return 0;
1514 /** Implementation helper for GETINFO: knows the answers for questions about
1515 * directory information. */
1516 static int
1517 getinfo_helper_dir(control_connection_t *control_conn,
1518 const char *question, char **answer,
1519 const char **errmsg)
1521 (void) control_conn;
1522 if (!strcmpstart(question, "desc/id/")) {
1523 routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
1524 if (ri) {
1525 const char *body = signed_descriptor_get_body(&ri->cache_info);
1526 if (body)
1527 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1529 } else if (!strcmpstart(question, "desc/name/")) {
1530 routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
1531 if (ri) {
1532 const char *body = signed_descriptor_get_body(&ri->cache_info);
1533 if (body)
1534 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1536 } else if (!strcmp(question, "desc/all-recent")) {
1537 routerlist_t *routerlist = router_get_routerlist();
1538 smartlist_t *sl = smartlist_create();
1539 if (routerlist && routerlist->routers) {
1540 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
1542 const char *body = signed_descriptor_get_body(&ri->cache_info);
1543 if (body)
1544 smartlist_add(sl,
1545 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1548 *answer = smartlist_join_strings(sl, "", 0, NULL);
1549 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1550 smartlist_free(sl);
1551 } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
1552 /* XXXX Remove this once Torstat asks for extrainfos. */
1553 routerlist_t *routerlist = router_get_routerlist();
1554 smartlist_t *sl = smartlist_create();
1555 if (routerlist && routerlist->routers) {
1556 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
1558 const char *body = signed_descriptor_get_body(&ri->cache_info);
1559 signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
1560 ri->cache_info.extra_info_digest);
1561 if (ei && body) {
1562 smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
1563 &ri->cache_info, ei));
1564 } else if (body) {
1565 smartlist_add(sl,
1566 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1570 *answer = smartlist_join_strings(sl, "", 0, NULL);
1571 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1572 smartlist_free(sl);
1573 } else if (!strcmpstart(question, "desc-annotations/id/")) {
1574 routerinfo_t *ri = router_get_by_hexdigest(question+
1575 strlen("desc-annotations/id/"));
1576 if (ri) {
1577 const char *annotations =
1578 signed_descriptor_get_annotations(&ri->cache_info);
1579 if (annotations)
1580 *answer = tor_strndup(annotations,
1581 ri->cache_info.annotations_len);
1583 } else if (!strcmpstart(question, "dir/server/")) {
1584 size_t answer_len = 0, url_len = strlen(question)+2;
1585 char *url = tor_malloc(url_len);
1586 smartlist_t *descs = smartlist_create();
1587 const char *msg;
1588 int res;
1589 char *cp;
1590 tor_snprintf(url, url_len, "/tor/%s", question+4);
1591 res = dirserv_get_routerdescs(descs, url, &msg);
1592 if (res) {
1593 log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
1594 smartlist_free(descs);
1595 tor_free(url);
1596 *errmsg = msg;
1597 return -1;
1599 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1600 answer_len += sd->signed_descriptor_len);
1601 cp = *answer = tor_malloc(answer_len+1);
1602 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1604 memcpy(cp, signed_descriptor_get_body(sd),
1605 sd->signed_descriptor_len);
1606 cp += sd->signed_descriptor_len;
1608 *cp = '\0';
1609 tor_free(url);
1610 smartlist_free(descs);
1611 } else if (!strcmpstart(question, "dir/status/")) {
1612 if (directory_permits_controller_requests(get_options())) {
1613 size_t len=0;
1614 char *cp;
1615 smartlist_t *status_list = smartlist_create();
1616 dirserv_get_networkstatus_v2(status_list,
1617 question+strlen("dir/status/"));
1618 SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
1619 cp = *answer = tor_malloc(len+1);
1620 SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
1621 memcpy(cp, d->dir, d->dir_len);
1622 cp += d->dir_len;
1624 *cp = '\0';
1625 smartlist_free(status_list);
1626 } else {
1627 smartlist_t *fp_list = smartlist_create();
1628 smartlist_t *status_list = smartlist_create();
1629 dirserv_get_networkstatus_v2_fingerprints(
1630 fp_list, question+strlen("dir/status/"));
1631 SMARTLIST_FOREACH(fp_list, const char *, fp, {
1632 char *s;
1633 char *fname = networkstatus_get_cache_filename(fp);
1634 s = read_file_to_str(fname, 0, NULL);
1635 if (s)
1636 smartlist_add(status_list, s);
1637 tor_free(fname);
1639 SMARTLIST_FOREACH(fp_list, char *, fp, tor_free(fp));
1640 smartlist_free(fp_list);
1641 *answer = smartlist_join_strings(status_list, "", 0, NULL);
1642 SMARTLIST_FOREACH(status_list, char *, s, tor_free(s));
1643 smartlist_free(status_list);
1645 } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
1646 if (directory_caches_dir_info(get_options())) {
1647 const cached_dir_t *consensus = dirserv_get_consensus("ns");
1648 if (consensus)
1649 *answer = tor_strdup(consensus->dir);
1651 if (!*answer) { /* try loading it from disk */
1652 char *filename = get_datadir_fname("cached-consensus");
1653 *answer = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
1654 tor_free(filename);
1656 } else if (!strcmp(question, "network-status")) { /* v1 */
1657 routerlist_t *routerlist = router_get_routerlist();
1658 if (!routerlist || !routerlist->routers ||
1659 list_server_status_v1(routerlist->routers, answer, 1) < 0) {
1660 return -1;
1662 } else if (!strcmpstart(question, "extra-info/digest/")) {
1663 question += strlen("extra-info/digest/");
1664 if (strlen(question) == HEX_DIGEST_LEN) {
1665 char d[DIGEST_LEN];
1666 signed_descriptor_t *sd = NULL;
1667 if (base16_decode(d, sizeof(d), question, strlen(question))==0) {
1668 /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
1669 * but I don't want to risk affecting other parts of the code,
1670 * especially since the rules for using our own extrainfo (including
1671 * when it might be freed) are different from those for using one
1672 * we have downloaded. */
1673 if (router_extrainfo_digest_is_me(d))
1674 sd = &(router_get_my_extrainfo()->cache_info);
1675 else
1676 sd = extrainfo_get_by_descriptor_digest(d);
1678 if (sd) {
1679 const char *body = signed_descriptor_get_body(sd);
1680 if (body)
1681 *answer = tor_strndup(body, sd->signed_descriptor_len);
1686 return 0;
1689 /** Implementation helper for GETINFO: knows how to generate summaries of the
1690 * current states of things we send events about. */
1691 static int
1692 getinfo_helper_events(control_connection_t *control_conn,
1693 const char *question, char **answer,
1694 const char **errmsg)
1696 (void) control_conn;
1697 if (!strcmp(question, "circuit-status")) {
1698 circuit_t *circ;
1699 smartlist_t *status = smartlist_create();
1700 for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
1701 char *s, *path;
1702 size_t slen;
1703 const char *state;
1704 const char *purpose;
1705 if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
1706 continue;
1708 path = circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ));
1710 if (circ->state == CIRCUIT_STATE_OPEN)
1711 state = "BUILT";
1712 else if (strlen(path))
1713 state = "EXTENDED";
1714 else
1715 state = "LAUNCHED";
1717 purpose = circuit_purpose_to_controller_string(circ->purpose);
1718 slen = strlen(path)+strlen(state)+strlen(purpose)+30;
1719 s = tor_malloc(slen+1);
1720 tor_snprintf(s, slen, "%lu %s%s%s PURPOSE=%s",
1721 (unsigned long)TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1722 state, *path ? " " : "", path, purpose);
1723 smartlist_add(status, s);
1724 tor_free(path);
1726 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1727 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1728 smartlist_free(status);
1729 } else if (!strcmp(question, "stream-status")) {
1730 smartlist_t *conns = get_connection_array();
1731 smartlist_t *status = smartlist_create();
1732 char buf[256];
1733 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1734 const char *state;
1735 edge_connection_t *conn;
1736 char *s;
1737 size_t slen;
1738 circuit_t *circ;
1739 origin_circuit_t *origin_circ = NULL;
1740 if (base_conn->type != CONN_TYPE_AP ||
1741 base_conn->marked_for_close ||
1742 base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
1743 base_conn->state == AP_CONN_STATE_NATD_WAIT)
1744 continue;
1745 conn = TO_EDGE_CONN(base_conn);
1746 switch (conn->_base.state)
1748 case AP_CONN_STATE_CONTROLLER_WAIT:
1749 case AP_CONN_STATE_CIRCUIT_WAIT:
1750 if (conn->socks_request &&
1751 SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
1752 state = "NEWRESOLVE";
1753 else
1754 state = "NEW";
1755 break;
1756 case AP_CONN_STATE_RENDDESC_WAIT:
1757 case AP_CONN_STATE_CONNECT_WAIT:
1758 state = "SENTCONNECT"; break;
1759 case AP_CONN_STATE_RESOLVE_WAIT:
1760 state = "SENTRESOLVE"; break;
1761 case AP_CONN_STATE_OPEN:
1762 state = "SUCCEEDED"; break;
1763 default:
1764 log_warn(LD_BUG, "Asked for stream in unknown state %d",
1765 conn->_base.state);
1766 continue;
1768 circ = circuit_get_by_edge_conn(conn);
1769 if (circ && CIRCUIT_IS_ORIGIN(circ))
1770 origin_circ = TO_ORIGIN_CIRCUIT(circ);
1771 write_stream_target_to_buf(conn, buf, sizeof(buf));
1772 slen = strlen(buf)+strlen(state)+32;
1773 s = tor_malloc(slen+1);
1774 tor_snprintf(s, slen, "%lu %s %lu %s",
1775 (unsigned long) conn->_base.global_identifier,state,
1776 origin_circ?
1777 (unsigned long)origin_circ->global_identifier : 0ul,
1778 buf);
1779 smartlist_add(status, s);
1780 } SMARTLIST_FOREACH_END(base_conn);
1781 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1782 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1783 smartlist_free(status);
1784 } else if (!strcmp(question, "orconn-status")) {
1785 smartlist_t *conns = get_connection_array();
1786 smartlist_t *status = smartlist_create();
1787 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1788 const char *state;
1789 char *s;
1790 char name[128];
1791 size_t slen;
1792 or_connection_t *conn;
1793 if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
1794 continue;
1795 conn = TO_OR_CONN(base_conn);
1796 if (conn->_base.state == OR_CONN_STATE_OPEN)
1797 state = "CONNECTED";
1798 else if (conn->nickname)
1799 state = "LAUNCHED";
1800 else
1801 state = "NEW";
1802 orconn_target_get_name(name, sizeof(name), conn);
1803 slen = strlen(name)+strlen(state)+2;
1804 s = tor_malloc(slen+1);
1805 tor_snprintf(s, slen, "%s %s", name, state);
1806 smartlist_add(status, s);
1807 } SMARTLIST_FOREACH_END(base_conn);
1808 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1809 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1810 smartlist_free(status);
1811 } else if (!strcmpstart(question, "address-mappings/")) {
1812 time_t min_e, max_e;
1813 smartlist_t *mappings;
1814 question += strlen("address-mappings/");
1815 if (!strcmp(question, "all")) {
1816 min_e = 0; max_e = TIME_MAX;
1817 } else if (!strcmp(question, "cache")) {
1818 min_e = 2; max_e = TIME_MAX;
1819 } else if (!strcmp(question, "config")) {
1820 min_e = 0; max_e = 0;
1821 } else if (!strcmp(question, "control")) {
1822 min_e = 1; max_e = 1;
1823 } else {
1824 return 0;
1826 mappings = smartlist_create();
1827 addressmap_get_mappings(mappings, min_e, max_e, 1);
1828 *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
1829 SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
1830 smartlist_free(mappings);
1831 } else if (!strcmpstart(question, "status/")) {
1832 /* Note that status/ is not a catch-all for events; there's only supposed
1833 * to be a status GETINFO if there's a corresponding STATUS event. */
1834 if (!strcmp(question, "status/circuit-established")) {
1835 *answer = tor_strdup(can_complete_circuit ? "1" : "0");
1836 } else if (!strcmp(question, "status/enough-dir-info")) {
1837 *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
1838 } else if (!strcmp(question, "status/good-server-descriptor") ||
1839 !strcmp(question, "status/accepted-server-descriptor")) {
1840 /* They're equivalent for now, until we can figure out how to make
1841 * good-server-descriptor be what we want. See comment in
1842 * control-spec.txt. */
1843 *answer = tor_strdup(directories_have_accepted_server_descriptor()
1844 ? "1" : "0");
1845 } else if (!strcmp(question, "status/reachability-succeeded/or")) {
1846 *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
1847 } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
1848 *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
1849 } else if (!strcmp(question, "status/reachability-succeeded")) {
1850 *answer = tor_malloc(16);
1851 tor_snprintf(*answer, 16, "OR=%d DIR=%d",
1852 check_whether_orport_reachable() ? 1 : 0,
1853 check_whether_dirport_reachable() ? 1 : 0);
1854 } else if (!strcmp(question, "status/bootstrap-phase")) {
1855 *answer = tor_strdup(last_sent_bootstrap_message);
1856 } else if (!strcmpstart(question, "status/version/")) {
1857 int is_server = server_mode(get_options());
1858 networkstatus_t *c = networkstatus_get_latest_consensus();
1859 version_status_t status;
1860 const char *recommended;
1861 if (c) {
1862 recommended = is_server ? c->server_versions : c->client_versions;
1863 status = tor_version_is_obsolete(VERSION, recommended);
1864 } else {
1865 recommended = "?";
1866 status = VS_UNKNOWN;
1869 if (!strcmp(question, "status/version/recommended")) {
1870 *answer = tor_strdup(recommended);
1871 return 0;
1873 if (!strcmp(question, "status/version/current")) {
1874 switch (status)
1876 case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
1877 case VS_OLD: *answer = tor_strdup("obsolete"); break;
1878 case VS_NEW: *answer = tor_strdup("new"); break;
1879 case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
1880 case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
1881 case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
1882 case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
1883 default: tor_fragile_assert();
1885 } else if (!strcmp(question, "status/version/num-versioning") ||
1886 !strcmp(question, "status/version/num-concurring")) {
1887 char s[33];
1888 tor_snprintf(s, sizeof(s), "%d", get_n_authorities(V3_AUTHORITY));
1889 *answer = tor_strdup(s);
1890 log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
1891 "information", question);
1893 } else if (!strcmp(question, "status/clients-seen")) {
1894 char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
1895 if (!bridge_stats) {
1896 *errmsg = "No bridge-client stats available";
1897 return -1;
1899 *answer = bridge_stats;
1900 } else {
1901 return 0;
1904 return 0;
1907 /** Callback function for GETINFO: on a given control connection, try to
1908 * answer the question <b>q</b> and store the newly-allocated answer in
1909 * *<b>a</b>. If an internal error occurs, return -1 and optionally set
1910 * *<b>error_out</b> to point to an error message to be delivered to the
1911 * controller. On success, _or if the key is not recognized_, return 0. Do not
1912 * set <b>a</b> if the key is not recognized.
1914 typedef int (*getinfo_helper_t)(control_connection_t *,
1915 const char *q, char **a,
1916 const char **error_out);
1918 /** A single item for the GETINFO question-to-answer-function table. */
1919 typedef struct getinfo_item_t {
1920 const char *varname; /**< The value (or prefix) of the question. */
1921 getinfo_helper_t fn; /**< The function that knows the answer: NULL if
1922 * this entry is documentation-only. */
1923 const char *desc; /**< Description of the variable. */
1924 int is_prefix; /** Must varname match exactly, or must it be a prefix? */
1925 } getinfo_item_t;
1927 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
1928 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
1929 #define DOC(name, desc) { name, NULL, desc, 0 }
1931 /** Table mapping questions accepted by GETINFO to the functions that know how
1932 * to answer them. */
1933 static const getinfo_item_t getinfo_items[] = {
1934 ITEM("version", misc, "The current version of Tor."),
1935 ITEM("config-file", misc, "Current location of the \"torrc\" file."),
1936 ITEM("config-text", misc,
1937 "Return the string that would be written by a saveconf command."),
1938 ITEM("accounting/bytes", accounting,
1939 "Number of bytes read/written so far in the accounting interval."),
1940 ITEM("accounting/bytes-left", accounting,
1941 "Number of bytes left to write/read so far in the accounting interval."),
1942 ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
1943 ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
1944 ITEM("accounting/interval-start", accounting,
1945 "Time when the accounting period starts."),
1946 ITEM("accounting/interval-end", accounting,
1947 "Time when the accounting period ends."),
1948 ITEM("accounting/interval-wake", accounting,
1949 "Time to wake up in this accounting period."),
1950 ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
1951 ITEM("entry-guards", entry_guards,
1952 "Which nodes are we using as entry guards?"),
1953 ITEM("fingerprint", misc, NULL),
1954 PREFIX("config/", config, "Current configuration values."),
1955 DOC("config/names",
1956 "List of configuration options, types, and documentation."),
1957 ITEM("info/names", misc,
1958 "List of GETINFO options, types, and documentation."),
1959 ITEM("events/names", misc,
1960 "Events that the controller can ask for with SETEVENTS."),
1961 ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
1962 PREFIX("desc/id/", dir, "Router descriptors by ID."),
1963 PREFIX("desc/name/", dir, "Router descriptors by nickname."),
1964 ITEM("desc/all-recent", dir,
1965 "All non-expired, non-superseded router descriptors."),
1966 ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
1967 PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
1968 PREFIX("net/listeners/", listeners, "Bound addresses by type"),
1969 ITEM("ns/all", networkstatus,
1970 "Brief summary of router status (v2 directory format)"),
1971 PREFIX("ns/id/", networkstatus,
1972 "Brief summary of router status by ID (v2 directory format)."),
1973 PREFIX("ns/name/", networkstatus,
1974 "Brief summary of router status by nickname (v2 directory format)."),
1975 PREFIX("ns/purpose/", networkstatus,
1976 "Brief summary of router status by purpose (v2 directory format)."),
1978 ITEM("network-status", dir,
1979 "Brief summary of router status (v1 directory format)"),
1980 ITEM("circuit-status", events, "List of current circuits originating here."),
1981 ITEM("stream-status", events,"List of current streams."),
1982 ITEM("orconn-status", events, "A list of current OR connections."),
1983 PREFIX("address-mappings/", events, NULL),
1984 DOC("address-mappings/all", "Current address mappings."),
1985 DOC("address-mappings/cache", "Current cached DNS replies."),
1986 DOC("address-mappings/config",
1987 "Current address mappings from configuration."),
1988 DOC("address-mappings/control", "Current address mappings from controller."),
1989 PREFIX("status/", events, NULL),
1990 DOC("status/circuit-established",
1991 "Whether we think client functionality is working."),
1992 DOC("status/enough-dir-info",
1993 "Whether we have enough up-to-date directory information to build "
1994 "circuits."),
1995 DOC("status/bootstrap-phase",
1996 "The last bootstrap phase status event that Tor sent."),
1997 DOC("status/clients-seen",
1998 "Breakdown of client countries seen by a bridge."),
1999 DOC("status/version/recommended", "List of currently recommended versions."),
2000 DOC("status/version/current", "Status of the current version."),
2001 DOC("status/version/num-versioning", "Number of versioning authorities."),
2002 DOC("status/version/num-concurring",
2003 "Number of versioning authorities agreeing on the status of the "
2004 "current version"),
2005 ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
2006 ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
2007 PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
2008 PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
2009 PREFIX("dir/status/", dir,
2010 "v2 networkstatus docs as retrieved from a DirPort."),
2011 ITEM("dir/status-vote/current/consensus", dir,
2012 "v3 Networkstatus consensus as retrieved from a DirPort."),
2013 PREFIX("exit-policy/default", policies,
2014 "The default value appended to the configured exit policy."),
2015 PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
2016 { NULL, NULL, NULL, 0 }
2019 /** Allocate and return a list of recognized GETINFO options. */
2020 static char *
2021 list_getinfo_options(void)
2023 int i;
2024 char *buf=NULL;
2025 smartlist_t *lines = smartlist_create();
2026 char *ans;
2027 for (i = 0; getinfo_items[i].varname; ++i) {
2028 if (!getinfo_items[i].desc)
2029 continue;
2031 tor_asprintf(&buf, "%s%s -- %s\n",
2032 getinfo_items[i].varname,
2033 getinfo_items[i].is_prefix ? "*" : "",
2034 getinfo_items[i].desc);
2035 smartlist_add(lines, buf);
2037 smartlist_sort_strings(lines);
2039 ans = smartlist_join_strings(lines, "", 0, NULL);
2040 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
2041 smartlist_free(lines);
2043 return ans;
2046 /** Lookup the 'getinfo' entry <b>question</b>, and return
2047 * the answer in <b>*answer</b> (or NULL if key not recognized).
2048 * Return 0 if success or unrecognized, or -1 if recognized but
2049 * internal error. */
2050 static int
2051 handle_getinfo_helper(control_connection_t *control_conn,
2052 const char *question, char **answer,
2053 const char **err_out)
2055 int i;
2056 *answer = NULL; /* unrecognized key by default */
2058 for (i = 0; getinfo_items[i].varname; ++i) {
2059 int match;
2060 if (getinfo_items[i].is_prefix)
2061 match = !strcmpstart(question, getinfo_items[i].varname);
2062 else
2063 match = !strcmp(question, getinfo_items[i].varname);
2064 if (match) {
2065 tor_assert(getinfo_items[i].fn);
2066 return getinfo_items[i].fn(control_conn, question, answer, err_out);
2070 return 0; /* unrecognized */
2073 /** Called when we receive a GETINFO command. Try to fetch all requested
2074 * information, and reply with information or error message. */
2075 static int
2076 handle_control_getinfo(control_connection_t *conn, uint32_t len,
2077 const char *body)
2079 smartlist_t *questions = smartlist_create();
2080 smartlist_t *answers = smartlist_create();
2081 smartlist_t *unrecognized = smartlist_create();
2082 char *msg = NULL, *ans = NULL;
2083 int i;
2084 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
2086 smartlist_split_string(questions, body, " ",
2087 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2088 SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
2089 const char *errmsg = NULL;
2090 if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
2091 if (!errmsg)
2092 errmsg = "Internal error";
2093 connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
2094 goto done;
2096 if (!ans) {
2097 smartlist_add(unrecognized, (char*)q);
2098 } else {
2099 smartlist_add(answers, tor_strdup(q));
2100 smartlist_add(answers, ans);
2102 } SMARTLIST_FOREACH_END(q);
2103 if (smartlist_len(unrecognized)) {
2104 for (i=0; i < smartlist_len(unrecognized)-1; ++i)
2105 connection_printf_to_buf(conn,
2106 "552-Unrecognized key \"%s\"\r\n",
2107 (char*)smartlist_get(unrecognized, i));
2108 connection_printf_to_buf(conn,
2109 "552 Unrecognized key \"%s\"\r\n",
2110 (char*)smartlist_get(unrecognized, i));
2111 goto done;
2114 for (i = 0; i < smartlist_len(answers); i += 2) {
2115 char *k = smartlist_get(answers, i);
2116 char *v = smartlist_get(answers, i+1);
2117 if (!strchr(v, '\n') && !strchr(v, '\r')) {
2118 connection_printf_to_buf(conn, "250-%s=", k);
2119 connection_write_str_to_buf(v, conn);
2120 connection_write_str_to_buf("\r\n", conn);
2121 } else {
2122 char *esc = NULL;
2123 size_t esc_len;
2124 esc_len = write_escaped_data(v, strlen(v), &esc);
2125 connection_printf_to_buf(conn, "250+%s=\r\n", k);
2126 connection_write_to_buf(esc, esc_len, TO_CONN(conn));
2127 tor_free(esc);
2130 connection_write_str_to_buf("250 OK\r\n", conn);
2132 done:
2133 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
2134 smartlist_free(answers);
2135 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
2136 smartlist_free(questions);
2137 smartlist_free(unrecognized);
2138 tor_free(msg);
2140 return 0;
2143 /** Given a string, convert it to a circuit purpose. */
2144 static uint8_t
2145 circuit_purpose_from_string(const char *string)
2147 if (!strcasecmpstart(string, "purpose="))
2148 string += strlen("purpose=");
2150 if (!strcasecmp(string, "general"))
2151 return CIRCUIT_PURPOSE_C_GENERAL;
2152 else if (!strcasecmp(string, "controller"))
2153 return CIRCUIT_PURPOSE_CONTROLLER;
2154 else
2155 return CIRCUIT_PURPOSE_UNKNOWN;
2158 /** Return a newly allocated smartlist containing the arguments to the command
2159 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
2160 * or if <b>max_args</b> is nonnegative and there are more than
2161 * <b>max_args</b> arguments, send a 512 error to the controller, using
2162 * <b>command</b> as the command name in the error message. */
2163 static smartlist_t *
2164 getargs_helper(const char *command, control_connection_t *conn,
2165 const char *body, int min_args, int max_args)
2167 smartlist_t *args = smartlist_create();
2168 smartlist_split_string(args, body, " ",
2169 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2170 if (smartlist_len(args) < min_args) {
2171 connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
2172 goto err;
2173 } else if (max_args >= 0 && smartlist_len(args) > max_args) {
2174 connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
2175 goto err;
2177 return args;
2178 err:
2179 SMARTLIST_FOREACH(args, char *, s, tor_free(s));
2180 smartlist_free(args);
2181 return NULL;
2184 /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
2185 * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
2186 * such element exists. */
2187 static const char *
2188 find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
2190 int i;
2191 for (i = start_at; i < smartlist_len(sl); ++i) {
2192 const char *elt = smartlist_get(sl, i);
2193 if (!strcasecmpstart(elt, prefix))
2194 return elt;
2196 return NULL;
2199 /** Helper. Return true iff s is an argument that we should treat as a
2200 * key-value pair. */
2201 static int
2202 is_keyval_pair(const char *s)
2204 /* An argument is a key-value pair if it has an =, and it isn't of the form
2205 * $fingeprint=name */
2206 return strchr(s, '=') && s[0] != '$';
2209 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
2210 * circuit, and report success or failure. */
2211 static int
2212 handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
2213 const char *body)
2215 smartlist_t *router_nicknames=NULL, *routers=NULL;
2216 origin_circuit_t *circ = NULL;
2217 int zero_circ;
2218 uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
2219 smartlist_t *args;
2220 (void) len;
2222 router_nicknames = smartlist_create();
2224 args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
2225 if (!args)
2226 goto done;
2228 zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
2230 if (zero_circ) {
2231 const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
2233 if (purp) {
2234 intended_purpose = circuit_purpose_from_string(purp);
2235 if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
2236 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
2237 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2238 smartlist_free(args);
2239 goto done;
2243 if ((smartlist_len(args) == 1) ||
2244 (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
2245 // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
2246 circ = circuit_launch_by_router(intended_purpose, NULL,
2247 CIRCLAUNCH_NEED_CAPACITY);
2248 if (!circ) {
2249 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
2250 } else {
2251 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
2252 (unsigned long)circ->global_identifier);
2254 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2255 smartlist_free(args);
2256 goto done;
2258 // "EXTENDCIRCUIT 0 router1,router2" ||
2259 // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
2262 if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
2263 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2264 (char*)smartlist_get(args, 0));
2265 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2266 smartlist_free(args);
2267 goto done;
2270 smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
2272 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2273 smartlist_free(args);
2275 routers = smartlist_create();
2276 SMARTLIST_FOREACH(router_nicknames, const char *, n,
2278 routerinfo_t *r = router_get_by_nickname(n, 1);
2279 if (!r) {
2280 connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
2281 goto done;
2283 smartlist_add(routers, r);
2285 if (!smartlist_len(routers)) {
2286 connection_write_str_to_buf("512 No router names provided\r\n", conn);
2287 goto done;
2290 if (zero_circ) {
2291 /* start a new circuit */
2292 circ = origin_circuit_init(intended_purpose, 0);
2295 /* now circ refers to something that is ready to be extended */
2296 SMARTLIST_FOREACH(routers, routerinfo_t *, r,
2298 extend_info_t *info = extend_info_from_router(r);
2299 circuit_append_new_exit(circ, info);
2300 extend_info_free(info);
2303 /* now that we've populated the cpath, start extending */
2304 if (zero_circ) {
2305 int err_reason = 0;
2306 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
2307 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2308 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
2309 goto done;
2311 } else {
2312 if (circ->_base.state == CIRCUIT_STATE_OPEN) {
2313 int err_reason = 0;
2314 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
2315 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
2316 log_info(LD_CONTROL,
2317 "send_next_onion_skin failed; circuit marked for closing.");
2318 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2319 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
2320 goto done;
2325 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
2326 (unsigned long)circ->global_identifier);
2327 if (zero_circ) /* send a 'launched' event, for completeness */
2328 control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
2329 done:
2330 SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
2331 smartlist_free(router_nicknames);
2332 smartlist_free(routers);
2333 return 0;
2336 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
2337 * circuit and it's a valid purpose, change it. */
2338 static int
2339 handle_control_setcircuitpurpose(control_connection_t *conn,
2340 uint32_t len, const char *body)
2342 origin_circuit_t *circ = NULL;
2343 uint8_t new_purpose;
2344 smartlist_t *args;
2345 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
2347 args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
2348 if (!args)
2349 goto done;
2351 if (!(circ = get_circ(smartlist_get(args,0)))) {
2352 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2353 (char*)smartlist_get(args, 0));
2354 goto done;
2358 const char *purp = find_element_starting_with(args,1,"PURPOSE=");
2359 new_purpose = circuit_purpose_from_string(purp);
2360 if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
2361 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
2362 goto done;
2366 circ->_base.purpose = new_purpose;
2367 connection_write_str_to_buf("250 OK\r\n", conn);
2369 done:
2370 if (args) {
2371 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2372 smartlist_free(args);
2374 return 0;
2377 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
2378 * stream, and report success or failure. */
2379 static int
2380 handle_control_attachstream(control_connection_t *conn, uint32_t len,
2381 const char *body)
2383 edge_connection_t *ap_conn = NULL;
2384 origin_circuit_t *circ = NULL;
2385 int zero_circ;
2386 smartlist_t *args;
2387 crypt_path_t *cpath=NULL;
2388 int hop=0, hop_line_ok=1;
2389 (void) len;
2391 args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
2392 if (!args)
2393 return 0;
2395 zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
2397 if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
2398 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2399 (char*)smartlist_get(args, 0));
2400 } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
2401 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2402 (char*)smartlist_get(args, 1));
2403 } else if (circ) {
2404 const char *hopstring = find_element_starting_with(args,2,"HOP=");
2405 if (hopstring) {
2406 hopstring += strlen("HOP=");
2407 hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
2408 &hop_line_ok, NULL);
2409 if (!hop_line_ok) { /* broken hop line */
2410 connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
2414 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2415 smartlist_free(args);
2416 if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
2417 return 0;
2419 if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT &&
2420 ap_conn->_base.state != AP_CONN_STATE_CONNECT_WAIT &&
2421 ap_conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
2422 connection_write_str_to_buf(
2423 "555 Connection is not managed by controller.\r\n",
2424 conn);
2425 return 0;
2428 /* Do we need to detach it first? */
2429 if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT) {
2430 circuit_t *tmpcirc = circuit_get_by_edge_conn(ap_conn);
2431 connection_edge_end(ap_conn, END_STREAM_REASON_TIMEOUT);
2432 /* Un-mark it as ending, since we're going to reuse it. */
2433 ap_conn->edge_has_sent_end = 0;
2434 ap_conn->end_reason = 0;
2435 if (tmpcirc)
2436 circuit_detach_stream(tmpcirc,ap_conn);
2437 ap_conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
2440 if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
2441 connection_write_str_to_buf(
2442 "551 Can't attach stream to non-open origin circuit\r\n",
2443 conn);
2444 return 0;
2446 /* Is this a single hop circuit? */
2447 if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
2448 routerinfo_t *r = NULL;
2449 char* exit_digest;
2450 if (circ->build_state &&
2451 circ->build_state->chosen_exit &&
2452 !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
2453 exit_digest = circ->build_state->chosen_exit->identity_digest;
2454 r = router_get_by_digest(exit_digest);
2456 /* Do both the client and relay allow one-hop exit circuits? */
2457 if (!r || !r->allow_single_hop_exits ||
2458 !get_options()->AllowSingleHopCircuits) {
2459 connection_write_str_to_buf(
2460 "551 Can't attach stream to this one-hop circuit.\r\n", conn);
2461 return 0;
2463 ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
2466 if (circ && hop>0) {
2467 /* find this hop in the circuit, and set cpath */
2468 cpath = circuit_get_cpath_hop(circ, hop);
2469 if (!cpath) {
2470 connection_printf_to_buf(conn,
2471 "551 Circuit doesn't have %d hops.\r\n", hop);
2472 return 0;
2475 if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
2476 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
2477 return 0;
2479 send_control_done(conn);
2480 return 0;
2483 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
2484 * descriptor, and report success or failure. */
2485 static int
2486 handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
2487 const char *body)
2489 char *desc;
2490 const char *msg=NULL;
2491 uint8_t purpose = ROUTER_PURPOSE_GENERAL;
2492 int cache = 0; /* eventually, we may switch this to 1 */
2494 char *cp = memchr(body, '\n', len);
2495 smartlist_t *args = smartlist_create();
2496 tor_assert(cp);
2497 *cp++ = '\0';
2499 smartlist_split_string(args, body, " ",
2500 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2501 SMARTLIST_FOREACH(args, char *, option,
2503 if (!strcasecmpstart(option, "purpose=")) {
2504 option += strlen("purpose=");
2505 purpose = router_purpose_from_string(option);
2506 if (purpose == ROUTER_PURPOSE_UNKNOWN) {
2507 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
2508 option);
2509 goto done;
2511 } else if (!strcasecmpstart(option, "cache=")) {
2512 option += strlen("cache=");
2513 if (!strcasecmp(option, "no"))
2514 cache = 0;
2515 else if (!strcasecmp(option, "yes"))
2516 cache = 1;
2517 else {
2518 connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
2519 option);
2520 goto done;
2522 } else { /* unrecognized argument? */
2523 connection_printf_to_buf(conn,
2524 "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
2525 goto done;
2529 read_escaped_data(cp, len-(cp-body), &desc);
2531 switch (router_load_single_router(desc, purpose, cache, &msg)) {
2532 case -1:
2533 if (!msg) msg = "Could not parse descriptor";
2534 connection_printf_to_buf(conn, "554 %s\r\n", msg);
2535 break;
2536 case 0:
2537 if (!msg) msg = "Descriptor not added";
2538 connection_printf_to_buf(conn, "251 %s\r\n",msg);
2539 break;
2540 case 1:
2541 send_control_done(conn);
2542 break;
2545 tor_free(desc);
2546 done:
2547 SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
2548 smartlist_free(args);
2549 return 0;
2552 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
2553 * address of the named AP stream, and report success or failure. */
2554 static int
2555 handle_control_redirectstream(control_connection_t *conn, uint32_t len,
2556 const char *body)
2558 edge_connection_t *ap_conn = NULL;
2559 char *new_addr = NULL;
2560 uint16_t new_port = 0;
2561 smartlist_t *args;
2562 (void) len;
2564 args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
2565 if (!args)
2566 return 0;
2568 if (!(ap_conn = get_stream(smartlist_get(args, 0)))
2569 || !ap_conn->socks_request) {
2570 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2571 (char*)smartlist_get(args, 0));
2572 } else {
2573 int ok = 1;
2574 if (smartlist_len(args) > 2) { /* they included a port too */
2575 new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
2576 10, 1, 65535, &ok, NULL);
2578 if (!ok) {
2579 connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
2580 (char*)smartlist_get(args, 2));
2581 } else {
2582 new_addr = tor_strdup(smartlist_get(args, 1));
2586 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2587 smartlist_free(args);
2588 if (!new_addr)
2589 return 0;
2591 strlcpy(ap_conn->socks_request->address, new_addr,
2592 sizeof(ap_conn->socks_request->address));
2593 if (new_port)
2594 ap_conn->socks_request->port = new_port;
2595 tor_free(new_addr);
2596 send_control_done(conn);
2597 return 0;
2600 /** Called when we get a CLOSESTREAM command; try to close the named stream
2601 * and report success or failure. */
2602 static int
2603 handle_control_closestream(control_connection_t *conn, uint32_t len,
2604 const char *body)
2606 edge_connection_t *ap_conn=NULL;
2607 uint8_t reason=0;
2608 smartlist_t *args;
2609 int ok;
2610 (void) len;
2612 args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
2613 if (!args)
2614 return 0;
2616 else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
2617 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2618 (char*)smartlist_get(args, 0));
2619 else {
2620 reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
2621 &ok, NULL);
2622 if (!ok) {
2623 connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
2624 (char*)smartlist_get(args, 1));
2625 ap_conn = NULL;
2628 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2629 smartlist_free(args);
2630 if (!ap_conn)
2631 return 0;
2633 connection_mark_unattached_ap(ap_conn, reason);
2634 send_control_done(conn);
2635 return 0;
2638 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
2639 * and report success or failure. */
2640 static int
2641 handle_control_closecircuit(control_connection_t *conn, uint32_t len,
2642 const char *body)
2644 origin_circuit_t *circ = NULL;
2645 int safe = 0;
2646 smartlist_t *args;
2647 (void) len;
2649 args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
2650 if (!args)
2651 return 0;
2653 if (!(circ=get_circ(smartlist_get(args, 0))))
2654 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2655 (char*)smartlist_get(args, 0));
2656 else {
2657 int i;
2658 for (i=1; i < smartlist_len(args); ++i) {
2659 if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
2660 safe = 1;
2661 else
2662 log_info(LD_CONTROL, "Skipping unknown option %s",
2663 (char*)smartlist_get(args,i));
2666 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2667 smartlist_free(args);
2668 if (!circ)
2669 return 0;
2671 if (!safe || !circ->p_streams) {
2672 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
2675 send_control_done(conn);
2676 return 0;
2679 /** Called when we get a RESOLVE command: start trying to resolve
2680 * the listed addresses. */
2681 static int
2682 handle_control_resolve(control_connection_t *conn, uint32_t len,
2683 const char *body)
2685 smartlist_t *args, *failed;
2686 int is_reverse = 0;
2687 (void) len; /* body is nul-terminated; it's safe to ignore the length */
2689 if (!(conn->event_mask & ((uint32_t)1L<<EVENT_ADDRMAP))) {
2690 log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
2691 "isn't listening for ADDRMAP events. It probably won't see "
2692 "the answer.");
2694 args = smartlist_create();
2695 smartlist_split_string(args, body, " ",
2696 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2698 const char *modearg = find_element_starting_with(args, 0, "mode=");
2699 if (modearg && !strcasecmp(modearg, "mode=reverse"))
2700 is_reverse = 1;
2702 failed = smartlist_create();
2703 SMARTLIST_FOREACH(args, const char *, arg, {
2704 if (!is_keyval_pair(arg)) {
2705 if (dnsserv_launch_request(arg, is_reverse)<0)
2706 smartlist_add(failed, (char*)arg);
2710 send_control_done(conn);
2711 SMARTLIST_FOREACH(failed, const char *, arg, {
2712 control_event_address_mapped(arg, arg, time(NULL),
2713 "Unable to launch resolve request");
2716 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2717 smartlist_free(args);
2718 smartlist_free(failed);
2719 return 0;
2722 /** Called when we get a PROTOCOLINFO command: send back a reply. */
2723 static int
2724 handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
2725 const char *body)
2727 const char *bad_arg = NULL;
2728 smartlist_t *args;
2729 (void)len;
2731 conn->have_sent_protocolinfo = 1;
2732 args = smartlist_create();
2733 smartlist_split_string(args, body, " ",
2734 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2735 SMARTLIST_FOREACH(args, const char *, arg, {
2736 int ok;
2737 tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
2738 if (!ok) {
2739 bad_arg = arg;
2740 break;
2743 if (bad_arg) {
2744 connection_printf_to_buf(conn, "513 No such version %s\r\n",
2745 escaped(bad_arg));
2746 /* Don't tolerate bad arguments when not authenticated. */
2747 if (!STATE_IS_OPEN(TO_CONN(conn)->state))
2748 connection_mark_for_close(TO_CONN(conn));
2749 goto done;
2750 } else {
2751 or_options_t *options = get_options();
2752 int cookies = options->CookieAuthentication;
2753 char *cfile = get_cookie_file();
2754 char *esc_cfile = esc_for_log(cfile);
2755 char *methods;
2757 int passwd = (options->HashedControlPassword != NULL ||
2758 options->HashedControlSessionPassword != NULL);
2759 smartlist_t *mlist = smartlist_create();
2760 if (cookies)
2761 smartlist_add(mlist, (char*)"COOKIE");
2762 if (passwd)
2763 smartlist_add(mlist, (char*)"HASHEDPASSWORD");
2764 if (!cookies && !passwd)
2765 smartlist_add(mlist, (char*)"NULL");
2766 methods = smartlist_join_strings(mlist, ",", 0, NULL);
2767 smartlist_free(mlist);
2770 connection_printf_to_buf(conn,
2771 "250-PROTOCOLINFO 1\r\n"
2772 "250-AUTH METHODS=%s%s%s\r\n"
2773 "250-VERSION Tor=%s\r\n"
2774 "250 OK\r\n",
2775 methods,
2776 cookies?" COOKIEFILE=":"",
2777 cookies?esc_cfile:"",
2778 escaped(VERSION));
2779 tor_free(methods);
2780 tor_free(cfile);
2781 tor_free(esc_cfile);
2783 done:
2784 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2785 smartlist_free(args);
2786 return 0;
2789 /** Called when we get a USEFEATURE command: parse the feature list, and
2790 * set up the control_connection's options properly. */
2791 static int
2792 handle_control_usefeature(control_connection_t *conn,
2793 uint32_t len,
2794 const char *body)
2796 smartlist_t *args;
2797 int bad = 0;
2798 (void) len; /* body is nul-terminated; it's safe to ignore the length */
2799 args = smartlist_create();
2800 smartlist_split_string(args, body, " ",
2801 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2802 SMARTLIST_FOREACH(args, const char *, arg, {
2803 if (!strcasecmp(arg, "VERBOSE_NAMES"))
2805 else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
2807 else {
2808 connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
2809 arg);
2810 bad = 1;
2811 break;
2815 if (!bad) {
2816 send_control_done(conn);
2819 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2820 smartlist_free(args);
2821 return 0;
2824 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
2826 connection_control_finished_flushing(control_connection_t *conn)
2828 tor_assert(conn);
2830 connection_stop_writing(TO_CONN(conn));
2831 return 0;
2834 /** Called when <b>conn</b> has gotten its socket closed. */
2836 connection_control_reached_eof(control_connection_t *conn)
2838 tor_assert(conn);
2840 log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
2841 connection_mark_for_close(TO_CONN(conn));
2842 return 0;
2845 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
2846 * stage of the protocol. */
2847 static int
2848 is_valid_initial_command(control_connection_t *conn, const char *cmd)
2850 if (conn->_base.state == CONTROL_CONN_STATE_OPEN)
2851 return 1;
2852 if (!strcasecmp(cmd, "PROTOCOLINFO"))
2853 return !conn->have_sent_protocolinfo;
2854 if (!strcasecmp(cmd, "AUTHENTICATE") ||
2855 !strcasecmp(cmd, "QUIT"))
2856 return 1;
2857 return 0;
2860 /** Do not accept any control command of more than 1MB in length. Anything
2861 * that needs to be anywhere near this long probably means that one of our
2862 * interfaces is broken. */
2863 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
2865 /** Called when data has arrived on a v1 control connection: Try to fetch
2866 * commands from conn->inbuf, and execute them.
2869 connection_control_process_inbuf(control_connection_t *conn)
2871 size_t data_len;
2872 uint32_t cmd_data_len;
2873 int cmd_len;
2874 char *args;
2876 tor_assert(conn);
2877 tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN ||
2878 conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH);
2880 if (!conn->incoming_cmd) {
2881 conn->incoming_cmd = tor_malloc(1024);
2882 conn->incoming_cmd_len = 1024;
2883 conn->incoming_cmd_cur_len = 0;
2886 if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
2887 peek_buf_has_control0_command(conn->_base.inbuf)) {
2888 /* Detect v0 commands and send a "no more v0" message. */
2889 size_t body_len;
2890 char buf[128];
2891 set_uint16(buf+2, htons(0x0000)); /* type == error */
2892 set_uint16(buf+4, htons(0x0001)); /* code == internal error */
2893 strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
2894 "and later; upgrade your controller.",
2895 sizeof(buf)-6);
2896 body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
2897 set_uint16(buf+0, htons(body_len));
2898 connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
2899 connection_mark_for_close(TO_CONN(conn));
2900 conn->_base.hold_open_until_flushed = 1;
2901 return 0;
2904 again:
2905 while (1) {
2906 size_t last_idx;
2907 int r;
2908 /* First, fetch a line. */
2909 do {
2910 data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
2911 r = fetch_from_buf_line(conn->_base.inbuf,
2912 conn->incoming_cmd+conn->incoming_cmd_cur_len,
2913 &data_len);
2914 if (r == 0)
2915 /* Line not all here yet. Wait. */
2916 return 0;
2917 else if (r == -1) {
2918 if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
2919 connection_write_str_to_buf("500 Line too long.\r\n", conn);
2920 connection_stop_reading(TO_CONN(conn));
2921 connection_mark_for_close(TO_CONN(conn));
2922 conn->_base.hold_open_until_flushed = 1;
2924 while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
2925 conn->incoming_cmd_len *= 2;
2926 conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
2927 conn->incoming_cmd_len);
2929 } while (r != 1);
2931 tor_assert(data_len);
2933 last_idx = conn->incoming_cmd_cur_len;
2934 conn->incoming_cmd_cur_len += (int)data_len;
2936 /* We have appended a line to incoming_cmd. Is the command done? */
2937 if (last_idx == 0 && *conn->incoming_cmd != '+')
2938 /* One line command, didn't start with '+'. */
2939 break;
2940 /* XXXX this code duplication is kind of dumb. */
2941 if (last_idx+3 == conn->incoming_cmd_cur_len &&
2942 tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
2943 /* Just appended ".\r\n"; we're done. Remove it. */
2944 conn->incoming_cmd[last_idx] = '\0';
2945 conn->incoming_cmd_cur_len -= 3;
2946 break;
2947 } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
2948 tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
2949 /* Just appended ".\n"; we're done. Remove it. */
2950 conn->incoming_cmd[last_idx] = '\0';
2951 conn->incoming_cmd_cur_len -= 2;
2952 break;
2954 /* Otherwise, read another line. */
2956 data_len = conn->incoming_cmd_cur_len;
2957 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
2958 * recognize it.
2960 cmd_len = 0;
2961 while ((size_t)cmd_len < data_len
2962 && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
2963 ++cmd_len;
2965 conn->incoming_cmd[cmd_len]='\0';
2966 args = conn->incoming_cmd+cmd_len+1;
2967 tor_assert(data_len>(size_t)cmd_len);
2968 data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
2969 while (*args == ' ' || *args == '\t') {
2970 ++args;
2971 --data_len;
2974 /* If the connection is already closing, ignore further commands */
2975 if (TO_CONN(conn)->marked_for_close) {
2976 return 0;
2979 /* Otherwise, Quit is always valid. */
2980 if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
2981 connection_write_str_to_buf("250 closing connection\r\n", conn);
2982 connection_mark_for_close(TO_CONN(conn));
2983 conn->_base.hold_open_until_flushed = 1;
2984 return 0;
2987 if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
2988 !is_valid_initial_command(conn, conn->incoming_cmd)) {
2989 connection_write_str_to_buf("514 Authentication required.\r\n", conn);
2990 connection_mark_for_close(TO_CONN(conn));
2991 return 0;
2994 if (data_len >= UINT32_MAX) {
2995 connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
2996 connection_mark_for_close(TO_CONN(conn));
2997 return 0;
3000 cmd_data_len = (uint32_t)data_len;
3001 if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
3002 if (handle_control_setconf(conn, cmd_data_len, args))
3003 return -1;
3004 } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
3005 if (handle_control_resetconf(conn, cmd_data_len, args))
3006 return -1;
3007 } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
3008 if (handle_control_getconf(conn, cmd_data_len, args))
3009 return -1;
3010 } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
3011 if (handle_control_loadconf(conn, cmd_data_len, args))
3012 return -1;
3013 } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
3014 if (handle_control_setevents(conn, cmd_data_len, args))
3015 return -1;
3016 } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
3017 if (handle_control_authenticate(conn, cmd_data_len, args))
3018 return -1;
3019 } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
3020 if (handle_control_saveconf(conn, cmd_data_len, args))
3021 return -1;
3022 } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
3023 if (handle_control_signal(conn, cmd_data_len, args))
3024 return -1;
3025 } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
3026 if (handle_control_mapaddress(conn, cmd_data_len, args))
3027 return -1;
3028 } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
3029 if (handle_control_getinfo(conn, cmd_data_len, args))
3030 return -1;
3031 } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
3032 if (handle_control_extendcircuit(conn, cmd_data_len, args))
3033 return -1;
3034 } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
3035 if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
3036 return -1;
3037 } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
3038 connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
3039 } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
3040 if (handle_control_attachstream(conn, cmd_data_len, args))
3041 return -1;
3042 } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
3043 if (handle_control_postdescriptor(conn, cmd_data_len, args))
3044 return -1;
3045 } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
3046 if (handle_control_redirectstream(conn, cmd_data_len, args))
3047 return -1;
3048 } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
3049 if (handle_control_closestream(conn, cmd_data_len, args))
3050 return -1;
3051 } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
3052 if (handle_control_closecircuit(conn, cmd_data_len, args))
3053 return -1;
3054 } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
3055 if (handle_control_usefeature(conn, cmd_data_len, args))
3056 return -1;
3057 } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
3058 if (handle_control_resolve(conn, cmd_data_len, args))
3059 return -1;
3060 } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
3061 if (handle_control_protocolinfo(conn, cmd_data_len, args))
3062 return -1;
3063 } else {
3064 connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
3065 conn->incoming_cmd);
3068 conn->incoming_cmd_cur_len = 0;
3069 goto again;
3072 /** Something has happened to circuit <b>circ</b>: tell any interested
3073 * control connections. */
3075 control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
3076 int reason_code)
3078 const char *status;
3079 char extended_buf[96];
3080 int providing_reason=0;
3081 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
3082 return 0;
3083 tor_assert(circ);
3085 switch (tp)
3087 case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
3088 case CIRC_EVENT_BUILT: status = "BUILT"; break;
3089 case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
3090 case CIRC_EVENT_FAILED: status = "FAILED"; break;
3091 case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
3092 default:
3093 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3094 return 0;
3097 tor_snprintf(extended_buf, sizeof(extended_buf), "PURPOSE=%s",
3098 circuit_purpose_to_controller_string(circ->_base.purpose));
3100 if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
3101 const char *reason_str = circuit_end_reason_to_control_string(reason_code);
3102 char *reason = NULL;
3103 size_t n=strlen(extended_buf);
3104 providing_reason=1;
3105 if (!reason_str) {
3106 reason = tor_malloc(16);
3107 tor_snprintf(reason, 16, "UNKNOWN_%d", reason_code);
3108 reason_str = reason;
3110 if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
3111 tor_snprintf(extended_buf+n, sizeof(extended_buf)-n,
3112 " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
3113 } else {
3114 tor_snprintf(extended_buf+n, sizeof(extended_buf)-n,
3115 " REASON=%s", reason_str);
3117 tor_free(reason);
3121 char *vpath = circuit_list_path_for_controller(circ);
3122 const char *sp = strlen(vpath) ? " " : "";
3123 send_control_event(EVENT_CIRCUIT_STATUS, ALL_FORMATS,
3124 "650 CIRC %lu %s%s%s %s\r\n",
3125 (unsigned long)circ->global_identifier,
3126 status, sp, vpath, extended_buf);
3127 tor_free(vpath);
3130 return 0;
3133 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
3134 * <b>buf</b>, determine the address:port combination requested on
3135 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
3136 * failure. */
3137 static int
3138 write_stream_target_to_buf(edge_connection_t *conn, char *buf, size_t len)
3140 char buf2[256];
3141 if (conn->chosen_exit_name)
3142 if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
3143 return -1;
3144 if (!conn->socks_request)
3145 return -1;
3146 if (tor_snprintf(buf, len, "%s%s%s:%d",
3147 conn->socks_request->address,
3148 conn->chosen_exit_name ? buf2 : "",
3149 !conn->chosen_exit_name &&
3150 connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
3151 conn->socks_request->port)<0)
3152 return -1;
3153 return 0;
3156 /** Something has happened to the stream associated with AP connection
3157 * <b>conn</b>: tell any interested control connections. */
3159 control_event_stream_status(edge_connection_t *conn, stream_status_event_t tp,
3160 int reason_code)
3162 char reason_buf[64];
3163 char addrport_buf[64];
3164 const char *status;
3165 circuit_t *circ;
3166 origin_circuit_t *origin_circ = NULL;
3167 char buf[256];
3168 const char *purpose = "";
3169 tor_assert(conn->socks_request);
3171 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
3172 return 0;
3174 if (tp == STREAM_EVENT_CLOSED &&
3175 (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
3176 return 0;
3178 write_stream_target_to_buf(conn, buf, sizeof(buf));
3180 reason_buf[0] = '\0';
3181 switch (tp)
3183 case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
3184 case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
3185 case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
3186 case STREAM_EVENT_FAILED: status = "FAILED"; break;
3187 case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
3188 case STREAM_EVENT_NEW: status = "NEW"; break;
3189 case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
3190 case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
3191 case STREAM_EVENT_REMAP: status = "REMAP"; break;
3192 default:
3193 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3194 return 0;
3196 if (reason_code && (tp == STREAM_EVENT_FAILED ||
3197 tp == STREAM_EVENT_CLOSED ||
3198 tp == STREAM_EVENT_FAILED_RETRIABLE)) {
3199 const char *reason_str = stream_end_reason_to_control_string(reason_code);
3200 char *r = NULL;
3201 if (!reason_str) {
3202 r = tor_malloc(16);
3203 tor_snprintf(r, 16, " UNKNOWN_%d", reason_code);
3204 reason_str = r;
3206 if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
3207 tor_snprintf(reason_buf, sizeof(reason_buf),
3208 " REASON=END REMOTE_REASON=%s", reason_str);
3209 else
3210 tor_snprintf(reason_buf, sizeof(reason_buf),
3211 " REASON=%s", reason_str);
3212 tor_free(r);
3213 } else if (reason_code && tp == STREAM_EVENT_REMAP) {
3214 switch (reason_code) {
3215 case REMAP_STREAM_SOURCE_CACHE:
3216 strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
3217 break;
3218 case REMAP_STREAM_SOURCE_EXIT:
3219 strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
3220 break;
3221 default:
3222 tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
3223 reason_code);
3224 /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
3225 break;
3229 if (tp == STREAM_EVENT_NEW) {
3230 tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
3231 TO_CONN(conn)->address, TO_CONN(conn)->port );
3232 } else {
3233 addrport_buf[0] = '\0';
3236 if (tp == STREAM_EVENT_NEW_RESOLVE) {
3237 purpose = " PURPOSE=DNS_REQUEST";
3238 } else if (tp == STREAM_EVENT_NEW) {
3239 if (conn->is_dns_request ||
3240 (conn->socks_request &&
3241 SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)))
3242 purpose = " PURPOSE=DNS_REQUEST";
3243 else if (conn->use_begindir) {
3244 connection_t *linked = TO_CONN(conn)->linked_conn;
3245 int linked_dir_purpose = -1;
3246 if (linked && linked->type == CONN_TYPE_DIR)
3247 linked_dir_purpose = linked->purpose;
3248 if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
3249 purpose = " PURPOSE=DIR_UPLOAD";
3250 else
3251 purpose = " PURPOSE=DIR_FETCH";
3252 } else
3253 purpose = " PURPOSE=USER";
3256 circ = circuit_get_by_edge_conn(conn);
3257 if (circ && CIRCUIT_IS_ORIGIN(circ))
3258 origin_circ = TO_ORIGIN_CIRCUIT(circ);
3259 send_control_event(EVENT_STREAM_STATUS, ALL_FORMATS,
3260 "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
3261 U64_PRINTF_ARG(conn->_base.global_identifier), status,
3262 origin_circ?
3263 (unsigned long)origin_circ->global_identifier : 0ul,
3264 buf, reason_buf, addrport_buf, purpose);
3266 /* XXX need to specify its intended exit, etc? */
3268 return 0;
3271 /** Figure out the best name for the target router of an OR connection
3272 * <b>conn</b>, and write it into the <b>len</b>-character buffer
3273 * <b>name</b>. */
3274 static void
3275 orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
3277 routerinfo_t *ri = router_get_by_digest(conn->identity_digest);
3278 if (ri) {
3279 tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
3280 router_get_verbose_nickname(name, ri);
3281 } else if (! tor_digest_is_zero(conn->identity_digest)) {
3282 name[0] = '$';
3283 base16_encode(name+1, len-1, conn->identity_digest,
3284 DIGEST_LEN);
3285 } else {
3286 tor_snprintf(name, len, "%s:%d",
3287 conn->_base.address, conn->_base.port);
3291 /** Called when the status of an OR connection <b>conn</b> changes: tell any
3292 * interested control connections. <b>tp</b> is the new status for the
3293 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
3294 * may be the reason why.
3297 control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
3298 int reason)
3300 int ncircs = 0;
3301 const char *status;
3302 char name[128];
3303 char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
3305 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
3306 return 0;
3308 switch (tp)
3310 case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
3311 case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
3312 case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
3313 case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
3314 case OR_CONN_EVENT_NEW: status = "NEW"; break;
3315 default:
3316 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3317 return 0;
3319 ncircs = circuit_count_pending_on_or_conn(conn);
3320 ncircs += conn->n_circuits;
3321 if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
3322 tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
3323 reason ? " " : "", ncircs);
3326 orconn_target_get_name(name, sizeof(name), conn);
3327 send_control_event(EVENT_OR_CONN_STATUS, ALL_FORMATS,
3328 "650 ORCONN %s %s %s%s%s\r\n",
3329 name, status,
3330 reason ? "REASON=" : "",
3331 orconn_end_reason_to_control_string(reason),
3332 ncircs_buf);
3334 return 0;
3338 * Print out STREAM_BW event for a single conn
3341 control_event_stream_bandwidth(edge_connection_t *edge_conn)
3343 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
3344 if (!edge_conn->n_read && !edge_conn->n_written)
3345 return 0;
3347 send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
3348 "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
3349 U64_PRINTF_ARG(edge_conn->_base.global_identifier),
3350 (unsigned long)edge_conn->n_read,
3351 (unsigned long)edge_conn->n_written);
3353 edge_conn->n_written = edge_conn->n_read = 0;
3356 return 0;
3359 /** A second or more has elapsed: tell any interested control
3360 * connections how much bandwidth streams have used. */
3362 control_event_stream_bandwidth_used(void)
3364 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
3365 smartlist_t *conns = get_connection_array();
3366 edge_connection_t *edge_conn;
3368 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
3370 if (conn->type != CONN_TYPE_AP)
3371 continue;
3372 edge_conn = TO_EDGE_CONN(conn);
3373 if (!edge_conn->n_read && !edge_conn->n_written)
3374 continue;
3376 send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
3377 "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
3378 U64_PRINTF_ARG(edge_conn->_base.global_identifier),
3379 (unsigned long)edge_conn->n_read,
3380 (unsigned long)edge_conn->n_written);
3382 edge_conn->n_written = edge_conn->n_read = 0;
3384 SMARTLIST_FOREACH_END(conn);
3387 return 0;
3390 /** A second or more has elapsed: tell any interested control
3391 * connections how much bandwidth we used. */
3393 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
3395 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
3396 send_control_event(EVENT_BANDWIDTH_USED, ALL_FORMATS,
3397 "650 BW %lu %lu\r\n",
3398 (unsigned long)n_read,
3399 (unsigned long)n_written);
3402 return 0;
3405 /** Called when we are sending a log message to the controllers: suspend
3406 * sending further log messages to the controllers until we're done. Used by
3407 * CONN_LOG_PROTECT. */
3408 void
3409 disable_control_logging(void)
3411 ++disable_log_messages;
3414 /** We're done sending a log message to the controllers: re-enable controller
3415 * logging. Used by CONN_LOG_PROTECT. */
3416 void
3417 enable_control_logging(void)
3419 if (--disable_log_messages < 0)
3420 tor_assert(0);
3423 /** We got a log message: tell any interested control connections. */
3424 void
3425 control_event_logmsg(int severity, uint32_t domain, const char *msg)
3427 int event;
3429 /* Don't even think of trying to add stuff to a buffer from a cpuworker
3430 * thread. */
3431 if (! in_main_thread())
3432 return;
3434 if (disable_log_messages)
3435 return;
3437 if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
3438 severity <= LOG_NOTICE) {
3439 char *esc = esc_for_log(msg);
3440 ++disable_log_messages;
3441 control_event_general_status(severity, "BUG REASON=\"%s\"", esc);
3442 --disable_log_messages;
3443 tor_free(esc);
3446 event = log_severity_to_event(severity);
3447 if (event >= 0 && EVENT_IS_INTERESTING(event)) {
3448 char *b = NULL;
3449 const char *s;
3450 if (strchr(msg, '\n')) {
3451 char *cp;
3452 b = tor_strdup(msg);
3453 for (cp = b; *cp; ++cp)
3454 if (*cp == '\r' || *cp == '\n')
3455 *cp = ' ';
3457 switch (severity) {
3458 case LOG_DEBUG: s = "DEBUG"; break;
3459 case LOG_INFO: s = "INFO"; break;
3460 case LOG_NOTICE: s = "NOTICE"; break;
3461 case LOG_WARN: s = "WARN"; break;
3462 case LOG_ERR: s = "ERR"; break;
3463 default: s = "UnknownLogSeverity"; break;
3465 ++disable_log_messages;
3466 send_control_event(event, ALL_FORMATS, "650 %s %s\r\n", s, b?b:msg);
3467 --disable_log_messages;
3468 tor_free(b);
3472 /** Called whenever we receive new router descriptors: tell any
3473 * interested control connections. <b>routers</b> is a list of
3474 * routerinfo_t's.
3477 control_event_descriptors_changed(smartlist_t *routers)
3479 char *msg;
3481 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
3482 return 0;
3485 smartlist_t *names = smartlist_create();
3486 char *ids;
3487 size_t names_len;
3488 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
3489 char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
3490 router_get_verbose_nickname(b, ri);
3491 smartlist_add(names, b);
3493 ids = smartlist_join_strings(names, " ", 0, &names_len);
3494 names_len = strlen(ids)+32;
3495 msg = tor_malloc(names_len);
3496 tor_snprintf(msg, names_len, "650 NEWDESC %s\r\n", ids);
3497 send_control_event_string(EVENT_NEW_DESC, ALL_FORMATS, msg);
3498 tor_free(ids);
3499 tor_free(msg);
3500 SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
3501 smartlist_free(names);
3503 return 0;
3506 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
3507 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
3508 * <b>error</b> is non-NULL, it is an error code describing the failure
3509 * mode of the mapping.
3512 control_event_address_mapped(const char *from, const char *to, time_t expires,
3513 const char *error)
3515 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
3516 return 0;
3518 if (expires < 3 || expires == TIME_MAX)
3519 send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
3520 "650 ADDRMAP %s %s NEVER %s\r\n", from, to,
3521 error?error:"");
3522 else {
3523 char buf[ISO_TIME_LEN+1];
3524 char buf2[ISO_TIME_LEN+1];
3525 format_local_iso_time(buf,expires);
3526 format_iso_time(buf2,expires);
3527 send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
3528 "650 ADDRMAP %s %s \"%s\""
3529 " %s%sEXPIRES=\"%s\"\r\n",
3530 from, to, buf,
3531 error?error:"", error?" ":"",
3532 buf2);
3535 return 0;
3538 /** The authoritative dirserver has received a new descriptor that
3539 * has passed basic syntax checks and is properly self-signed.
3541 * Notify any interested party of the new descriptor and what has
3542 * been done with it, and also optionally give an explanation/reason. */
3544 control_event_or_authdir_new_descriptor(const char *action,
3545 const char *desc, size_t desclen,
3546 const char *msg)
3548 char firstline[1024];
3549 char *buf;
3550 size_t totallen;
3551 char *esc = NULL;
3552 size_t esclen;
3554 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
3555 return 0;
3557 tor_snprintf(firstline, sizeof(firstline),
3558 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
3559 action,
3560 msg ? msg : "");
3562 /* Escape the server descriptor properly */
3563 esclen = write_escaped_data(desc, desclen, &esc);
3565 totallen = strlen(firstline) + esclen + 1;
3566 buf = tor_malloc(totallen);
3567 strlcpy(buf, firstline, totallen);
3568 strlcpy(buf+strlen(firstline), esc, totallen);
3569 send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
3570 buf);
3571 send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
3572 "650 OK\r\n");
3573 tor_free(esc);
3574 tor_free(buf);
3576 return 0;
3579 /** Helper function for NS-style events. Constructs and sends an event
3580 * of type <b>event</b> with string <b>event_string</b> out of the set of
3581 * networkstatuses <b>statuses</b>. Currently it is used for NS events
3582 * and NEWCONSENSUS events. */
3583 static int
3584 control_event_networkstatus_changed_helper(smartlist_t *statuses,
3585 uint16_t event,
3586 const char *event_string)
3588 smartlist_t *strs;
3589 char *s, *esc = NULL;
3590 if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
3591 return 0;
3593 strs = smartlist_create();
3594 smartlist_add(strs, tor_strdup("650+"));
3595 smartlist_add(strs, tor_strdup(event_string));
3596 smartlist_add(strs, tor_strdup("\r\n"));
3597 SMARTLIST_FOREACH(statuses, routerstatus_t *, rs,
3599 s = networkstatus_getinfo_helper_single(rs);
3600 if (!s) continue;
3601 smartlist_add(strs, s);
3604 s = smartlist_join_strings(strs, "", 0, NULL);
3605 write_escaped_data(s, strlen(s), &esc);
3606 SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
3607 smartlist_free(strs);
3608 tor_free(s);
3609 send_control_event_string(event, ALL_FORMATS, esc);
3610 send_control_event_string(event, ALL_FORMATS,
3611 "650 OK\r\n");
3613 tor_free(esc);
3614 return 0;
3617 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
3618 * an NS event to any controller that cares. */
3620 control_event_networkstatus_changed(smartlist_t *statuses)
3622 return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
3625 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
3626 * event consisting of an NS-style line for each relay in the consensus. */
3628 control_event_newconsensus(const networkstatus_t *consensus)
3630 if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
3631 return 0;
3632 return control_event_networkstatus_changed_helper(
3633 consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
3636 /** Called when we compute a new circuitbuildtimeout */
3638 control_event_buildtimeout_set(const circuit_build_times_t *cbt,
3639 buildtimeout_set_event_t type)
3641 const char *type_string = NULL;
3642 double qnt = circuit_build_times_quantile_cutoff();
3644 if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
3645 return 0;
3647 switch (type) {
3648 case BUILDTIMEOUT_SET_EVENT_COMPUTED:
3649 type_string = "COMPUTED";
3650 break;
3651 case BUILDTIMEOUT_SET_EVENT_RESET:
3652 type_string = "RESET";
3653 qnt = 1.0;
3654 break;
3655 case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
3656 type_string = "SUSPENDED";
3657 qnt = 1.0;
3658 break;
3659 case BUILDTIMEOUT_SET_EVENT_DISCARD:
3660 type_string = "DISCARD";
3661 qnt = 1.0;
3662 break;
3663 case BUILDTIMEOUT_SET_EVENT_RESUME:
3664 type_string = "RESUME";
3665 break;
3666 default:
3667 type_string = "UNKNOWN";
3668 break;
3671 send_control_event(EVENT_BUILDTIMEOUT_SET, ALL_FORMATS,
3672 "650 BUILDTIMEOUT_SET %s TOTAL_TIMES=%lu "
3673 "TIMEOUT_MS=%lu XM=%lu ALPHA=%lf CUTOFF_QUANTILE=%lf "
3674 "TIMEOUT_RATE=%lf CLOSE_MS=%lu CLOSE_RATE=%lf\r\n",
3675 type_string, (unsigned long)cbt->total_build_times,
3676 (unsigned long)cbt->timeout_ms,
3677 (unsigned long)cbt->Xm, cbt->alpha, qnt,
3678 circuit_build_times_timeout_rate(cbt),
3679 (unsigned long)cbt->close_ms,
3680 circuit_build_times_close_rate(cbt));
3682 return 0;
3685 /** Called when a single local_routerstatus_t has changed: Sends an NS event
3686 * to any controller that cares. */
3688 control_event_networkstatus_changed_single(routerstatus_t *rs)
3690 smartlist_t *statuses;
3691 int r;
3693 if (!EVENT_IS_INTERESTING(EVENT_NS))
3694 return 0;
3696 statuses = smartlist_create();
3697 smartlist_add(statuses, rs);
3698 r = control_event_networkstatus_changed(statuses);
3699 smartlist_free(statuses);
3700 return r;
3703 /** Our own router descriptor has changed; tell any controllers that care.
3706 control_event_my_descriptor_changed(void)
3708 send_control_event(EVENT_DESCCHANGED, ALL_FORMATS, "650 DESCCHANGED\r\n");
3709 return 0;
3712 /** Helper: sends a status event where <b>type</b> is one of
3713 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
3714 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
3715 * string corresponding to <b>args</b>. */
3716 static int
3717 control_event_status(int type, int severity, const char *format, va_list args)
3719 char format_buf[160];
3720 const char *status, *sev;
3722 switch (type) {
3723 case EVENT_STATUS_GENERAL:
3724 status = "STATUS_GENERAL";
3725 break;
3726 case EVENT_STATUS_CLIENT:
3727 status = "STATUS_CLIENT";
3728 break;
3729 case EVENT_STATUS_SERVER:
3730 status = "STATUS_SERVER";
3731 break;
3732 default:
3733 log_warn(LD_BUG, "Unrecognized status type %d", type);
3734 return -1;
3736 switch (severity) {
3737 case LOG_NOTICE:
3738 sev = "NOTICE";
3739 break;
3740 case LOG_WARN:
3741 sev = "WARN";
3742 break;
3743 case LOG_ERR:
3744 sev = "ERR";
3745 break;
3746 default:
3747 log_warn(LD_BUG, "Unrecognized status severity %d", severity);
3748 return -1;
3750 if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s %s\r\n",
3751 status, sev, format)<0) {
3752 log_warn(LD_BUG, "Format string too long.");
3753 return -1;
3756 send_control_event_impl(type, ALL_FORMATS, format_buf, args);
3757 return 0;
3760 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
3761 * by formatting the arguments using the printf-style <b>format</b>. */
3763 control_event_general_status(int severity, const char *format, ...)
3765 va_list ap;
3766 int r;
3767 if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
3768 return 0;
3770 va_start(ap, format);
3771 r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
3772 va_end(ap);
3773 return r;
3776 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
3777 * by formatting the arguments using the printf-style <b>format</b>. */
3779 control_event_client_status(int severity, const char *format, ...)
3781 va_list ap;
3782 int r;
3783 if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
3784 return 0;
3786 va_start(ap, format);
3787 r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
3788 va_end(ap);
3789 return r;
3792 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
3793 * by formatting the arguments using the printf-style <b>format</b>. */
3795 control_event_server_status(int severity, const char *format, ...)
3797 va_list ap;
3798 int r;
3799 if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
3800 return 0;
3802 va_start(ap, format);
3803 r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
3804 va_end(ap);
3805 return r;
3808 /** Called when the status of an entry guard with the given <b>nickname</b>
3809 * and identity <b>digest</b> has changed to <b>status</b>: tells any
3810 * controllers that care. */
3812 control_event_guard(const char *nickname, const char *digest,
3813 const char *status)
3815 char hbuf[HEX_DIGEST_LEN+1];
3816 base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
3817 if (!EVENT_IS_INTERESTING(EVENT_GUARD))
3818 return 0;
3821 char buf[MAX_VERBOSE_NICKNAME_LEN+1];
3822 routerinfo_t *ri = router_get_by_digest(digest);
3823 if (ri) {
3824 router_get_verbose_nickname(buf, ri);
3825 } else {
3826 tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
3828 send_control_event(EVENT_GUARD, ALL_FORMATS,
3829 "650 GUARD ENTRY %s %s\r\n", buf, status);
3831 return 0;
3834 /** Helper: Return a newly allocated string containing a path to the
3835 * file where we store our authentication cookie. */
3836 static char *
3837 get_cookie_file(void)
3839 or_options_t *options = get_options();
3840 if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
3841 return tor_strdup(options->CookieAuthFile);
3842 } else {
3843 return get_datadir_fname("control_auth_cookie");
3847 /** Choose a random authentication cookie and write it to disk.
3848 * Anybody who can read the cookie from disk will be considered
3849 * authorized to use the control connection. Return -1 if we can't
3850 * write the file, or 0 on success. */
3852 init_cookie_authentication(int enabled)
3854 char *fname;
3855 if (!enabled) {
3856 authentication_cookie_is_set = 0;
3857 return 0;
3860 /* We don't want to generate a new cookie every time we call
3861 * options_act(). One should be enough. */
3862 if (authentication_cookie_is_set)
3863 return 0; /* all set */
3865 fname = get_cookie_file();
3866 crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
3867 authentication_cookie_is_set = 1;
3868 if (write_bytes_to_file(fname, authentication_cookie,
3869 AUTHENTICATION_COOKIE_LEN, 1)) {
3870 log_warn(LD_FS,"Error writing authentication cookie to %s.",
3871 escaped(fname));
3872 tor_free(fname);
3873 return -1;
3875 #ifndef MS_WINDOWS
3876 if (get_options()->CookieAuthFileGroupReadable) {
3877 if (chmod(fname, 0640)) {
3878 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
3881 #endif
3883 tor_free(fname);
3884 return 0;
3887 /** Convert the name of a bootstrapping phase <b>s</b> into strings
3888 * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
3889 static int
3890 bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
3891 const char **summary)
3893 switch (s) {
3894 case BOOTSTRAP_STATUS_UNDEF:
3895 *tag = "undef";
3896 *summary = "Undefined";
3897 break;
3898 case BOOTSTRAP_STATUS_STARTING:
3899 *tag = "starting";
3900 *summary = "Starting";
3901 break;
3902 case BOOTSTRAP_STATUS_CONN_DIR:
3903 *tag = "conn_dir";
3904 *summary = "Connecting to directory server";
3905 break;
3906 case BOOTSTRAP_STATUS_HANDSHAKE:
3907 *tag = "status_handshake";
3908 *summary = "Finishing handshake";
3909 break;
3910 case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
3911 *tag = "handshake_dir";
3912 *summary = "Finishing handshake with directory server";
3913 break;
3914 case BOOTSTRAP_STATUS_ONEHOP_CREATE:
3915 *tag = "onehop_create";
3916 *summary = "Establishing an encrypted directory connection";
3917 break;
3918 case BOOTSTRAP_STATUS_REQUESTING_STATUS:
3919 *tag = "requesting_status";
3920 *summary = "Asking for networkstatus consensus";
3921 break;
3922 case BOOTSTRAP_STATUS_LOADING_STATUS:
3923 *tag = "loading_status";
3924 *summary = "Loading networkstatus consensus";
3925 break;
3926 case BOOTSTRAP_STATUS_LOADING_KEYS:
3927 *tag = "loading_keys";
3928 *summary = "Loading authority key certs";
3929 break;
3930 case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
3931 *tag = "requesting_descriptors";
3932 *summary = "Asking for relay descriptors";
3933 break;
3934 case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
3935 *tag = "loading_descriptors";
3936 *summary = "Loading relay descriptors";
3937 break;
3938 case BOOTSTRAP_STATUS_CONN_OR:
3939 *tag = "conn_or";
3940 *summary = "Connecting to the Tor network";
3941 break;
3942 case BOOTSTRAP_STATUS_HANDSHAKE_OR:
3943 *tag = "handshake_or";
3944 *summary = "Finishing handshake with first hop";
3945 break;
3946 case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
3947 *tag = "circuit_create";
3948 *summary = "Establishing a Tor circuit";
3949 break;
3950 case BOOTSTRAP_STATUS_DONE:
3951 *tag = "done";
3952 *summary = "Done";
3953 break;
3954 default:
3955 // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
3956 *tag = *summary = "unknown";
3957 return -1;
3959 return 0;
3962 /** What percentage through the bootstrap process are we? We remember
3963 * this so we can avoid sending redundant bootstrap status events, and
3964 * so we can guess context for the bootstrap messages which are
3965 * ambiguous. It starts at 'undef', but gets set to 'starting' while
3966 * Tor initializes. */
3967 static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
3969 /** How many problems have we had getting to the next bootstrapping phase?
3970 * These include failure to establish a connection to a Tor relay,
3971 * failures to finish the TLS handshake, failures to validate the
3972 * consensus document, etc. */
3973 static int bootstrap_problems = 0;
3975 /* We only tell the controller once we've hit a threshold of problems
3976 * for the current phase. */
3977 #define BOOTSTRAP_PROBLEM_THRESHOLD 10
3979 /** Called when Tor has made progress at bootstrapping its directory
3980 * information and initial circuits.
3982 * <b>status</b> is the new status, that is, what task we will be doing
3983 * next. <b>progress</b> is zero if we just started this task, else it
3984 * represents progress on the task. */
3985 void
3986 control_event_bootstrap(bootstrap_status_t status, int progress)
3988 const char *tag, *summary;
3989 char buf[BOOTSTRAP_MSG_LEN];
3991 if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
3992 return; /* already bootstrapped; nothing to be done here. */
3994 /* special case for handshaking status, since our TLS handshaking code
3995 * can't distinguish what the connection is going to be for. */
3996 if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
3997 if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
3998 status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
3999 } else {
4000 status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
4004 if (status > bootstrap_percent ||
4005 (progress && progress > bootstrap_percent)) {
4006 bootstrap_status_to_string(status, &tag, &summary);
4007 log(status ? LOG_NOTICE : LOG_INFO, LD_CONTROL,
4008 "Bootstrapped %d%%: %s.", progress ? progress : status, summary);
4009 tor_snprintf(buf, sizeof(buf),
4010 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
4011 progress ? progress : status, tag, summary);
4012 tor_snprintf(last_sent_bootstrap_message,
4013 sizeof(last_sent_bootstrap_message),
4014 "NOTICE %s", buf);
4015 control_event_client_status(LOG_NOTICE, "%s", buf);
4016 if (status > bootstrap_percent) {
4017 bootstrap_percent = status; /* new milestone reached */
4019 if (progress > bootstrap_percent) {
4020 /* incremental progress within a milestone */
4021 bootstrap_percent = progress;
4022 bootstrap_problems = 0; /* Progress! Reset our problem counter. */
4027 /** Called when Tor has failed to make bootstrapping progress in a way
4028 * that indicates a problem. <b>warn</b> gives a hint as to why, and
4029 * <b>reason</b> provides an "or_conn_end_reason" tag.
4031 void
4032 control_event_bootstrap_problem(const char *warn, int reason)
4034 int status = bootstrap_percent;
4035 const char *tag, *summary;
4036 char buf[BOOTSTRAP_MSG_LEN];
4037 const char *recommendation = "ignore";
4039 /* bootstrap_percent must not be in "undefined" state here. */
4040 tor_assert(status >= 0);
4042 if (bootstrap_percent == 100)
4043 return; /* already bootstrapped; nothing to be done here. */
4045 bootstrap_problems++;
4047 if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
4048 recommendation = "warn";
4050 if (reason == END_OR_CONN_REASON_NO_ROUTE)
4051 recommendation = "warn";
4053 if (get_options()->UseBridges &&
4054 !any_bridge_descriptors_known() &&
4055 !any_pending_bridge_descriptor_fetches())
4056 recommendation = "warn";
4058 while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
4059 status--; /* find a recognized status string based on current progress */
4060 status = bootstrap_percent; /* set status back to the actual number */
4062 log_fn(!strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO,
4063 LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
4064 "count %d; recommendation %s)",
4065 status, summary, warn,
4066 orconn_end_reason_to_control_string(reason),
4067 bootstrap_problems, recommendation);
4068 tor_snprintf(buf, sizeof(buf),
4069 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
4070 "COUNT=%d RECOMMENDATION=%s",
4071 bootstrap_percent, tag, summary, warn,
4072 orconn_end_reason_to_control_string(reason), bootstrap_problems,
4073 recommendation);
4074 tor_snprintf(last_sent_bootstrap_message,
4075 sizeof(last_sent_bootstrap_message),
4076 "WARN %s", buf);
4077 control_event_client_status(LOG_WARN, "%s", buf);
4080 /** We just generated a new summary of which countries we've seen clients
4081 * from recently. Send a copy to the controller in case it wants to
4082 * display it for the user. */
4083 void
4084 control_event_clients_seen(const char *controller_str)
4086 send_control_event(EVENT_CLIENTS_SEEN, 0,
4087 "650 CLIENTS_SEEN %s\r\n", controller_str);