If the networkstatus consensus lists no recommended versions, don't
[tor.git] / src / or / control.c
blobff3a4b10ae52702515e7bc629bf925fab7a75292
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
4 /* $Id$ */
5 const char control_c_id[] =
6 "$Id$";
8 /**
9 * \file control.c
10 * \brief Implementation for Tor's control-socket interface.
11 * See doc/spec/control-spec.txt for full details on protocol.
12 **/
14 #define CONTROL_PRIVATE
16 #include "or.h"
18 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
19 * finished authentication and is accepting commands. */
20 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
22 /* Recognized asynchronous event types. It's okay to expand this list
23 * because it is used both as a list of v0 event types, and as indices
24 * into the bitfield to determine which controllers want which events.
26 #define _EVENT_MIN 0x0001
27 #define EVENT_CIRCUIT_STATUS 0x0001
28 #define EVENT_STREAM_STATUS 0x0002
29 #define EVENT_OR_CONN_STATUS 0x0003
30 #define EVENT_BANDWIDTH_USED 0x0004
31 #define EVENT_LOG_OBSOLETE 0x0005 /* Can reclaim this. */
32 #define EVENT_NEW_DESC 0x0006
33 #define EVENT_DEBUG_MSG 0x0007
34 #define EVENT_INFO_MSG 0x0008
35 #define EVENT_NOTICE_MSG 0x0009
36 #define EVENT_WARN_MSG 0x000A
37 #define EVENT_ERR_MSG 0x000B
38 #define EVENT_ADDRMAP 0x000C
39 // #define EVENT_AUTHDIR_NEWDESCS 0x000D
40 #define EVENT_DESCCHANGED 0x000E
41 // #define EVENT_NS 0x000F
42 #define EVENT_STATUS_CLIENT 0x0010
43 #define EVENT_STATUS_SERVER 0x0011
44 #define EVENT_STATUS_GENERAL 0x0012
45 #define EVENT_GUARD 0x0013
46 #define EVENT_STREAM_BANDWIDTH_USED 0x0014
47 #define _EVENT_MAX 0x0014
48 /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
50 /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
51 * connection is interested in events of type <b>e</b>. We use this
52 * so that we can decide to skip generating event messages that nobody
53 * has interest in without having to walk over the global connection
54 * list to find out.
55 **/
56 typedef uint32_t event_mask_t;
57 static event_mask_t global_event_mask1long = 0;
58 static event_mask_t global_event_mask1short = 0;
60 /** True iff we have disabled log messages from being sent to the controller */
61 static int disable_log_messages = 0;
63 /** Macro: true if any control connection is interested in events of type
64 * <b>e</b>. */
65 #define EVENT_IS_INTERESTING(e) \
66 ((global_event_mask1long|global_event_mask1short) & (1<<(e)))
67 #define EVENT_IS_INTERESTING1L(e) (global_event_mask1long & (1<<(e)))
68 #define EVENT_IS_INTERESTING1S(e) (global_event_mask1short & (1<<(e)))
70 /** If we're using cookie-type authentication, how long should our cookies be?
72 #define AUTHENTICATION_COOKIE_LEN 32
74 /** If true, we've set authentication_cookie to a secret code and
75 * stored it to disk. */
76 static int authentication_cookie_is_set = 0;
77 static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
79 #define SHORT_NAMES 1
80 #define LONG_NAMES 2
81 #define ALL_NAMES (SHORT_NAMES|LONG_NAMES)
82 #define EXTENDED_FORMAT 4
83 #define NONEXTENDED_FORMAT 8
84 #define ALL_FORMATS (EXTENDED_FORMAT|NONEXTENDED_FORMAT)
85 typedef int event_format_t;
87 static void connection_printf_to_buf(control_connection_t *conn,
88 const char *format, ...)
89 CHECK_PRINTF(2,3);
90 static void send_control_done(control_connection_t *conn);
91 static void send_control_event(uint16_t event, event_format_t which,
92 const char *format, ...)
93 CHECK_PRINTF(3,4);
94 static void send_control_event_extended(uint16_t event, event_format_t which,
95 const char *format, ...)
96 CHECK_PRINTF(3,4);
97 static int handle_control_setconf(control_connection_t *conn, uint32_t len,
98 char *body);
99 static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
100 char *body);
101 static int handle_control_getconf(control_connection_t *conn, uint32_t len,
102 const char *body);
103 static int handle_control_setevents(control_connection_t *conn, uint32_t len,
104 const char *body);
105 static int handle_control_authenticate(control_connection_t *conn,
106 uint32_t len,
107 const char *body);
108 static int handle_control_saveconf(control_connection_t *conn, uint32_t len,
109 const char *body);
110 static int handle_control_signal(control_connection_t *conn, uint32_t len,
111 const char *body);
112 static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
113 const char *body);
114 static char *list_getinfo_options(void);
115 static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
116 const char *body);
117 static int handle_control_extendcircuit(control_connection_t *conn,
118 uint32_t len,
119 const char *body);
120 static int handle_control_setcircuitpurpose(control_connection_t *conn,
121 uint32_t len, const char *body);
122 static int handle_control_attachstream(control_connection_t *conn,
123 uint32_t len,
124 const char *body);
125 static int handle_control_postdescriptor(control_connection_t *conn,
126 uint32_t len,
127 const char *body);
128 static int handle_control_redirectstream(control_connection_t *conn,
129 uint32_t len,
130 const char *body);
131 static int handle_control_closestream(control_connection_t *conn, uint32_t len,
132 const char *body);
133 static int handle_control_closecircuit(control_connection_t *conn,
134 uint32_t len,
135 const char *body);
136 static int handle_control_resolve(control_connection_t *conn, uint32_t len,
137 const char *body);
138 static int handle_control_usefeature(control_connection_t *conn,
139 uint32_t len,
140 const char *body);
141 static int write_stream_target_to_buf(edge_connection_t *conn, char *buf,
142 size_t len);
143 static void orconn_target_get_name(int long_names, char *buf, size_t len,
144 or_connection_t *conn);
145 static char *get_cookie_file(void);
147 /** Given a control event code for a message event, return the corresponding
148 * log severity. */
149 static INLINE int
150 event_to_log_severity(int event)
152 switch (event) {
153 case EVENT_DEBUG_MSG: return LOG_DEBUG;
154 case EVENT_INFO_MSG: return LOG_INFO;
155 case EVENT_NOTICE_MSG: return LOG_NOTICE;
156 case EVENT_WARN_MSG: return LOG_WARN;
157 case EVENT_ERR_MSG: return LOG_ERR;
158 default: return -1;
162 /** Given a log severity, return the corresponding control event code. */
163 static INLINE int
164 log_severity_to_event(int severity)
166 switch (severity) {
167 case LOG_DEBUG: return EVENT_DEBUG_MSG;
168 case LOG_INFO: return EVENT_INFO_MSG;
169 case LOG_NOTICE: return EVENT_NOTICE_MSG;
170 case LOG_WARN: return EVENT_WARN_MSG;
171 case LOG_ERR: return EVENT_ERR_MSG;
172 default: return -1;
176 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
177 * connection's event_mask field. */
178 void
179 control_update_global_event_mask(void)
181 smartlist_t *conns = get_connection_array();
182 event_mask_t old_mask, new_mask;
183 old_mask = global_event_mask1short;
184 old_mask |= global_event_mask1long;
186 global_event_mask1short = 0;
187 global_event_mask1long = 0;
188 SMARTLIST_FOREACH(conns, connection_t *, _conn,
190 if (_conn->type == CONN_TYPE_CONTROL &&
191 STATE_IS_OPEN(_conn->state)) {
192 control_connection_t *conn = TO_CONTROL_CONN(_conn);
193 if (conn->use_long_names)
194 global_event_mask1long |= conn->event_mask;
195 else
196 global_event_mask1short |= conn->event_mask;
200 new_mask = global_event_mask1short;
201 new_mask |= global_event_mask1long;
203 /* Handle the aftermath. Set up the log callback to tell us only what
204 * we want to hear...*/
205 control_adjust_event_log_severity();
207 /* ...then, if we've started logging stream bw, clear the appropriate
208 * fields. */
209 if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
210 (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
211 SMARTLIST_FOREACH(conns, connection_t *, conn,
213 if (conn->type == CONN_TYPE_AP) {
214 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
215 edge_conn->n_written = edge_conn->n_read = 0;
221 /** Adjust the log severities that result in control_event_logmsg being called
222 * to match the severity of log messages that any controllers are interested
223 * in. */
224 void
225 control_adjust_event_log_severity(void)
227 int i;
228 int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
230 for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
231 if (EVENT_IS_INTERESTING(i)) {
232 min_log_event = i;
233 break;
236 for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
237 if (EVENT_IS_INTERESTING(i)) {
238 max_log_event = i;
239 break;
242 if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE) ||
243 EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
244 if (min_log_event > EVENT_NOTICE_MSG)
245 min_log_event = EVENT_NOTICE_MSG;
246 if (max_log_event < EVENT_ERR_MSG)
247 max_log_event = EVENT_ERR_MSG;
249 change_callback_log_severity(event_to_log_severity(min_log_event),
250 event_to_log_severity(max_log_event),
251 control_event_logmsg);
254 /** Return true iff the event with code <b>c</b> is being sent to any current
255 * control connection. This is useful if the amount of work needed to prepare
256 * to call the appropriate control_event_...() function is high.
259 control_event_is_interesting(int event)
261 return EVENT_IS_INTERESTING(event);
264 /** Append a NUL-terminated string <b>s</b> to the end of
265 * <b>conn</b>-\>outbuf.
267 static INLINE void
268 connection_write_str_to_buf(const char *s, control_connection_t *conn)
270 size_t len = strlen(s);
271 connection_write_to_buf(s, len, TO_CONN(conn));
274 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
275 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
276 * contents of <b>data</b> into *<b>out</b>, adding a period before any period
277 * that that appears at the start of a line, and adding a period-CRLF line at
278 * the end. Replace all LF characters sequences with CRLF. Return the number
279 * of bytes in *<b>out</b>.
281 /* static */ size_t
282 write_escaped_data(const char *data, size_t len, char **out)
284 size_t sz_out = len+8;
285 char *outp;
286 const char *start = data, *end;
287 int i;
288 int start_of_line;
289 for (i=0; i<(int)len; ++i) {
290 if (data[i]== '\n')
291 sz_out += 2; /* Maybe add a CR; maybe add a dot. */
293 *out = outp = tor_malloc(sz_out+1);
294 end = data+len;
295 start_of_line = 1;
296 while (data < end) {
297 if (*data == '\n') {
298 if (data > start && data[-1] != '\r')
299 *outp++ = '\r';
300 start_of_line = 1;
301 } else if (*data == '.') {
302 if (start_of_line) {
303 start_of_line = 0;
304 *outp++ = '.';
306 } else {
307 start_of_line = 0;
309 *outp++ = *data++;
311 if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
312 *outp++ = '\r';
313 *outp++ = '\n';
315 *outp++ = '.';
316 *outp++ = '\r';
317 *outp++ = '\n';
318 *outp = '\0'; /* NUL-terminate just in case. */
319 tor_assert((outp - *out) <= (int)sz_out);
320 return outp - *out;
323 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
324 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
325 * the contents of <b>data</b> into *<b>out</b>, removing any period
326 * that appears at the start of a line, and replacing all CRLF sequences
327 * with LF. Return the number of
328 * bytes in *<b>out</b>. */
329 /* static */ size_t
330 read_escaped_data(const char *data, size_t len, char **out)
332 char *outp;
333 const char *next;
334 const char *end;
336 *out = outp = tor_malloc(len+1);
338 end = data+len;
340 while (data < end) {
341 /* we're at the start of a line. */
342 if (*data == '.')
343 ++data;
344 next = memchr(data, '\n', end-data);
345 if (next) {
346 size_t n_to_copy = next-data;
347 /* Don't copy a CR that precedes this LF. */
348 if (n_to_copy && *(next-1) == '\r')
349 --n_to_copy;
350 memcpy(outp, data, n_to_copy);
351 outp += n_to_copy;
352 data = next+1; /* This will point at the start of the next line,
353 * or the end of the string, or a period. */
354 } else {
355 memcpy(outp, data, end-data);
356 outp += (end-data);
357 *outp = '\0';
358 return outp - *out;
360 *outp++ = '\n';
363 *outp = '\0';
364 return outp - *out;
367 /** DOCDOC */
368 static const char *
369 extract_escaped_string(const char *start, size_t in_len_max,
370 char **out, size_t *out_len)
372 const char *cp, *end;
373 size_t len=0;
375 if (*start != '\"')
376 return NULL;
378 cp = start+1;
379 end = start+in_len_max;
381 /* Calculate length. */
382 while (1) {
383 if (cp >= end)
384 return NULL;
385 else if (*cp == '\\') {
386 if (++cp == end)
387 return NULL; /* Can't escape EOS. */
388 ++cp;
389 ++len;
390 } else if (*cp == '\"') {
391 break;
392 } else {
393 ++cp;
394 ++len;
397 end = cp;
399 *out_len = end-start+1;
400 *out = tor_strndup(start, *out_len);
402 return end+1;
405 /** Given a pointer to a string starting at <b>start</b> containing
406 * <b>in_len_max</b> characters, decode a string beginning with one double
407 * quote, containing any number of non-quote characters or characters escaped
408 * with a backslash, and ending with a final double quote. Place the resulting
409 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
410 * store its length in <b>out_len</b>. On success, return a pointer to the
411 * character immediately following the escaped string. On failure, return
412 * NULL. */
413 /* XXXX020 fold into extract_escaped_string */
414 static const char *
415 get_escaped_string(const char *start, size_t in_len_max,
416 char **out, size_t *out_len)
418 const char *cp, *end;
419 char *outp;
420 size_t len=0;
422 if (*start != '\"')
423 return NULL;
425 cp = start+1;
426 end = start+in_len_max;
428 /* Calculate length. */
429 while (1) {
430 if (cp >= end)
431 return NULL;
432 else if (*cp == '\\') {
433 if (++cp == end)
434 return NULL; /* Can't escape EOS. */
435 ++cp;
436 ++len;
437 } else if (*cp == '\"') {
438 break;
439 } else {
440 ++cp;
441 ++len;
444 end = cp;
445 outp = *out = tor_malloc(len+1);
446 *out_len = len;
448 cp = start+1;
449 while (cp < end) {
450 if (*cp == '\\')
451 ++cp;
452 *outp++ = *cp++;
454 *outp = '\0';
455 tor_assert((outp - *out) == (int)*out_len);
457 return end+1;
460 /** Acts like sprintf, but writes its formatted string to the end of
461 * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
462 * but it will always end with a CRLF sequence.
464 * Currently the length of the message is limited to 1024 (including the
465 * ending \r\n\0. */
466 static void
467 connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
469 #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
470 va_list ap;
471 char buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE];
472 int r;
473 size_t len;
474 va_start(ap,format);
475 r = tor_vsnprintf(buf, sizeof(buf), format, ap);
476 va_end(ap);
477 if (r<0) {
478 log_warn(LD_BUG, "Unable to format string for controller.");
479 return;
481 len = strlen(buf);
482 if (memcmp("\r\n\0", buf+len-2, 3)) {
483 buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-1] = '\0';
484 buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-2] = '\n';
485 buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-3] = '\r';
487 connection_write_to_buf(buf, len, TO_CONN(conn));
490 /** Send a "DONE" message down the control connection <b>conn</b>. */
491 static void
492 send_control_done(control_connection_t *conn)
494 connection_write_str_to_buf("250 OK\r\n", conn);
497 /* Send an event to all v1 controllers that are listening for code
498 * <b>event</b>. The event's body is given by <b>msg</b>.
500 * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
501 * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
502 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
503 * to contollers that <em>have</em> enabled VERBOSE_NAMES.
505 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
506 * respect to the EXTENDED_EVENTS feature. */
507 static void
508 send_control_event_string(uint16_t event, event_format_t which,
509 const char *msg)
511 smartlist_t *conns = get_connection_array();
512 tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);
514 SMARTLIST_FOREACH(conns, connection_t *, conn,
516 if (conn->type == CONN_TYPE_CONTROL &&
517 !conn->marked_for_close &&
518 conn->state == CONTROL_CONN_STATE_OPEN) {
519 control_connection_t *control_conn = TO_CONTROL_CONN(conn);
520 if (control_conn->use_long_names) {
521 if (!(which & LONG_NAMES))
522 continue;
523 } else {
524 if (!(which & SHORT_NAMES))
525 continue;
527 if (control_conn->use_extended_events) {
528 if (!(which & EXTENDED_FORMAT))
529 continue;
530 } else {
531 if (!(which & NONEXTENDED_FORMAT))
532 continue;
534 if (control_conn->event_mask & (1<<event)) {
535 int is_err = 0;
536 connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
537 if (event == EVENT_ERR_MSG)
538 is_err = 1;
539 else if (event == EVENT_STATUS_GENERAL)
540 is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
541 else if (event == EVENT_STATUS_CLIENT)
542 is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
543 else if (event == EVENT_STATUS_SERVER)
544 is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
545 if (is_err)
546 connection_handle_write(TO_CONN(control_conn), 1);
552 /** Helper for send_control1_event and send_control1_event_extended:
553 * Send an event to all v1 controllers that are listening for code
554 * <b>event</b>. The event's body is created by the printf-style format in
555 * <b>format</b>, and other arguments as provided.
557 * If <b>extended</b> is true, and the format contains a single '@' character,
558 * it will be replaced with a space and all text after that character will be
559 * sent only to controllers that have enabled extended events.
561 * Currently the length of the message is limited to 1024 (including the
562 * ending \n\r\0). */
563 static void
564 send_control_event_impl(uint16_t event, event_format_t which, int extended,
565 const char *format, va_list ap)
567 /* This is just a little longer than the longest allowed log message */
568 #define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
569 int r;
570 char buf[SEND_CONTROL1_EVENT_BUFFERSIZE];
571 size_t len;
572 char *cp;
574 r = tor_vsnprintf(buf, sizeof(buf), format, ap);
575 if (r<0) {
576 log_warn(LD_BUG, "Unable to format event for controller.");
577 return;
580 len = strlen(buf);
581 if (memcmp("\r\n\0", buf+len-2, 3)) {
582 /* if it is not properly terminated, do it now */
583 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-1] = '\0';
584 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-2] = '\n';
585 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-3] = '\r';
588 if (extended && (cp = strchr(buf, '@'))) {
589 which &= ~ALL_FORMATS;
590 *cp = ' ';
591 send_control_event_string(event, which|EXTENDED_FORMAT, buf);
592 memcpy(cp, "\r\n\0", 3);
593 send_control_event_string(event, which|NONEXTENDED_FORMAT, buf);
594 } else {
595 send_control_event_string(event, which|ALL_FORMATS, buf);
599 /* Send an event to all v1 controllers that are listening for code
600 * <b>event</b>. The event's body is created by the printf-style format in
601 * <b>format</b>, and other arguments as provided.
603 * Currently the length of the message is limited to 1024 (including the
604 * ending \n\r\0. */
605 static void
606 send_control_event(uint16_t event, event_format_t which,
607 const char *format, ...)
609 va_list ap;
610 va_start(ap, format);
611 send_control_event_impl(event, which, 0, format, ap);
612 va_end(ap);
615 /* Send an event to all v1 controllers that are listening for code
616 * <b>event</b>. The event's body is created by the printf-style format in
617 * <b>format</b>, and other arguments as provided.
619 * If the format contains a single '@' character, it will be replaced with a
620 * space and all text after that character will be sent only to controllers
621 * that have enabled extended events.
623 * Currently the length of the message is limited to 1024 (including the
624 * ending \n\r\0. */
625 static void
626 send_control_event_extended(uint16_t event, event_format_t which,
627 const char *format, ...)
629 va_list ap;
630 va_start(ap, format);
631 send_control_event_impl(event, which, 1, format, ap);
632 va_end(ap);
635 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
636 static origin_circuit_t *
637 get_circ(const char *id)
639 unsigned long n_id;
640 int ok;
641 n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
642 if (!ok)
643 return NULL;
644 return circuit_get_by_global_id(n_id);
647 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
648 static edge_connection_t *
649 get_stream(const char *id)
651 unsigned long n_id;
652 int ok;
653 edge_connection_t *conn;
654 n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
655 if (!ok)
656 return NULL;
657 conn = connection_get_by_global_id(n_id);
658 if (!conn || conn->_base.type != CONN_TYPE_AP)
659 return NULL;
660 return conn;
663 /** Helper for setconf and resetconf. Acts like setconf, except
664 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
665 * contents of body.
667 static int
668 control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
669 int use_defaults)
671 int r;
672 config_line_t *lines=NULL;
673 char *start = body;
674 char *errstring = NULL;
675 const int clear_first = 1;
677 char *config;
678 smartlist_t *entries = smartlist_create();
680 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
681 * separated by space. break it into a list of configuration entries. */
682 while (*body) {
683 char *eq = body;
684 char *key;
685 char *entry;
686 while (!TOR_ISSPACE(*eq) && *eq != '=')
687 ++eq;
688 key = tor_strndup(body, eq-body);
689 body = eq+1;
690 if (*eq == '=') {
691 char *val=NULL;
692 size_t val_len=0;
693 size_t ent_len;
694 if (*body != '\"') {
695 char *val_start = body;
696 while (!TOR_ISSPACE(*body))
697 body++;
698 val = tor_strndup(val_start, body-val_start);
699 val_len = strlen(val);
700 } else {
701 body = (char*)extract_escaped_string(body, (len - (body-start)),
702 &val, &val_len);
703 if (!body) {
704 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
705 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
706 smartlist_free(entries);
707 tor_free(key);
708 return 0;
711 ent_len = strlen(key)+val_len+3;
712 entry = tor_malloc(ent_len+1);
713 tor_snprintf(entry, ent_len, "%s %s", key, val);
714 tor_free(key);
715 tor_free(val);
716 } else {
717 entry = key;
719 smartlist_add(entries, entry);
720 while (TOR_ISSPACE(*body))
721 ++body;
724 smartlist_add(entries, tor_strdup(""));
725 config = smartlist_join_strings(entries, "\n", 0, NULL);
726 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
727 smartlist_free(entries);
729 if (config_get_lines(config, &lines) < 0) {
730 log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
731 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
732 conn);
733 tor_free(config);
734 return 0;
736 tor_free(config);
738 if ((r=options_trial_assign(lines, use_defaults,
739 clear_first, &errstring)) < 0) {
740 const char *msg;
741 log_warn(LD_CONTROL,
742 "Controller gave us config lines that didn't validate: %s",
743 errstring);
744 switch (r) {
745 case -1:
746 msg = "552 Unrecognized option";
747 break;
748 case -2:
749 msg = "513 Unacceptable option value";
750 break;
751 case -3:
752 msg = "553 Transition not allowed";
753 break;
754 case -4:
755 default:
756 msg = "553 Unable to set option";
757 break;
759 connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
760 config_free_lines(lines);
761 tor_free(errstring);
762 return 0;
764 config_free_lines(lines);
765 send_control_done(conn);
766 return 0;
769 /** Called when we receive a SETCONF message: parse the body and try
770 * to update our configuration. Reply with a DONE or ERROR message.
771 * Modifies the contents of body.*/
772 static int
773 handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
775 return control_setconf_helper(conn, len, body, 0);
778 /** Called when we receive a RESETCONF message: parse the body and try
779 * to update our configuration. Reply with a DONE or ERROR message.
780 * Modifies the contents of body. */
781 static int
782 handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
784 return control_setconf_helper(conn, len, body, 1);
787 /** Called when we receive a GETCONF message. Parse the request, and
788 * reply with a CONFVALUE or an ERROR message */
789 static int
790 handle_control_getconf(control_connection_t *conn, uint32_t body_len,
791 const char *body)
793 smartlist_t *questions = NULL;
794 smartlist_t *answers = NULL;
795 smartlist_t *unrecognized = NULL;
796 char *msg = NULL;
797 size_t msg_len;
798 or_options_t *options = get_options();
799 int i, len;
801 questions = smartlist_create();
802 (void) body_len; /* body is nul-terminated; so we can ignore len. */
803 smartlist_split_string(questions, body, " ",
804 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
805 answers = smartlist_create();
806 unrecognized = smartlist_create();
807 SMARTLIST_FOREACH(questions, char *, q,
809 if (!option_is_recognized(q)) {
810 smartlist_add(unrecognized, q);
811 } else {
812 config_line_t *answer = option_get_assignment(options,q);
813 if (!answer) {
814 const char *name = option_get_canonical_name(q);
815 size_t alen = strlen(name)+8;
816 char *astr = tor_malloc(alen);
817 tor_snprintf(astr, alen, "250-%s\r\n", name);
818 smartlist_add(answers, astr);
821 while (answer) {
822 config_line_t *next;
823 size_t alen = strlen(answer->key)+strlen(answer->value)+8;
824 char *astr = tor_malloc(alen);
825 tor_snprintf(astr, alen, "250-%s=%s\r\n",
826 answer->key, answer->value);
827 smartlist_add(answers, astr);
829 next = answer->next;
830 tor_free(answer->key);
831 tor_free(answer->value);
832 tor_free(answer);
833 answer = next;
838 if ((len = smartlist_len(unrecognized))) {
839 for (i=0; i < len-1; ++i)
840 connection_printf_to_buf(conn,
841 "552-Unrecognized configuration key \"%s\"\r\n",
842 (char*)smartlist_get(unrecognized, i));
843 connection_printf_to_buf(conn,
844 "552 Unrecognized configuration key \"%s\"\r\n",
845 (char*)smartlist_get(unrecognized, len-1));
846 } else if ((len = smartlist_len(answers))) {
847 char *tmp = smartlist_get(answers, len-1);
848 tor_assert(strlen(tmp)>4);
849 tmp[3] = ' ';
850 msg = smartlist_join_strings(answers, "", 0, &msg_len);
851 connection_write_to_buf(msg, msg_len, TO_CONN(conn));
852 } else {
853 connection_write_str_to_buf("250 OK\r\n", conn);
856 if (answers) {
857 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
858 smartlist_free(answers);
860 if (questions) {
861 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
862 smartlist_free(questions);
864 smartlist_free(unrecognized);
865 tor_free(msg);
867 return 0;
870 /** Called when we get a SETEVENTS message: update conn->event_mask,
871 * and reply with DONE or ERROR. */
872 static int
873 handle_control_setevents(control_connection_t *conn, uint32_t len,
874 const char *body)
876 uint16_t event_code;
877 uint32_t event_mask = 0;
878 unsigned int extended = 0;
879 smartlist_t *events = smartlist_create();
881 (void) len;
883 smartlist_split_string(events, body, " ",
884 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
885 SMARTLIST_FOREACH(events, const char *, ev,
887 if (!strcasecmp(ev, "EXTENDED")) {
888 extended = 1;
889 continue;
890 } else if (!strcasecmp(ev, "CIRC"))
891 event_code = EVENT_CIRCUIT_STATUS;
892 else if (!strcasecmp(ev, "STREAM"))
893 event_code = EVENT_STREAM_STATUS;
894 else if (!strcasecmp(ev, "ORCONN"))
895 event_code = EVENT_OR_CONN_STATUS;
896 else if (!strcasecmp(ev, "BW"))
897 event_code = EVENT_BANDWIDTH_USED;
898 else if (!strcasecmp(ev, "DEBUG"))
899 event_code = EVENT_DEBUG_MSG;
900 else if (!strcasecmp(ev, "INFO"))
901 event_code = EVENT_INFO_MSG;
902 else if (!strcasecmp(ev, "NOTICE"))
903 event_code = EVENT_NOTICE_MSG;
904 else if (!strcasecmp(ev, "WARN"))
905 event_code = EVENT_WARN_MSG;
906 else if (!strcasecmp(ev, "ERR"))
907 event_code = EVENT_ERR_MSG;
908 else if (!strcasecmp(ev, "NEWDESC"))
909 event_code = EVENT_NEW_DESC;
910 else if (!strcasecmp(ev, "ADDRMAP"))
911 event_code = EVENT_ADDRMAP;
912 else if (!strcasecmp(ev, "AUTHDIR_NEWDESCS"))
913 event_code = EVENT_AUTHDIR_NEWDESCS;
914 else if (!strcasecmp(ev, "DESCCHANGED"))
915 event_code = EVENT_DESCCHANGED;
916 else if (!strcasecmp(ev, "NS"))
917 event_code = EVENT_NS;
918 else if (!strcasecmp(ev, "STATUS_GENERAL"))
919 event_code = EVENT_STATUS_GENERAL;
920 else if (!strcasecmp(ev, "STATUS_CLIENT"))
921 event_code = EVENT_STATUS_CLIENT;
922 else if (!strcasecmp(ev, "STATUS_SERVER"))
923 event_code = EVENT_STATUS_SERVER;
924 else if (!strcasecmp(ev, "GUARD"))
925 event_code = EVENT_GUARD;
926 else if (!strcasecmp(ev, "GUARDS")) {
927 /* XXXX021 This check is here to tolerate the controllers that
928 * depended on the buggy spec in 0.1.2.5-alpha through 0.1.2.10-rc.
929 * Once those versions are obsolete, stop supporting this. */
930 log_warn(LD_CONTROL, "Controller used obsolete 'GUARDS' event name; "
931 "use GUARD instead.");
932 event_code = EVENT_GUARD;
933 } else if (!strcasecmp(ev, "STREAM_BW"))
934 event_code = EVENT_STREAM_BANDWIDTH_USED;
935 else {
936 connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
937 ev);
938 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
939 smartlist_free(events);
940 return 0;
942 event_mask |= (1 << event_code);
944 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
945 smartlist_free(events);
947 conn->event_mask = event_mask;
948 if (extended)
949 conn->use_extended_events = 1;
951 control_update_global_event_mask();
952 send_control_done(conn);
953 return 0;
956 /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
957 * Return a smartlist of acceptable passwords (unterminated strings of
958 * length S2K_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on failure.
960 smartlist_t *
961 decode_hashed_passwords(config_line_t *passwords)
963 char decoded[64];
964 config_line_t *cl;
965 smartlist_t *sl = smartlist_create();
967 tor_assert(passwords);
969 for (cl = passwords; cl; cl = cl->next) {
970 const char *hashed = cl->value;
972 if (!strcmpstart(hashed, "16:")) {
973 if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
974 || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
975 goto err;
977 } else {
978 if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
979 != S2K_SPECIFIER_LEN+DIGEST_LEN) {
980 goto err;
983 smartlist_add(sl, tor_memdup(decoded, S2K_SPECIFIER_LEN+DIGEST_LEN));
986 return sl;
988 err:
989 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
990 smartlist_free(sl);
991 return NULL;
994 /** Called when we get an AUTHENTICATE message. Check whether the
995 * authentication is valid, and if so, update the connection's state to
996 * OPEN. Reply with DONE or ERROR.
998 static int
999 handle_control_authenticate(control_connection_t *conn, uint32_t len,
1000 const char *body)
1002 int used_quoted_string = 0;
1003 or_options_t *options = get_options();
1004 const char *errstr = NULL;
1005 char *password;
1006 size_t password_len;
1007 const char *cp;
1008 int i;
1009 int bad_cookie=0, bad_password=0;
1010 smartlist_t *sl = NULL;
1012 if (TOR_ISXDIGIT(body[0])) {
1013 cp = body;
1014 while (TOR_ISXDIGIT(*cp))
1015 ++cp;
1016 i = cp - body;
1017 tor_assert(i>0);
1018 password_len = i/2;
1019 password = tor_malloc(password_len + 1);
1020 if (base16_decode(password, password_len+1, body, i)<0) {
1021 connection_write_str_to_buf(
1022 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1023 "password? If so, the standard requires that you put it in "
1024 "double quotes.\r\n", conn);
1025 connection_mark_for_close(TO_CONN(conn));
1026 tor_free(password);
1027 return 0;
1029 } else if (TOR_ISSPACE(body[0])) {
1030 password = tor_strdup("");
1031 password_len = 0;
1032 } else {
1033 if (!get_escaped_string(body, len, &password, &password_len)) {
1034 connection_write_str_to_buf("551 Invalid quoted string. You need "
1035 "to put the password in double quotes.\r\n", conn);
1036 connection_mark_for_close(TO_CONN(conn));
1037 return 0;
1039 used_quoted_string = 1;
1042 if (!options->CookieAuthentication && !options->HashedControlPassword) {
1043 /* if Tor doesn't demand any stronger authentication, then
1044 * the controller can get in with anything. */
1045 goto ok;
1048 if (options->CookieAuthentication) {
1049 int also_password = options->HashedControlPassword != NULL;
1050 if (password_len != AUTHENTICATION_COOKIE_LEN) {
1051 if (!also_password) {
1052 log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
1053 "(%d)", (int)password_len);
1054 errstr = "Wrong length on authentication cookie.";
1055 goto err;
1057 bad_cookie = 1;
1058 } else if (memcmp(authentication_cookie, password, password_len)) {
1059 if (!also_password) {
1060 log_warn(LD_CONTROL, "Got mismatched authentication cookie");
1061 errstr = "Authentication cookie did not match expected value.";
1062 goto err;
1064 bad_cookie = 1;
1065 } else {
1066 goto ok;
1070 if (options->HashedControlPassword) {
1071 char received[DIGEST_LEN];
1072 int also_cookie = options->CookieAuthentication;
1073 sl = decode_hashed_passwords(options->HashedControlPassword);
1074 if (!sl) {
1075 if (!also_cookie) {
1076 log_warn(LD_CONTROL,
1077 "Couldn't decode HashedControlPassword: invalid base16");
1078 errstr="Couldn't decode HashedControlPassword value in configuration.";
1080 bad_password = 1;
1081 } else {
1082 SMARTLIST_FOREACH(sl, char *, expected,
1084 secret_to_key(received,DIGEST_LEN,password,password_len,expected);
1085 if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
1086 goto ok;
1088 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1089 smartlist_free(sl);
1091 if (used_quoted_string)
1092 errstr = "Password did not match HashedControlPassword value from "
1093 "configuration";
1094 else
1095 errstr = "Password did not match HashedControlPassword value from "
1096 "configuration. Maybe you tried a plain text password? "
1097 "If so, the standard requires that you put it in double quotes.";
1098 bad_password = 1;
1099 if (!also_cookie)
1100 goto err;
1104 /** We only get here if both kinds of authentication failed. */
1105 tor_assert(bad_password && bad_cookie);
1106 log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
1107 errstr = "Password did not match HashedControlPassword *or* authentication "
1108 "cookie.";
1110 err:
1111 tor_free(password);
1112 if (!errstr)
1113 errstr = "Unknown reason.";
1114 connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n",
1115 errstr);
1116 connection_mark_for_close(TO_CONN(conn));
1117 return 0;
1119 log_info(LD_CONTROL, "Authenticated control connection (%d)", conn->_base.s);
1120 send_control_done(conn);
1121 conn->_base.state = CONTROL_CONN_STATE_OPEN;
1122 tor_free(password);
1123 if (sl) { /* clean up */
1124 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1125 smartlist_free(sl);
1127 return 0;
1130 /** Called when we get a SAVECONF command. Try to flush the current options to
1131 * disk, and report success or failure. */
1132 static int
1133 handle_control_saveconf(control_connection_t *conn, uint32_t len,
1134 const char *body)
1136 (void) len;
1137 (void) body;
1138 if (options_save_current()<0) {
1139 connection_write_str_to_buf(
1140 "551 Unable to write configuration to disk.\r\n", conn);
1141 } else {
1142 send_control_done(conn);
1144 return 0;
1147 /** Called when we get a SIGNAL command. React to the provided signal, and
1148 * report success or failure. (If the signal results in a shutdown, success
1149 * may not be reported.) */
1150 static int
1151 handle_control_signal(control_connection_t *conn, uint32_t len,
1152 const char *body)
1154 int sig;
1155 int n = 0;
1156 char *s;
1158 (void) len;
1160 while (body[n] && ! TOR_ISSPACE(body[n]))
1161 ++n;
1162 s = tor_strndup(body, n);
1163 if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
1164 sig = SIGHUP;
1165 else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
1166 sig = SIGINT;
1167 else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
1168 sig = SIGUSR1;
1169 else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
1170 sig = SIGUSR2;
1171 else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
1172 sig = SIGTERM;
1173 else if (!strcasecmp(s, "NEWNYM"))
1174 sig = SIGNEWNYM;
1175 else if (!strcasecmp(s, "CLEARDNSCACHE"))
1176 sig = SIGCLEARDNSCACHE;
1177 else {
1178 connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
1180 sig = -1;
1182 tor_free(s);
1183 if (sig<0)
1184 return 0;
1186 send_control_done(conn);
1187 /* Flush the "done" first if the signal might make us shut down. */
1188 if (sig == SIGTERM || sig == SIGINT)
1189 connection_handle_write(TO_CONN(conn), 1);
1190 control_signal_act(sig);
1191 return 0;
1194 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1195 * and report success or failrue. */
1196 static int
1197 handle_control_mapaddress(control_connection_t *conn, uint32_t len,
1198 const char *body)
1200 smartlist_t *elts;
1201 smartlist_t *lines;
1202 smartlist_t *reply;
1203 char *r;
1204 size_t sz;
1205 (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
1207 lines = smartlist_create();
1208 elts = smartlist_create();
1209 reply = smartlist_create();
1210 smartlist_split_string(lines, body, " ",
1211 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1212 SMARTLIST_FOREACH(lines, char *, line,
1214 tor_strlower(line);
1215 smartlist_split_string(elts, line, "=", 0, 2);
1216 if (smartlist_len(elts) == 2) {
1217 const char *from = smartlist_get(elts,0);
1218 const char *to = smartlist_get(elts,1);
1219 size_t anslen = strlen(line)+512;
1220 char *ans = tor_malloc(anslen);
1221 if (address_is_invalid_destination(to, 1)) {
1222 tor_snprintf(ans, anslen,
1223 "512-syntax error: invalid address '%s'", to);
1224 smartlist_add(reply, ans);
1225 log_warn(LD_CONTROL,
1226 "Skipping invalid argument '%s' in MapAddress msg", to);
1227 } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
1228 const char *address = addressmap_register_virtual_address(
1229 !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
1230 tor_strdup(to));
1231 if (!address) {
1232 tor_snprintf(ans, anslen,
1233 "451-resource exhausted: skipping '%s'", line);
1234 smartlist_add(reply, ans);
1235 log_warn(LD_CONTROL,
1236 "Unable to allocate address for '%s' in MapAddress msg",
1237 safe_str(line));
1238 } else {
1239 tor_snprintf(ans, anslen, "250-%s=%s", address, to);
1240 smartlist_add(reply, ans);
1242 } else {
1243 addressmap_register(from, tor_strdup(to), 1);
1244 tor_snprintf(ans, anslen, "250-%s", line);
1245 smartlist_add(reply, ans);
1247 } else {
1248 size_t anslen = strlen(line)+256;
1249 char *ans = tor_malloc(anslen);
1250 tor_snprintf(ans, anslen, "512-syntax error: mapping '%s' is "
1251 "not of expected form 'foo=bar'.", line);
1252 smartlist_add(reply, ans);
1253 log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
1254 "number of items.", safe_str(line));
1256 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
1257 smartlist_clear(elts);
1259 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1260 smartlist_free(lines);
1261 smartlist_free(elts);
1263 if (smartlist_len(reply)) {
1264 ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
1265 r = smartlist_join_strings(reply, "\r\n", 1, &sz);
1266 connection_write_to_buf(r, sz, TO_CONN(conn));
1267 tor_free(r);
1268 } else {
1269 const char *response =
1270 "512 syntax error: not enough arguments to mapaddress.\r\n";
1271 connection_write_to_buf(response, strlen(response), TO_CONN(conn));
1274 SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
1275 smartlist_free(reply);
1276 return 0;
1279 /** Implementation helper for GETINFO: knows the answers for various
1280 * trivial-to-implement questions. */
1281 static int
1282 getinfo_helper_misc(control_connection_t *conn, const char *question,
1283 char **answer)
1285 (void) conn;
1286 if (!strcmp(question, "version")) {
1287 *answer = tor_strdup(get_version());
1288 } else if (!strcmp(question, "config-file")) {
1289 *answer = tor_strdup(get_torrc_fname());
1290 } else if (!strcmp(question, "info/names")) {
1291 *answer = list_getinfo_options();
1292 } else if (!strcmp(question, "events/names")) {
1293 *answer = tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
1294 "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
1295 "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
1296 "GUARD STREAM_BW");
1297 } else if (!strcmp(question, "features/names")) {
1298 *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1299 } else if (!strcmp(question, "address")) {
1300 uint32_t addr;
1301 if (router_pick_published_address(get_options(), &addr) < 0)
1302 return -1;
1303 *answer = tor_dup_addr(addr);
1304 } else if (!strcmp(question, "dir-usage")) {
1305 *answer = directory_dump_request_log();
1306 } else if (!strcmp(question, "fingerprint")) {
1307 routerinfo_t *me = router_get_my_routerinfo();
1308 if (!me)
1309 return -1;
1310 *answer = tor_malloc(HEX_DIGEST_LEN+1);
1311 base16_encode(*answer, HEX_DIGEST_LEN+1, me->cache_info.identity_digest,
1312 DIGEST_LEN);
1314 return 0;
1317 /** Awful hack: return a newly allocated string based on a routerinfo and
1318 * (possibly) an extrainfo, sticking the read-history and write-history from
1319 * <b>ei</b> into the resulting string. The thing you get back won't
1320 * necessarily have a valid signature.
1322 * New code should never use this; it's for backward compatibiliy.
1324 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1325 * not be NUL-terminated. */
1326 static char *
1327 munge_extrainfo_into_routerinfo(const char *ri_body, signed_descriptor_t *ri,
1328 signed_descriptor_t *ei)
1330 char *out = NULL, *outp;
1331 int i;
1332 const char *router_sig;
1333 const char *ei_body = signed_descriptor_get_body(ei);
1334 size_t ri_len = ri->signed_descriptor_len;
1335 size_t ei_len = ei->signed_descriptor_len;
1336 if (!ei_body)
1337 goto bail;
1339 outp = out = tor_malloc(ri_len+ei_len+1);
1340 if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
1341 goto bail;
1342 ++router_sig;
1343 memcpy(out, ri_body, router_sig-ri_body);
1344 outp += router_sig-ri_body;
1346 for (i=0; i < 2; ++i) {
1347 const char *kwd = i?"\nwrite-history ":"\nread-history ";
1348 const char *cp, *eol;
1349 if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
1350 continue;
1351 ++cp;
1352 eol = memchr(cp, '\n', ei_len - (cp-ei_body));
1353 memcpy(outp, cp, eol-cp+1);
1354 outp += eol-cp+1;
1356 memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
1357 *outp++ = '\0';
1358 tor_assert(outp-out < (int)(ri_len+ei_len+1));
1360 return out;
1361 bail:
1362 tor_free(out);
1363 return tor_strndup(ri_body, ri->signed_descriptor_len);
1366 /** Implementation helper for GETINFO: knows the answers for questions about
1367 * directory information. */
1368 static int
1369 getinfo_helper_dir(control_connection_t *control_conn,
1370 const char *question, char **answer)
1372 if (!strcmpstart(question, "desc/id/")) {
1373 routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
1374 if (ri) {
1375 const char *body = signed_descriptor_get_body(&ri->cache_info);
1376 if (body)
1377 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1379 } else if (!strcmpstart(question, "desc/name/")) {
1380 routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
1381 if (ri) {
1382 const char *body = signed_descriptor_get_body(&ri->cache_info);
1383 if (body)
1384 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1386 } else if (!strcmp(question, "desc/all-recent")) {
1387 routerlist_t *routerlist = router_get_routerlist();
1388 smartlist_t *sl = smartlist_create();
1389 if (routerlist && routerlist->routers) {
1390 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
1392 const char *body = signed_descriptor_get_body(&ri->cache_info);
1393 if (body)
1394 smartlist_add(sl,
1395 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1398 *answer = smartlist_join_strings(sl, "", 0, NULL);
1399 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1400 smartlist_free(sl);
1401 } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
1402 /* XXXX Remove this once Torstat asks for extrainfos. */
1403 routerlist_t *routerlist = router_get_routerlist();
1404 smartlist_t *sl = smartlist_create();
1405 if (routerlist && routerlist->routers) {
1406 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
1408 const char *body = signed_descriptor_get_body(&ri->cache_info);
1409 signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
1410 ri->cache_info.extra_info_digest);
1411 if (ei && body) {
1412 smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
1413 &ri->cache_info, ei));
1414 } else if (body) {
1415 smartlist_add(sl,
1416 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1420 *answer = smartlist_join_strings(sl, "", 0, NULL);
1421 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1422 smartlist_free(sl);
1423 } else if (!strcmpstart(question, "desc-annotations/id/")) {
1424 routerinfo_t *ri = router_get_by_hexdigest(question+
1425 strlen("desc-annotations/id/"));
1426 if (ri) {
1427 const char *annotations =
1428 signed_descriptor_get_annotations(&ri->cache_info);
1429 if (annotations)
1430 *answer = tor_strndup(annotations,
1431 ri->cache_info.annotations_len);
1433 } else if (!strcmpstart(question, "dir/server/")) {
1434 size_t answer_len = 0, url_len = strlen(question)+2;
1435 char *url = tor_malloc(url_len);
1436 smartlist_t *descs = smartlist_create();
1437 const char *msg;
1438 int res;
1439 char *cp;
1440 tor_snprintf(url, url_len, "/tor/%s", question+4);
1441 res = dirserv_get_routerdescs(descs, url, &msg);
1442 if (res) {
1443 log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
1444 smartlist_free(descs);
1445 return -1;
1447 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1448 answer_len += sd->signed_descriptor_len);
1449 cp = *answer = tor_malloc(answer_len+1);
1450 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1452 memcpy(cp, signed_descriptor_get_body(sd),
1453 sd->signed_descriptor_len);
1454 cp += sd->signed_descriptor_len;
1456 *cp = '\0';
1457 tor_free(url);
1458 smartlist_free(descs);
1459 } else if (!strcmpstart(question, "dir/status/")) {
1460 if (directory_permits_controller_requests(get_options())) {
1461 size_t len=0;
1462 char *cp;
1463 smartlist_t *status_list = smartlist_create();
1464 dirserv_get_networkstatus_v2(status_list,
1465 question+strlen("dir/status/"));
1466 SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
1467 cp = *answer = tor_malloc(len+1);
1468 SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
1469 memcpy(cp, d->dir, d->dir_len);
1470 cp += d->dir_len;
1472 *cp = '\0';
1473 smartlist_free(status_list);
1474 } else {
1475 smartlist_t *fp_list = smartlist_create();
1476 smartlist_t *status_list = smartlist_create();
1477 dirserv_get_networkstatus_v2_fingerprints(
1478 fp_list, question+strlen("dir/status/"));
1479 SMARTLIST_FOREACH(fp_list, const char *, fp, {
1480 char *s;
1481 char *fname = networkstatus_get_cache_filename(fp);
1482 s = read_file_to_str(fname, 0, NULL);
1483 if (s)
1484 smartlist_add(status_list, s);
1485 tor_free(fname);
1487 SMARTLIST_FOREACH(fp_list, char *, fp, tor_free(fp));
1488 smartlist_free(fp_list);
1489 *answer = smartlist_join_strings(status_list, "", 0, NULL);
1490 SMARTLIST_FOREACH(status_list, char *, s, tor_free(s));
1491 smartlist_free(status_list);
1493 } else if (!strcmp(question, "network-status")) {
1494 routerlist_t *routerlist = router_get_routerlist();
1495 int verbose = control_conn->use_long_names;
1496 if (!routerlist || !routerlist->routers ||
1497 list_server_status_v1(routerlist->routers, answer,
1498 verbose ? 2 : 1) < 0) {
1499 return -1;
1501 } else if (!strcmpstart(question, "extra-info/digest/")) {
1502 question += strlen("extra-info/digest/");
1503 if (strlen(question) == HEX_DIGEST_LEN) {
1504 char d[DIGEST_LEN];
1505 signed_descriptor_t *sd = NULL;
1506 if (base16_decode(d, sizeof(d), question, strlen(question))==0)
1507 sd = extrainfo_get_by_descriptor_digest(d);
1508 if (sd) {
1509 const char *body = signed_descriptor_get_body(sd);
1510 if (body)
1511 *answer = tor_strndup(body, sd->signed_descriptor_len);
1516 return 0;
1519 /** Implementation helper for GETINFO: knows how to generate summaries of the
1520 * current states of things we send events about. */
1521 static int
1522 getinfo_helper_events(control_connection_t *control_conn,
1523 const char *question, char **answer)
1525 if (!strcmp(question, "circuit-status")) {
1526 circuit_t *circ;
1527 smartlist_t *status = smartlist_create();
1528 for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
1529 char *s, *path;
1530 size_t slen;
1531 const char *state;
1532 if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
1533 continue;
1534 if (control_conn->use_long_names)
1535 path = circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ));
1536 else
1537 path = circuit_list_path(TO_ORIGIN_CIRCUIT(circ),0);
1538 if (circ->state == CIRCUIT_STATE_OPEN)
1539 state = "BUILT";
1540 else if (strlen(path))
1541 state = "EXTENDED";
1542 else
1543 state = "LAUNCHED";
1545 slen = strlen(path)+strlen(state)+20;
1546 s = tor_malloc(slen+1);
1547 tor_snprintf(s, slen, "%lu %s%s%s",
1548 (unsigned long)TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1549 state, *path ? " " : "", path);
1550 smartlist_add(status, s);
1551 tor_free(path);
1553 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1554 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1555 smartlist_free(status);
1556 } else if (!strcmp(question, "stream-status")) {
1557 smartlist_t *conns = get_connection_array();
1558 smartlist_t *status = smartlist_create();
1559 char buf[256];
1560 SMARTLIST_FOREACH(conns, connection_t *, base_conn,
1562 const char *state;
1563 edge_connection_t *conn;
1564 char *s;
1565 size_t slen;
1566 circuit_t *circ;
1567 origin_circuit_t *origin_circ = NULL;
1568 if (base_conn->type != CONN_TYPE_AP ||
1569 base_conn->marked_for_close ||
1570 base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
1571 base_conn->state == AP_CONN_STATE_NATD_WAIT)
1572 continue;
1573 conn = TO_EDGE_CONN(base_conn);
1574 switch (conn->_base.state)
1576 case AP_CONN_STATE_CONTROLLER_WAIT:
1577 case AP_CONN_STATE_CIRCUIT_WAIT:
1578 if (conn->socks_request &&
1579 SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
1580 state = "NEWRESOLVE";
1581 else
1582 state = "NEW";
1583 break;
1584 case AP_CONN_STATE_RENDDESC_WAIT:
1585 case AP_CONN_STATE_CONNECT_WAIT:
1586 state = "SENTCONNECT"; break;
1587 case AP_CONN_STATE_RESOLVE_WAIT:
1588 state = "SENTRESOLVE"; break;
1589 case AP_CONN_STATE_OPEN:
1590 state = "SUCCEEDED"; break;
1591 default:
1592 log_warn(LD_BUG, "Asked for stream in unknown state %d",
1593 conn->_base.state);
1594 continue;
1596 circ = circuit_get_by_edge_conn(conn);
1597 if (circ && CIRCUIT_IS_ORIGIN(circ))
1598 origin_circ = TO_ORIGIN_CIRCUIT(circ);
1599 write_stream_target_to_buf(conn, buf, sizeof(buf));
1600 slen = strlen(buf)+strlen(state)+32;
1601 s = tor_malloc(slen+1);
1602 tor_snprintf(s, slen, "%lu %s %lu %s",
1603 (unsigned long) conn->global_identifier,state,
1604 origin_circ?
1605 (unsigned long)origin_circ->global_identifier : 0ul,
1606 buf);
1607 smartlist_add(status, s);
1609 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1610 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1611 smartlist_free(status);
1612 } else if (!strcmp(question, "orconn-status")) {
1613 smartlist_t *conns = get_connection_array();
1614 smartlist_t *status = smartlist_create();
1615 SMARTLIST_FOREACH(conns, connection_t *, base_conn,
1617 const char *state;
1618 char *s;
1619 char name[128];
1620 size_t slen;
1621 or_connection_t *conn;
1622 if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
1623 continue;
1624 conn = TO_OR_CONN(base_conn);
1625 if (conn->_base.state == OR_CONN_STATE_OPEN)
1626 state = "CONNECTED";
1627 else if (conn->nickname)
1628 state = "LAUNCHED";
1629 else
1630 state = "NEW";
1631 orconn_target_get_name(control_conn->use_long_names, name, sizeof(name),
1632 conn);
1633 slen = strlen(name)+strlen(state)+2;
1634 s = tor_malloc(slen+1);
1635 tor_snprintf(s, slen, "%s %s", name, state);
1636 smartlist_add(status, s);
1638 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1639 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1640 smartlist_free(status);
1641 } else if (!strcmpstart(question, "addr-mappings/") ||
1642 !strcmpstart(question, "address-mappings/")) {
1643 /* XXXX021 Warn about deprecated addr-mappings variant. */
1644 time_t min_e, max_e;
1645 smartlist_t *mappings;
1646 int want_expiry = !strcmpstart(question, "address-mappings/");
1647 question += strlen(want_expiry ? "address-mappings/"
1648 : "addr-mappings/");
1649 if (!strcmp(question, "all")) {
1650 min_e = 0; max_e = TIME_MAX;
1651 } else if (!strcmp(question, "cache")) {
1652 min_e = 2; max_e = TIME_MAX;
1653 } else if (!strcmp(question, "config")) {
1654 min_e = 0; max_e = 0;
1655 } else if (!strcmp(question, "control")) {
1656 min_e = 1; max_e = 1;
1657 } else {
1658 return 0;
1660 mappings = smartlist_create();
1661 addressmap_get_mappings(mappings, min_e, max_e, want_expiry);
1662 *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
1663 SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
1664 smartlist_free(mappings);
1665 } else if (!strcmpstart(question, "status/")) {
1666 /* Note that status/ is not a catch-all for events; there's only supposed
1667 * to be a status GETINFO if there's a corresponding STATUS event. */
1668 if (!strcmp(question, "status/circuit-established")) {
1669 *answer = tor_strdup(has_completed_circuit ? "1" : "0");
1670 } else if (!strcmp(question, "status/enough-dir-info")) {
1671 *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
1672 } else if (!strcmp(question, "status/good-server-descriptor")) {
1673 *answer = tor_strdup(directories_have_accepted_server_descriptor()
1674 ? "1" : "0");
1675 } else if (!strcmp(question, "status/reachability-succeeded/or")) {
1676 *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
1677 } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
1678 *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
1679 } else if (!strcmp(question, "status/reachability-succeeded")) {
1680 *answer = tor_malloc(16);
1681 tor_snprintf(*answer, 16, "OR=%d DIR=%d",
1682 check_whether_orport_reachable() ? 1 : 0,
1683 check_whether_dirport_reachable() ? 1 : 0);
1684 } else if (!strcmpstart(question, "status/version/")) {
1685 int is_server = server_mode(get_options());
1686 networkstatus_t *c = networkstatus_get_latest_consensus();
1687 version_status_t status;
1688 const char *recommended;
1689 if (c) {
1690 recommended = is_server ? c->server_versions : c->client_versions;
1691 status = tor_version_is_obsolete(VERSION, recommended);
1692 } else {
1693 recommended = "?";
1694 status = VS_UNKNOWN;
1697 if (!strcmp(question, "status/version/recommended")) {
1698 *answer = tor_strdup(recommended);
1699 return 0;
1701 if (!strcmp(question, "status/version/current")) {
1702 switch (status)
1704 case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
1705 case VS_OLD: *answer = tor_strdup("obsolete"); break;
1706 case VS_NEW: *answer = tor_strdup("new"); break;
1707 case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
1708 case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
1709 case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
1710 case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
1711 default: tor_fragile_assert();
1713 } else if (!strcmp(question, "status/version/num-versioning") ||
1714 !strcmp(question, "status/version/num-concurring")) {
1715 char s[33];
1716 tor_snprintf(s, sizeof(s), "%d", get_n_authorities(V3_AUTHORITY));
1717 *answer = tor_strdup(s);
1718 log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
1719 "information", question);
1721 } else {
1722 return 0;
1725 return 0;
1728 /** Callback function for GETINFO: on a given control connection, try to
1729 * answer the question <b>q</b> and store the newly-allocated answer in
1730 * *<b>a</b>. If there's no answer, or an error occurs, just don't set
1731 * <b>a</b>. Return 0.
1733 typedef int (*getinfo_helper_t)(control_connection_t *,
1734 const char *q, char **a);
1736 /** A single item for the GETINFO question-to-answer-function table. */
1737 typedef struct getinfo_item_t {
1738 const char *varname; /**< The value (or prefix) of the question. */
1739 getinfo_helper_t fn; /**< The function that knows the answer: NULL if
1740 * this entry is documentation-only. */
1741 const char *desc; /**< Description of the variable. */
1742 int is_prefix; /** Must varname match exactly, or must it be a prefix? */
1743 } getinfo_item_t;
1745 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
1746 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
1747 #define DOC(name, desc) { name, NULL, desc, 0 }
1749 /** Table mapping questions accepted by GETINFO to the functions that know how
1750 * to answer them. */
1751 static const getinfo_item_t getinfo_items[] = {
1752 ITEM("version", misc, "The current version of Tor."),
1753 ITEM("config-file", misc, "Current location of the \"torrc\" file."),
1754 ITEM("accounting/bytes", accounting,
1755 "Number of bytes read/written so far in the accounting interval."),
1756 ITEM("accounting/bytes-left", accounting,
1757 "Number of bytes left to write/read so far in the accounting interval."),
1758 ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
1759 ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
1760 ITEM("accounting/interval-start", accounting,
1761 "Time when the accounting period starts."),
1762 ITEM("accounting/interval-end", accounting,
1763 "Time when the accounting period ends."),
1764 ITEM("accounting/interval-wake", accounting,
1765 "Time to wake up in this accounting period."),
1766 ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
1767 ITEM("entry-guards", entry_guards,
1768 "Which nodes are we using as entry guards?"),
1769 ITEM("fingerprint", misc, NULL),
1770 PREFIX("config/", config, "Current configuration values."),
1771 DOC("config/names",
1772 "List of configuration options, types, and documentation."),
1773 ITEM("info/names", misc,
1774 "List of GETINFO options, types, and documentation."),
1775 ITEM("events/names", misc,
1776 "Events that the controller can ask for with SETEVENTS."),
1777 ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
1778 PREFIX("desc/id/", dir, "Router descriptors by ID."),
1779 PREFIX("desc/name/", dir, "Router descriptors by nickname."),
1780 ITEM("desc/all-recent", dir,
1781 "All non-expired, non-superseded router descriptors."),
1782 ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
1783 PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
1784 ITEM("ns/all", networkstatus,
1785 "Brief summary of router status (v2 directory format)"),
1786 PREFIX("ns/id/", networkstatus,
1787 "Brief summary of router status by ID (v2 directory format)."),
1788 PREFIX("ns/name/", networkstatus,
1789 "Brief summary of router status by nickname (v2 directory format)."),
1790 PREFIX("ns/purpose/", networkstatus,
1791 "Brief summary of router status by purpose (v2 directory format)."),
1793 PREFIX("unregistered-servers-", dirserv_unregistered, NULL),
1794 ITEM("network-status", dir,
1795 "Brief summary of router status (v1 directory format)"),
1796 ITEM("circuit-status", events, "List of current circuits originating here."),
1797 ITEM("stream-status", events,"List of current streams."),
1798 ITEM("orconn-status", events, "A list of current OR connections."),
1799 PREFIX("address-mappings/", events, NULL),
1800 DOC("address-mappings/all", "Current address mappings."),
1801 DOC("address-mappings/cache", "Current cached DNS replies."),
1802 DOC("address-mappings/config",
1803 "Current address mappings from configuration."),
1804 DOC("address-mappings/control", "Current address mappings from controller."),
1805 PREFIX("addr-mappings/", events, NULL),
1806 DOC("addr-mappings/all", "Current address mappings without expiry times."),
1807 DOC("addr-mappings/cache",
1808 "Current cached DNS replies without expiry times."),
1809 DOC("addr-mappings/config",
1810 "Current address mappings from configuration without expiry times."),
1811 DOC("addr-mappings/control",
1812 "Current address mappings from controller without expiry times."),
1813 PREFIX("status/", events, NULL),
1814 DOC("status/circuit-established",
1815 "Whether we think client functionality is working."),
1816 DOC("status/enough-dir-info",
1817 "Whether we have enough up-to-date directory information to build "
1818 "circuits."),
1819 DOC("status/version/recommended", "List of currently recommended versions."),
1820 DOC("status/version/current", "Status of the current version."),
1821 DOC("status/version/num-versioning", "Number of versioning authorities."),
1822 DOC("status/version/num-concurring",
1823 "Number of versioning authorities agreeing on the status of the "
1824 "current version"),
1825 ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
1826 ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
1827 PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
1828 PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
1829 PREFIX("dir/status/", dir,"Networkstatus docs as retrieved from a DirPort."),
1830 PREFIX("exit-policy/default", policies,
1831 "The default value appended to the configured exit policy."),
1832 PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
1833 { NULL, NULL, NULL, 0 }
1836 /** Allocate and return a list of recognized GETINFO options. */
1837 static char *
1838 list_getinfo_options(void)
1840 int i;
1841 char buf[300];
1842 smartlist_t *lines = smartlist_create();
1843 char *ans;
1844 for (i = 0; getinfo_items[i].varname; ++i) {
1845 if (!getinfo_items[i].desc)
1846 continue;
1848 tor_snprintf(buf, sizeof(buf), "%s%s -- %s\n",
1849 getinfo_items[i].varname,
1850 getinfo_items[i].is_prefix ? "*" : "",
1851 getinfo_items[i].desc);
1852 smartlist_add(lines, tor_strdup(buf));
1854 smartlist_sort_strings(lines);
1856 ans = smartlist_join_strings(lines, "", 0, NULL);
1857 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1858 smartlist_free(lines);
1860 return ans;
1863 /** Lookup the 'getinfo' entry <b>question</b>, and return
1864 * the answer in <b>*answer</b> (or NULL if key not recognized).
1865 * Return 0 if success or unrecognized, or -1 if recognized but
1866 * internal error. */
1867 static int
1868 handle_getinfo_helper(control_connection_t *control_conn,
1869 const char *question, char **answer)
1871 int i;
1872 *answer = NULL; /* unrecognized key by default */
1874 for (i = 0; getinfo_items[i].varname; ++i) {
1875 int match;
1876 if (getinfo_items[i].is_prefix)
1877 match = !strcmpstart(question, getinfo_items[i].varname);
1878 else
1879 match = !strcmp(question, getinfo_items[i].varname);
1880 if (match) {
1881 tor_assert(getinfo_items[i].fn);
1882 return getinfo_items[i].fn(control_conn, question, answer);
1886 return 0; /* unrecognized */
1889 /** Called when we receive a GETINFO command. Try to fetch all requested
1890 * information, and reply with information or error message. */
1891 static int
1892 handle_control_getinfo(control_connection_t *conn, uint32_t len,
1893 const char *body)
1895 smartlist_t *questions = NULL;
1896 smartlist_t *answers = NULL;
1897 smartlist_t *unrecognized = NULL;
1898 char *msg = NULL, *ans = NULL;
1899 int i;
1900 (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
1902 questions = smartlist_create();
1903 smartlist_split_string(questions, body, " ",
1904 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1905 answers = smartlist_create();
1906 unrecognized = smartlist_create();
1907 SMARTLIST_FOREACH(questions, const char *, q,
1909 if (handle_getinfo_helper(conn, q, &ans) < 0) {
1910 connection_write_str_to_buf("551 Internal error\r\n", conn);
1911 goto done;
1913 if (!ans) {
1914 smartlist_add(unrecognized, (char*)q);
1915 } else {
1916 smartlist_add(answers, tor_strdup(q));
1917 smartlist_add(answers, ans);
1920 if (smartlist_len(unrecognized)) {
1921 for (i=0; i < smartlist_len(unrecognized)-1; ++i)
1922 connection_printf_to_buf(conn,
1923 "552-Unrecognized key \"%s\"\r\n",
1924 (char*)smartlist_get(unrecognized, i));
1925 connection_printf_to_buf(conn,
1926 "552 Unrecognized key \"%s\"\r\n",
1927 (char*)smartlist_get(unrecognized, i));
1928 goto done;
1931 for (i = 0; i < smartlist_len(answers); i += 2) {
1932 char *k = smartlist_get(answers, i);
1933 char *v = smartlist_get(answers, i+1);
1934 if (!strchr(v, '\n') && !strchr(v, '\r')) {
1935 connection_printf_to_buf(conn, "250-%s=", k);
1936 connection_write_str_to_buf(v, conn);
1937 connection_write_str_to_buf("\r\n", conn);
1938 } else {
1939 char *esc = NULL;
1940 size_t esc_len;
1941 esc_len = write_escaped_data(v, strlen(v), &esc);
1942 connection_printf_to_buf(conn, "250+%s=\r\n", k);
1943 connection_write_to_buf(esc, esc_len, TO_CONN(conn));
1944 tor_free(esc);
1947 connection_write_str_to_buf("250 OK\r\n", conn);
1949 done:
1950 if (answers) {
1951 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
1952 smartlist_free(answers);
1954 if (questions) {
1955 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
1956 smartlist_free(questions);
1958 smartlist_free(unrecognized);
1959 tor_free(msg);
1961 return 0;
1964 /** Given a string, convert it to a circuit purpose. */
1965 static uint8_t
1966 circuit_purpose_from_string(const char *string)
1968 if (!strcmpstart(string, "purpose="))
1969 string += strlen("purpose=");
1971 if (!strcmp(string, "general"))
1972 return CIRCUIT_PURPOSE_C_GENERAL;
1973 else if (!strcmp(string, "controller"))
1974 return CIRCUIT_PURPOSE_CONTROLLER;
1975 else
1976 return CIRCUIT_PURPOSE_UNKNOWN;
1979 /** Return a newly allocated smartlist containing the arguments to the command
1980 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
1981 * or if <b>max_args</b> is nonnegative and there are more than
1982 * <b>max_args</b> arguments, send a 512 error to the controller, using
1983 * <b>command</b> as the command name in the error message. */
1984 static smartlist_t *
1985 getargs_helper(const char *command, control_connection_t *conn,
1986 const char *body, int min_args, int max_args)
1988 smartlist_t *args = smartlist_create();
1989 smartlist_split_string(args, body, " ",
1990 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1991 if (smartlist_len(args) < min_args) {
1992 connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
1993 goto err;
1994 } else if (max_args >= 0 && smartlist_len(args) > max_args) {
1995 connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
1996 goto err;
1998 return args;
1999 err:
2000 SMARTLIST_FOREACH(args, char *, s, tor_free(s));
2001 smartlist_free(args);
2002 return NULL;
2005 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
2006 * circuit, and report success or failure. */
2007 static int
2008 handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
2009 const char *body)
2011 smartlist_t *router_nicknames=NULL, *routers=NULL;
2012 origin_circuit_t *circ = NULL;
2013 int zero_circ;
2014 uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
2015 smartlist_t *args;
2016 (void) len;
2018 router_nicknames = smartlist_create();
2020 args = getargs_helper("EXTENDCIRCUIT", conn, body, 2, -1);
2021 if (!args)
2022 goto done;
2024 zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
2025 if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
2026 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2027 (char*)smartlist_get(args, 0));
2029 smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
2031 if (zero_circ && smartlist_len(args)>2) {
2032 char *purp = smartlist_get(args,2);
2033 intended_purpose = circuit_purpose_from_string(purp);
2034 if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
2035 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
2036 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2037 smartlist_free(args);
2038 goto done;
2041 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2042 smartlist_free(args);
2043 if (!zero_circ && !circ) {
2044 goto done;
2047 routers = smartlist_create();
2048 SMARTLIST_FOREACH(router_nicknames, const char *, n,
2050 routerinfo_t *r = router_get_by_nickname(n, 1);
2051 if (!r) {
2052 connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
2053 goto done;
2055 smartlist_add(routers, r);
2057 if (!smartlist_len(routers)) {
2058 connection_write_str_to_buf("512 No router names provided\r\n", conn);
2059 goto done;
2062 if (zero_circ) {
2063 /* start a new circuit */
2064 circ = origin_circuit_init(intended_purpose, 0);
2067 /* now circ refers to something that is ready to be extended */
2068 SMARTLIST_FOREACH(routers, routerinfo_t *, r,
2070 extend_info_t *info = extend_info_from_router(r);
2071 circuit_append_new_exit(circ, info);
2072 extend_info_free(info);
2075 /* now that we've populated the cpath, start extending */
2076 if (zero_circ) {
2077 int err_reason = 0;
2078 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
2079 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2080 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
2081 goto done;
2083 } else {
2084 if (circ->_base.state == CIRCUIT_STATE_OPEN) {
2085 int err_reason = 0;
2086 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
2087 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
2088 log_info(LD_CONTROL,
2089 "send_next_onion_skin failed; circuit marked for closing.");
2090 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2091 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
2092 goto done;
2097 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
2098 (unsigned long)circ->global_identifier);
2099 if (zero_circ) /* send a 'launched' event, for completeness */
2100 control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
2101 done:
2102 SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
2103 smartlist_free(router_nicknames);
2104 if (routers)
2105 smartlist_free(routers);
2106 return 0;
2109 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
2110 * circuit and it's a valid purpose, change it. */
2111 static int
2112 handle_control_setcircuitpurpose(control_connection_t *conn,
2113 uint32_t len, const char *body)
2115 origin_circuit_t *circ = NULL;
2116 uint8_t new_purpose;
2117 smartlist_t *args;
2118 (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
2120 args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
2121 if (!args)
2122 goto done;
2124 if (!(circ = get_circ(smartlist_get(args,0)))) {
2125 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2126 (char*)smartlist_get(args, 0));
2127 goto done;
2131 char *purp = smartlist_get(args,1);
2132 new_purpose = circuit_purpose_from_string(purp);
2133 if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
2134 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
2135 goto done;
2139 circ->_base.purpose = new_purpose;
2140 connection_write_str_to_buf("250 OK\r\n", conn);
2142 done:
2143 if (args) {
2144 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2145 smartlist_free(args);
2147 return 0;
2150 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
2151 * stream, and report success or failure. */
2152 static int
2153 handle_control_attachstream(control_connection_t *conn, uint32_t len,
2154 const char *body)
2156 edge_connection_t *ap_conn = NULL;
2157 origin_circuit_t *circ = NULL;
2158 int zero_circ;
2159 smartlist_t *args;
2160 crypt_path_t *cpath=NULL;
2161 int hop=0, hop_line_ok=1;
2162 (void) len;
2164 args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
2165 if (!args)
2166 return 0;
2168 zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
2170 if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
2171 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2172 (char*)smartlist_get(args, 0));
2173 } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
2174 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2175 (char*)smartlist_get(args, 1));
2176 } else if (circ && smartlist_len(args) > 2) {
2177 char *hopstring = smartlist_get(args, 2);
2178 if (!strcasecmpstart(hopstring, "HOP=")) {
2179 hopstring += strlen("HOP=");
2180 hop = tor_parse_ulong(hopstring, 10, 0, ULONG_MAX,
2181 &hop_line_ok, NULL);
2182 if (!hop_line_ok) { /* broken hop line */
2183 connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
2187 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2188 smartlist_free(args);
2189 if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
2190 return 0;
2192 if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT &&
2193 ap_conn->_base.state != AP_CONN_STATE_CONNECT_WAIT &&
2194 ap_conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
2195 connection_write_str_to_buf(
2196 "555 Connection is not managed by controller.\r\n",
2197 conn);
2198 return 0;
2201 /* Do we need to detach it first? */
2202 if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT) {
2203 circuit_t *tmpcirc = circuit_get_by_edge_conn(ap_conn);
2204 connection_edge_end(ap_conn, END_STREAM_REASON_TIMEOUT);
2205 /* Un-mark it as ending, since we're going to reuse it. */
2206 ap_conn->_base.edge_has_sent_end = 0;
2207 ap_conn->end_reason = 0;
2208 if (tmpcirc)
2209 circuit_detach_stream(tmpcirc,ap_conn);
2210 ap_conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
2213 if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
2214 connection_write_str_to_buf(
2215 "551 Can't attach stream to non-open origin circuit\r\n",
2216 conn);
2217 return 0;
2219 if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
2220 connection_write_str_to_buf(
2221 "551 Can't attach stream to one-hop circuit.\r\n", conn);
2222 return 0;
2224 if (circ && hop>0) {
2225 /* find this hop in the circuit, and set cpath */
2226 cpath = circuit_get_cpath_hop(circ, hop);
2227 if (!cpath) {
2228 connection_printf_to_buf(conn,
2229 "551 Circuit doesn't have %d hops.\r\n", hop);
2230 return 0;
2233 if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
2234 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
2235 return 0;
2237 send_control_done(conn);
2238 return 0;
2241 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
2242 * descriptor, and report success or failure. */
2243 static int
2244 handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
2245 const char *body)
2247 char *desc;
2248 const char *msg=NULL;
2249 uint8_t purpose = ROUTER_PURPOSE_GENERAL;
2250 int cache = 0; /* eventually, we may switch this to 1 */
2252 char *cp = memchr(body, '\n', len);
2253 smartlist_t *args = smartlist_create();
2254 tor_assert(cp);
2255 *cp++ = '\0';
2257 smartlist_split_string(args, body, " ",
2258 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2259 SMARTLIST_FOREACH(args, char *, option,
2261 if (!strcasecmpstart(option, "purpose=")) {
2262 option += strlen("purpose=");
2263 purpose = router_purpose_from_string(option);
2264 if (purpose == ROUTER_PURPOSE_UNKNOWN) {
2265 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
2266 option);
2267 goto done;
2269 } else if (!strcasecmpstart(option, "cache=")) {
2270 option += strlen("cache=");
2271 if (!strcmp(option, "no"))
2272 cache = 0;
2273 else if (!strcmp(option, "yes"))
2274 cache = 1;
2275 else {
2276 connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
2277 option);
2278 goto done;
2280 } else { /* unrecognized argument? */
2281 connection_printf_to_buf(conn,
2282 "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
2283 goto done;
2287 read_escaped_data(cp, len-(cp-body), &desc);
2289 switch (router_load_single_router(desc, purpose, cache, &msg)) {
2290 case -1:
2291 if (!msg) msg = "Could not parse descriptor";
2292 connection_printf_to_buf(conn, "554 %s\r\n", msg);
2293 break;
2294 case 0:
2295 if (!msg) msg = "Descriptor not added";
2296 connection_printf_to_buf(conn, "251 %s\r\n",msg);
2297 break;
2298 case 1:
2299 send_control_done(conn);
2300 break;
2303 tor_free(desc);
2304 done:
2305 SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
2306 smartlist_free(args);
2307 return 0;
2310 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
2311 * address of the named AP stream, and report success or failure. */
2312 static int
2313 handle_control_redirectstream(control_connection_t *conn, uint32_t len,
2314 const char *body)
2316 edge_connection_t *ap_conn = NULL;
2317 char *new_addr = NULL;
2318 uint16_t new_port = 0;
2319 smartlist_t *args;
2320 (void) len;
2322 args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
2323 if (!args)
2324 return 0;
2326 if (!(ap_conn = get_stream(smartlist_get(args, 0)))
2327 || !ap_conn->socks_request) {
2328 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2329 (char*)smartlist_get(args, 0));
2330 } else {
2331 int ok = 1;
2332 if (smartlist_len(args) > 2) { /* they included a port too */
2333 new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
2334 10, 1, 65535, &ok, NULL);
2336 if (!ok) {
2337 connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
2338 (char*)smartlist_get(args, 2));
2339 } else {
2340 new_addr = tor_strdup(smartlist_get(args, 1));
2344 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2345 smartlist_free(args);
2346 if (!new_addr)
2347 return 0;
2349 strlcpy(ap_conn->socks_request->address, new_addr,
2350 sizeof(ap_conn->socks_request->address));
2351 if (new_port)
2352 ap_conn->socks_request->port = new_port;
2353 tor_free(new_addr);
2354 send_control_done(conn);
2355 return 0;
2358 /** Called when we get a CLOSESTREAM command; try to close the named stream
2359 * and report success or failure. */
2360 static int
2361 handle_control_closestream(control_connection_t *conn, uint32_t len,
2362 const char *body)
2364 edge_connection_t *ap_conn=NULL;
2365 uint8_t reason=0;
2366 smartlist_t *args;
2367 int ok;
2368 (void) len;
2370 args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
2371 if (!args)
2372 return 0;
2374 else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
2375 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2376 (char*)smartlist_get(args, 0));
2377 else {
2378 reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
2379 &ok, NULL);
2380 if (!ok) {
2381 connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
2382 (char*)smartlist_get(args, 1));
2383 ap_conn = NULL;
2386 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2387 smartlist_free(args);
2388 if (!ap_conn)
2389 return 0;
2391 connection_mark_unattached_ap(ap_conn, reason);
2392 send_control_done(conn);
2393 return 0;
2396 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
2397 * and report success or failure. */
2398 static int
2399 handle_control_closecircuit(control_connection_t *conn, uint32_t len,
2400 const char *body)
2402 origin_circuit_t *circ = NULL;
2403 int safe = 0;
2404 smartlist_t *args;
2405 (void) len;
2407 args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
2408 if (!args)
2409 return 0;
2411 if (!(circ=get_circ(smartlist_get(args, 0))))
2412 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2413 (char*)smartlist_get(args, 0));
2414 else {
2415 int i;
2416 for (i=1; i < smartlist_len(args); ++i) {
2417 if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
2418 safe = 1;
2419 else
2420 log_info(LD_CONTROL, "Skipping unknown option %s",
2421 (char*)smartlist_get(args,i));
2424 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2425 smartlist_free(args);
2426 if (!circ)
2427 return 0;
2429 if (!safe || !circ->p_streams) {
2430 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
2433 send_control_done(conn);
2434 return 0;
2437 /** Called when we get a RESOLVE command: start trying to resolve
2438 * the listed addresses. */
2439 static int
2440 handle_control_resolve(control_connection_t *conn, uint32_t len,
2441 const char *body)
2443 smartlist_t *args, *failed;
2444 int is_reverse = 0;
2445 (void) len; /* body is nul-terminated; it's safe to ignore the length */
2447 if (!(conn->event_mask & (1L<<EVENT_ADDRMAP))) {
2448 log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
2449 "isn't listening for ADDRMAP events. It probably won't see "
2450 "the answer.");
2452 args = smartlist_create();
2453 smartlist_split_string(args, body, " ",
2454 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2455 if (smartlist_len(args) &&
2456 !strcasecmp(smartlist_get(args, 0), "mode=reverse")) {
2457 char *cp = smartlist_get(args, 0);
2458 smartlist_del_keeporder(args, 0);
2459 tor_free(cp);
2460 is_reverse = 1;
2462 failed = smartlist_create();
2463 SMARTLIST_FOREACH(args, const char *, arg, {
2464 if (dnsserv_launch_request(arg, is_reverse)<0)
2465 smartlist_add(failed, (char*)arg);
2468 send_control_done(conn);
2469 SMARTLIST_FOREACH(failed, const char *, arg, {
2470 control_event_address_mapped(arg, arg, time(NULL),
2471 "Unable to launch resolve request");
2474 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2475 smartlist_free(args);
2476 smartlist_free(failed);
2477 return 0;
2480 /** Called when we get a PROTOCOLINFO command: send back a reply. */
2481 static int
2482 handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
2483 const char *body)
2485 const char *bad_arg = NULL;
2486 smartlist_t *args;
2487 (void)len;
2489 conn->have_sent_protocolinfo = 1;
2490 args = smartlist_create();
2491 smartlist_split_string(args, body, " ",
2492 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2493 SMARTLIST_FOREACH(args, const char *, arg, {
2494 int ok;
2495 tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
2496 if (!ok) {
2497 bad_arg = arg;
2498 break;
2501 if (bad_arg) {
2502 connection_printf_to_buf(conn, "513 No such version %s\r\n",
2503 escaped(bad_arg));
2504 /* Don't tolerate bad arguments when not authenticated. */
2505 if (!STATE_IS_OPEN(TO_CONN(conn)->state))
2506 connection_mark_for_close(TO_CONN(conn));
2507 goto done;
2508 } else {
2509 or_options_t *options = get_options();
2510 int cookies = options->CookieAuthentication;
2511 char *cfile = get_cookie_file();
2512 char *esc_cfile = esc_for_log(cfile);
2513 char *methods;
2515 int passwd = (options->HashedControlPassword != NULL);
2516 smartlist_t *mlist = smartlist_create();
2517 if (cookies)
2518 smartlist_add(mlist, (char*)"COOKIE");
2519 if (passwd)
2520 smartlist_add(mlist, (char*)"HASHEDPASSWORD");
2521 if (!cookies && !passwd)
2522 smartlist_add(mlist, (char*)"NULL");
2523 methods = smartlist_join_strings(mlist, ",", 0, NULL);
2524 smartlist_free(mlist);
2527 connection_printf_to_buf(conn,
2528 "250-PROTOCOLINFO 1\r\n"
2529 "250-AUTH METHODS=%s%s%s\r\n"
2530 "250-VERSION Tor=%s\r\n"
2531 "250 OK\r\n",
2532 methods,
2533 cookies?" COOKIEFILE=":"",
2534 cookies?esc_cfile:"",
2535 escaped(VERSION));
2536 tor_free(methods);
2537 tor_free(cfile);
2538 tor_free(esc_cfile);
2540 done:
2541 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2542 smartlist_free(args);
2543 return 0;
2546 /** Called when we get a USEFEATURE command: parse the feature list, and
2547 * set up the control_connection's options properly. */
2548 static int
2549 handle_control_usefeature(control_connection_t *conn,
2550 uint32_t len,
2551 const char *body)
2553 smartlist_t *args;
2554 int verbose_names = 0, extended_events = 0;
2555 int bad = 0;
2556 (void) len; /* body is nul-terminated; it's safe to ignore the length */
2557 args = smartlist_create();
2558 smartlist_split_string(args, body, " ",
2559 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2560 SMARTLIST_FOREACH(args, const char *, arg, {
2561 if (!strcasecmp(arg, "VERBOSE_NAMES"))
2562 verbose_names = 1;
2563 else if (!strcasecmp(arg, "EXTENDED_EVENTS")) /* <- documented */
2564 extended_events = 1;
2565 else if (!strcasecmp(arg, "EXTENDED_FORMAT")) {
2566 /* remove this in 0.1.2.4; EXTENDED_FORMAT only ever worked for a
2567 * little while during 0.1.2.2-alpha-dev. */
2568 log_warn(LD_GENERAL,
2569 "EXTENDED_FORMAT is deprecated; use EXTENDED_EVENTS "
2570 "instead.");
2571 extended_events = 1;
2572 } else {
2573 connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
2574 arg);
2575 bad = 1;
2576 break;
2580 if (!bad) {
2581 if (verbose_names) {
2582 conn->use_long_names = 1;
2583 control_update_global_event_mask();
2585 if (extended_events)
2586 conn->use_extended_events = 1;
2587 send_control_done(conn);
2590 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2591 smartlist_free(args);
2592 return 0;
2595 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
2597 connection_control_finished_flushing(control_connection_t *conn)
2599 tor_assert(conn);
2601 connection_stop_writing(TO_CONN(conn));
2602 return 0;
2605 /** Called when <b>conn</b> has gotten its socket closed. */
2607 connection_control_reached_eof(control_connection_t *conn)
2609 tor_assert(conn);
2611 log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
2612 connection_mark_for_close(TO_CONN(conn));
2613 return 0;
2616 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
2617 * stage of the protocol. */
2618 static int
2619 is_valid_initial_command(control_connection_t *conn, const char *cmd)
2621 if (conn->_base.state == CONTROL_CONN_STATE_OPEN)
2622 return 1;
2623 if (!strcasecmp(cmd, "PROTOCOLINFO"))
2624 return !conn->have_sent_protocolinfo;
2625 if (!strcasecmp(cmd, "AUTHENTICATE") ||
2626 !strcasecmp(cmd, "QUIT"))
2627 return 1;
2628 return 0;
2631 /** Do not accept any control command of more than 1MB in length. Anything
2632 * that needs to be anywhere near this long probably means that one of our
2633 * interfaces is broken. */
2634 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
2636 /** Called when data has arrived on a v1 control connection: Try to fetch
2637 * commands from conn->inbuf, and execute them.
2640 connection_control_process_inbuf(control_connection_t *conn)
2642 size_t data_len;
2643 int cmd_len;
2644 char *args;
2646 tor_assert(conn);
2647 tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN ||
2648 conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH);
2650 if (!conn->incoming_cmd) {
2651 conn->incoming_cmd = tor_malloc(1024);
2652 conn->incoming_cmd_len = 1024;
2653 conn->incoming_cmd_cur_len = 0;
2656 if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
2657 peek_buf_has_control0_command(conn->_base.inbuf)) {
2658 /* Detect v0 commands and send a "no more v0" message. */
2659 size_t body_len;
2660 char buf[128];
2661 set_uint16(buf+2, htons(0x0000)); /* type == error */
2662 set_uint16(buf+4, htons(0x0001)); /* code == internal error */
2663 strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
2664 "and later; upgrade your controller.",
2665 sizeof(buf)-6);
2666 body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
2667 set_uint16(buf+0, htons(body_len));
2668 connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
2669 connection_mark_for_close(TO_CONN(conn));
2670 conn->_base.hold_open_until_flushed = 1;
2671 return 0;
2674 again:
2675 while (1) {
2676 size_t last_idx;
2677 int r;
2678 /* First, fetch a line. */
2679 do {
2680 data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
2681 r = fetch_from_buf_line(conn->_base.inbuf,
2682 conn->incoming_cmd+conn->incoming_cmd_cur_len,
2683 &data_len);
2684 if (r == 0)
2685 /* Line not all here yet. Wait. */
2686 return 0;
2687 else if (r == -1) {
2688 if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
2689 connection_write_str_to_buf("500 Line too long.\r\n", conn);
2690 connection_stop_reading(TO_CONN(conn));
2691 connection_mark_for_close(TO_CONN(conn));
2692 conn->_base.hold_open_until_flushed = 1;
2694 while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
2695 conn->incoming_cmd_len *= 2;
2696 conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
2697 conn->incoming_cmd_len);
2699 } while (r != 1);
2701 tor_assert(data_len);
2703 last_idx = conn->incoming_cmd_cur_len;
2704 conn->incoming_cmd_cur_len += data_len;
2706 /* We have appended a line to incoming_cmd. Is the command done? */
2707 if (last_idx == 0 && *conn->incoming_cmd != '+')
2708 /* One line command, didn't start with '+'. */
2709 break;
2710 /* XXXX this code duplication is kind of dumb. */
2711 if (last_idx+3 == conn->incoming_cmd_cur_len &&
2712 !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
2713 /* Just appended ".\r\n"; we're done. Remove it. */
2714 conn->incoming_cmd_cur_len -= 3;
2715 break;
2716 } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
2717 !memcmp(conn->incoming_cmd + last_idx, ".\n", 2)) {
2718 /* Just appended ".\n"; we're done. Remove it. */
2719 conn->incoming_cmd_cur_len -= 2;
2720 break;
2722 /* Otherwise, read another line. */
2724 data_len = conn->incoming_cmd_cur_len;
2725 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
2726 * recognize it.
2728 cmd_len = 0;
2729 while ((size_t)cmd_len < data_len
2730 && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
2731 ++cmd_len;
2733 data_len -= cmd_len;
2734 conn->incoming_cmd[cmd_len]='\0';
2735 args = conn->incoming_cmd+cmd_len+1;
2736 while (*args == ' ' || *args == '\t') {
2737 ++args;
2738 --data_len;
2741 /* Quit is always valid. */
2742 if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
2743 connection_write_str_to_buf("250 closing connection\r\n", conn);
2744 connection_mark_for_close(TO_CONN(conn));
2745 return 0;
2748 if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
2749 !is_valid_initial_command(conn, conn->incoming_cmd)) {
2750 connection_write_str_to_buf("514 Authentication required.\r\n", conn);
2751 connection_mark_for_close(TO_CONN(conn));
2752 return 0;
2755 if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
2756 if (handle_control_setconf(conn, data_len, args))
2757 return -1;
2758 } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
2759 if (handle_control_resetconf(conn, data_len, args))
2760 return -1;
2761 } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
2762 if (handle_control_getconf(conn, data_len, args))
2763 return -1;
2764 } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
2765 if (handle_control_setevents(conn, data_len, args))
2766 return -1;
2767 } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
2768 if (handle_control_authenticate(conn, data_len, args))
2769 return -1;
2770 } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
2771 if (handle_control_saveconf(conn, data_len, args))
2772 return -1;
2773 } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
2774 if (handle_control_signal(conn, data_len, args))
2775 return -1;
2776 } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
2777 if (handle_control_mapaddress(conn, data_len, args))
2778 return -1;
2779 } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
2780 if (handle_control_getinfo(conn, data_len, args))
2781 return -1;
2782 } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
2783 if (handle_control_extendcircuit(conn, data_len, args))
2784 return -1;
2785 } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
2786 if (handle_control_setcircuitpurpose(conn, data_len, args))
2787 return -1;
2788 } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
2789 connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
2790 } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
2791 if (handle_control_attachstream(conn, data_len, args))
2792 return -1;
2793 } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
2794 if (handle_control_postdescriptor(conn, data_len, args))
2795 return -1;
2796 } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
2797 if (handle_control_redirectstream(conn, data_len, args))
2798 return -1;
2799 } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
2800 if (handle_control_closestream(conn, data_len, args))
2801 return -1;
2802 } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
2803 if (handle_control_closecircuit(conn, data_len, args))
2804 return -1;
2805 } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
2806 if (handle_control_usefeature(conn, data_len, args))
2807 return -1;
2808 } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
2809 if (handle_control_resolve(conn, data_len, args))
2810 return -1;
2811 } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
2812 if (handle_control_protocolinfo(conn, data_len, args))
2813 return -1;
2814 } else {
2815 connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
2816 conn->incoming_cmd);
2819 conn->incoming_cmd_cur_len = 0;
2820 goto again;
2823 /** Convert a numeric reason for destroying a circuit into a string for a
2824 * CIRCUIT event. */
2825 static const char *
2826 circuit_end_reason_to_string(int reason)
2828 if (reason >= 0 && reason & END_CIRC_REASON_FLAG_REMOTE)
2829 reason &= ~END_CIRC_REASON_FLAG_REMOTE;
2830 switch (reason) {
2831 case END_CIRC_AT_ORIGIN:
2832 /* This shouldn't get passed here; it's a catch-all reason. */
2833 return "ORIGIN";
2834 case END_CIRC_REASON_NONE:
2835 /* This shouldn't get passed here; it's a catch-all reason. */
2836 return "NONE";
2837 case END_CIRC_REASON_TORPROTOCOL:
2838 return "TORPROTOCOL";
2839 case END_CIRC_REASON_INTERNAL:
2840 return "INTERNAL";
2841 case END_CIRC_REASON_REQUESTED:
2842 return "REQUESTED";
2843 case END_CIRC_REASON_HIBERNATING:
2844 return "HIBERNATING";
2845 case END_CIRC_REASON_RESOURCELIMIT:
2846 return "RESOURCELIMIT";
2847 case END_CIRC_REASON_CONNECTFAILED:
2848 return "CONNECTFAILED";
2849 case END_CIRC_REASON_OR_IDENTITY:
2850 return "OR_IDENTITY";
2851 case END_CIRC_REASON_OR_CONN_CLOSED:
2852 return "OR_CONN_CLOSED";
2853 case END_CIRC_REASON_FINISHED:
2854 return "FINISHED";
2855 case END_CIRC_REASON_TIMEOUT:
2856 return "TIMEOUT";
2857 case END_CIRC_REASON_DESTROYED:
2858 return "DESTROYED";
2859 case END_CIRC_REASON_NOPATH:
2860 return "NOPATH";
2861 case END_CIRC_REASON_NOSUCHSERVICE:
2862 return "NOSUCHSERVICE";
2863 default:
2864 log_warn(LD_BUG, "Unrecognized reason code %d", (int)reason);
2865 return NULL;
2869 /** Something has happened to circuit <b>circ</b>: tell any interested
2870 * control connections. */
2872 control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
2873 int reason_code)
2875 const char *status;
2876 char reason_buf[64];
2877 int providing_reason=0;
2878 char *path=NULL;
2879 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
2880 return 0;
2881 tor_assert(circ);
2883 if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS))
2884 path = circuit_list_path(circ,0);
2886 switch (tp)
2888 case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
2889 case CIRC_EVENT_BUILT: status = "BUILT"; break;
2890 case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
2891 case CIRC_EVENT_FAILED: status = "FAILED"; break;
2892 case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
2893 default:
2894 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
2895 return 0;
2898 if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
2899 const char *reason_str = circuit_end_reason_to_string(reason_code);
2900 char *reason = NULL;
2901 providing_reason=1;
2902 if (!reason_str) {
2903 reason = tor_malloc(16);
2904 tor_snprintf(reason, 16, "UNKNOWN_%d", reason_code);
2905 reason_str = reason;
2907 if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
2908 tor_snprintf(reason_buf, sizeof(reason_buf),
2909 "REASON=DESTROYED REMOTE_REASON=%s", reason_str);
2910 } else {
2911 tor_snprintf(reason_buf, sizeof(reason_buf),
2912 "REASON=%s", reason_str);
2914 tor_free(reason);
2917 if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS)) {
2918 const char *sp = strlen(path) ? " " : "";
2919 if (providing_reason)
2920 send_control_event_extended(EVENT_CIRCUIT_STATUS, SHORT_NAMES,
2921 "650 CIRC %lu %s%s%s@%s\r\n",
2922 (unsigned long)circ->global_identifier,
2923 status, sp, path, reason_buf);
2924 else
2925 send_control_event_extended(EVENT_CIRCUIT_STATUS, SHORT_NAMES,
2926 "650 CIRC %lu %s%s%s\r\n",
2927 (unsigned long)circ->global_identifier,
2928 status, sp, path);
2930 if (EVENT_IS_INTERESTING1L(EVENT_CIRCUIT_STATUS)) {
2931 char *vpath = circuit_list_path_for_controller(circ);
2932 const char *sp = strlen(vpath) ? " " : "";
2933 if (providing_reason)
2934 send_control_event_extended(EVENT_CIRCUIT_STATUS, LONG_NAMES,
2935 "650 CIRC %lu %s%s%s@%s\r\n",
2936 (unsigned long)circ->global_identifier,
2937 status, sp, vpath, reason_buf);
2938 else
2939 send_control_event_extended(EVENT_CIRCUIT_STATUS, LONG_NAMES,
2940 "650 CIRC %lu %s%s%s\r\n",
2941 (unsigned long)circ->global_identifier,
2942 status, sp, vpath);
2943 tor_free(vpath);
2946 tor_free(path);
2948 return 0;
2951 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
2952 * <b>buf</b>, determine the address:port combination requested on
2953 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
2954 * failure. */
2955 static int
2956 write_stream_target_to_buf(edge_connection_t *conn, char *buf, size_t len)
2958 char buf2[256];
2959 if (conn->chosen_exit_name)
2960 if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
2961 return -1;
2962 if (tor_snprintf(buf, len, "%s%s%s:%d",
2963 conn->socks_request->address,
2964 conn->chosen_exit_name ? buf2 : "",
2965 !conn->chosen_exit_name &&
2966 connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
2967 conn->socks_request->port)<0)
2968 return -1;
2969 return 0;
2972 /** Convert the reason for ending a stream <b>reason</b> into the format used
2973 * in STREAM events. Return NULL if the reason is unrecognized. */
2974 static const char *
2975 stream_end_reason_to_string(int reason)
2977 reason &= END_STREAM_REASON_MASK;
2978 switch (reason) {
2979 case END_STREAM_REASON_MISC: return "MISC";
2980 case END_STREAM_REASON_RESOLVEFAILED: return "RESOLVEFAILED";
2981 case END_STREAM_REASON_CONNECTREFUSED: return "CONNECTREFUSED";
2982 case END_STREAM_REASON_EXITPOLICY: return "EXITPOLICY";
2983 case END_STREAM_REASON_DESTROY: return "DESTROY";
2984 case END_STREAM_REASON_DONE: return "DONE";
2985 case END_STREAM_REASON_TIMEOUT: return "TIMEOUT";
2986 case END_STREAM_REASON_HIBERNATING: return "HIBERNATING";
2987 case END_STREAM_REASON_INTERNAL: return "INTERNAL";
2988 case END_STREAM_REASON_RESOURCELIMIT: return "RESOURCELIMIT";
2989 case END_STREAM_REASON_CONNRESET: return "CONNRESET";
2990 case END_STREAM_REASON_TORPROTOCOL: return "TORPROTOCOL";
2991 case END_STREAM_REASON_NOTDIRECTORY: return "NOTDIRECTORY";
2993 case END_STREAM_REASON_CANT_ATTACH: return "CANT_ATTACH";
2994 case END_STREAM_REASON_NET_UNREACHABLE: return "NET_UNREACHABLE";
2995 case END_STREAM_REASON_SOCKSPROTOCOL: return "SOCKS_PROTOCOL";
2997 default: return NULL;
3001 /** Something has happened to the stream associated with AP connection
3002 * <b>conn</b>: tell any interested control connections. */
3004 control_event_stream_status(edge_connection_t *conn, stream_status_event_t tp,
3005 int reason_code)
3007 char reason_buf[64];
3008 char addrport_buf[64];
3009 const char *status;
3010 circuit_t *circ;
3011 origin_circuit_t *origin_circ = NULL;
3012 char buf[256];
3013 tor_assert(conn->socks_request);
3015 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
3016 return 0;
3018 if (tp == STREAM_EVENT_CLOSED &&
3019 (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
3020 return 0;
3022 write_stream_target_to_buf(conn, buf, sizeof(buf));
3024 reason_buf[0] = '\0';
3025 switch (tp)
3027 case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
3028 case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
3029 case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
3030 case STREAM_EVENT_FAILED: status = "FAILED"; break;
3031 case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
3032 case STREAM_EVENT_NEW: status = "NEW"; break;
3033 case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
3034 case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
3035 case STREAM_EVENT_REMAP: status = "REMAP"; break;
3036 default:
3037 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3038 return 0;
3040 if (reason_code && (tp == STREAM_EVENT_FAILED ||
3041 tp == STREAM_EVENT_CLOSED ||
3042 tp == STREAM_EVENT_FAILED_RETRIABLE)) {
3043 const char *reason_str = stream_end_reason_to_string(reason_code);
3044 char *r = NULL;
3045 if (!reason_str) {
3046 r = tor_malloc(16);
3047 tor_snprintf(r, 16, "UNKNOWN_%d", reason_code);
3048 reason_str = r;
3050 if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
3051 tor_snprintf(reason_buf, sizeof(reason_buf),
3052 "REASON=END REMOTE_REASON=%s", reason_str);
3053 else
3054 tor_snprintf(reason_buf, sizeof(reason_buf),
3055 "REASON=%s", reason_str);
3056 tor_free(r);
3057 } else if (reason_code && tp == STREAM_EVENT_REMAP) {
3058 switch (reason_code) {
3059 case REMAP_STREAM_SOURCE_CACHE:
3060 strlcpy(reason_buf, "SOURCE=CACHE", sizeof(reason_buf));
3061 break;
3062 case REMAP_STREAM_SOURCE_EXIT:
3063 strlcpy(reason_buf, "SOURCE=EXIT", sizeof(reason_buf));
3064 break;
3065 default:
3066 tor_snprintf(reason_buf, sizeof(reason_buf), "REASON=UNKNOWN_%d",
3067 reason_code);
3068 break;
3072 if (tp == STREAM_EVENT_NEW) {
3073 tor_snprintf(addrport_buf,sizeof(addrport_buf), "%sSOURCE_ADDR=%s:%d",
3074 strlen(reason_buf) ? " " : "",
3075 TO_CONN(conn)->address, TO_CONN(conn)->port );
3076 } else {
3077 addrport_buf[0] = '\0';
3080 circ = circuit_get_by_edge_conn(conn);
3081 if (circ && CIRCUIT_IS_ORIGIN(circ))
3082 origin_circ = TO_ORIGIN_CIRCUIT(circ);
3083 send_control_event_extended(EVENT_STREAM_STATUS, ALL_NAMES,
3084 "650 STREAM %lu %s %lu %s@%s%s\r\n",
3085 (unsigned long)conn->global_identifier, status,
3086 origin_circ?
3087 (unsigned long)origin_circ->global_identifier : 0ul,
3088 buf, reason_buf, addrport_buf);
3090 /* XXX need to specify its intended exit, etc? */
3092 return 0;
3095 /** Figure out the best name for the target router of an OR connection
3096 * <b>conn</b>, and write it into the <b>len</b>-character buffer
3097 * <b>name</b>. Use verbose names if <b>long_names</b> is set. */
3098 static void
3099 orconn_target_get_name(int long_names,
3100 char *name, size_t len, or_connection_t *conn)
3102 if (! long_names) {
3103 if (conn->nickname)
3104 strlcpy(name, conn->nickname, len);
3105 else
3106 tor_snprintf(name, len, "%s:%d",
3107 conn->_base.address, conn->_base.port);
3108 } else {
3109 routerinfo_t *ri = router_get_by_digest(conn->identity_digest);
3110 if (ri) {
3111 tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
3112 router_get_verbose_nickname(name, ri);
3113 } else if (! tor_digest_is_zero(conn->identity_digest)) {
3114 name[0] = '$';
3115 base16_encode(name+1, len-1, conn->identity_digest,
3116 DIGEST_LEN);
3117 } else {
3118 tor_snprintf(name, len, "%s:%d",
3119 conn->_base.address, conn->_base.port);
3124 /** Convert a TOR_TLS_* error code into an END_OR_CONN_* reason. */
3126 control_tls_error_to_reason(int e)
3128 switch (e) {
3129 case TOR_TLS_ERROR_IO:
3130 return END_OR_CONN_REASON_TLS_IO_ERROR;
3131 case TOR_TLS_ERROR_CONNREFUSED:
3132 return END_OR_CONN_REASON_TCP_REFUSED;
3133 case TOR_TLS_ERROR_CONNRESET:
3134 return END_OR_CONN_REASON_TLS_CONNRESET;
3135 case TOR_TLS_ERROR_NO_ROUTE:
3136 return END_OR_CONN_REASON_TLS_NO_ROUTE;
3137 case TOR_TLS_ERROR_TIMEOUT:
3138 return END_OR_CONN_REASON_TLS_TIMEOUT;
3139 case TOR_TLS_WANTREAD:
3140 case TOR_TLS_WANTWRITE:
3141 case TOR_TLS_CLOSE:
3142 case TOR_TLS_DONE:
3143 return END_OR_CONN_REASON_DONE;
3144 default:
3145 return END_OR_CONN_REASON_TLS_MISC;
3149 /** Convert the reason for ending an OR connection <b>r</b> into the format
3150 * used in ORCONN events. Return NULL if the reason is unrecognized. */
3151 static const char *
3152 or_conn_end_reason_to_string(int r)
3154 switch (r) {
3155 case END_OR_CONN_REASON_DONE:
3156 return "REASON=DONE";
3157 case END_OR_CONN_REASON_TCP_REFUSED:
3158 return "REASON=CONNECTREFUSED";
3159 case END_OR_CONN_REASON_OR_IDENTITY:
3160 return "REASON=IDENTITY";
3161 case END_OR_CONN_REASON_TLS_CONNRESET:
3162 return "REASON=CONNECTRESET";
3163 case END_OR_CONN_REASON_TLS_TIMEOUT:
3164 return "REASON=TIMEOUT";
3165 case END_OR_CONN_REASON_TLS_NO_ROUTE:
3166 return "REASON=NOROUTE";
3167 case END_OR_CONN_REASON_TLS_IO_ERROR:
3168 return "REASON=IOERROR";
3169 case END_OR_CONN_REASON_TLS_MISC:
3170 return "REASON=MISC";
3171 case 0:
3172 return "";
3173 default:
3174 log_warn(LD_BUG, "Unrecognized or_conn reason code %d", r);
3175 return "REASON=BOGUS";
3179 /** Called when the status of an OR connection <b>conn</b> changes: tell any
3180 * interested control connections. <b>tp</b> is the new status for the
3181 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
3182 * may be the reason why.
3185 control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
3186 int reason)
3188 int ncircs = 0;
3189 const char *status;
3190 char name[128];
3191 char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
3193 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
3194 return 0;
3196 switch (tp)
3198 case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
3199 case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
3200 case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
3201 case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
3202 case OR_CONN_EVENT_NEW: status = "NEW"; break;
3203 default:
3204 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3205 return 0;
3207 ncircs = circuit_count_pending_on_or_conn(conn);
3208 ncircs += conn->n_circuits;
3209 if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
3210 tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
3211 reason ? " " : "", ncircs);
3214 if (EVENT_IS_INTERESTING1S(EVENT_OR_CONN_STATUS)) {
3215 orconn_target_get_name(0, name, sizeof(name), conn);
3216 send_control_event_extended(EVENT_OR_CONN_STATUS, SHORT_NAMES,
3217 "650 ORCONN %s %s@%s%s\r\n",
3218 name, status,
3219 or_conn_end_reason_to_string(reason), ncircs_buf);
3221 if (EVENT_IS_INTERESTING1L(EVENT_OR_CONN_STATUS)) {
3222 orconn_target_get_name(1, name, sizeof(name), conn);
3223 send_control_event_extended(EVENT_OR_CONN_STATUS, LONG_NAMES,
3224 "650 ORCONN %s %s@%s%s\r\n",
3225 name, status,
3226 or_conn_end_reason_to_string(reason), ncircs_buf);
3229 return 0;
3232 /** A second or more has elapsed: tell any interested control
3233 * connections how much bandwidth streams have used. */
3235 control_event_stream_bandwidth_used(void)
3237 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
3238 smartlist_t *conns = get_connection_array();
3239 edge_connection_t *edge_conn;
3241 SMARTLIST_FOREACH(conns, connection_t *, conn,
3243 if (conn->type != CONN_TYPE_AP)
3244 continue;
3245 edge_conn = TO_EDGE_CONN(conn);
3246 if (!edge_conn->n_read && !edge_conn->n_written)
3247 continue;
3249 send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_NAMES,
3250 "650 STREAM_BW %lu %lu %lu\r\n",
3251 (unsigned long)edge_conn->global_identifier,
3252 (unsigned long)edge_conn->n_read,
3253 (unsigned long)edge_conn->n_written);
3255 edge_conn->n_written = edge_conn->n_read = 0;
3259 return 0;
3262 /** A second or more has elapsed: tell any interested control
3263 * connections how much bandwidth we used. */
3265 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
3267 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
3268 send_control_event(EVENT_BANDWIDTH_USED, ALL_NAMES,
3269 "650 BW %lu %lu\r\n",
3270 (unsigned long)n_read,
3271 (unsigned long)n_written);
3274 return 0;
3277 /** Called when we are sending a log message to the controllers: suspend
3278 * sending further log messages to the controllers until we're done. Used by
3279 * CONN_LOG_PROTECT. */
3280 void
3281 disable_control_logging(void)
3283 ++disable_log_messages;
3286 /** We're done sending a log message to the controllers: re-enable controller
3287 * logging. Used by CONN_LOG_PROTECT. */
3288 void
3289 enable_control_logging(void)
3291 if (--disable_log_messages < 0)
3292 tor_assert(0);
3295 /** We got a log message: tell any interested control connections. */
3296 void
3297 control_event_logmsg(int severity, uint32_t domain, const char *msg)
3299 int event;
3301 if (disable_log_messages)
3302 return;
3304 if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
3305 severity <= LOG_NOTICE) {
3306 char *esc = esc_for_log(msg);
3307 ++disable_log_messages;
3308 control_event_general_status(severity, "BUG REASON=\"%s\"", esc);
3309 --disable_log_messages;
3310 tor_free(esc);
3313 event = log_severity_to_event(severity);
3314 if (event >= 0 && EVENT_IS_INTERESTING(event)) {
3315 char *b = NULL;
3316 const char *s;
3317 if (strchr(msg, '\n')) {
3318 char *cp;
3319 b = tor_strdup(msg);
3320 for (cp = b; *cp; ++cp)
3321 if (*cp == '\r' || *cp == '\n')
3322 *cp = ' ';
3324 switch (severity) {
3325 case LOG_DEBUG: s = "DEBUG"; break;
3326 case LOG_INFO: s = "INFO"; break;
3327 case LOG_NOTICE: s = "NOTICE"; break;
3328 case LOG_WARN: s = "WARN"; break;
3329 case LOG_ERR: s = "ERR"; break;
3330 default: s = "UnknownLogSeverity"; break;
3332 ++disable_log_messages;
3333 send_control_event(event, ALL_NAMES, "650 %s %s\r\n", s, b?b:msg);
3334 --disable_log_messages;
3335 tor_free(b);
3339 /** Called whenever we receive new router descriptors: tell any
3340 * interested control connections. <b>routers</b> is a list of
3341 * routerinfo_t's.
3344 control_event_descriptors_changed(smartlist_t *routers)
3346 size_t len;
3347 char *msg;
3348 smartlist_t *identities = NULL;
3349 char buf[HEX_DIGEST_LEN+1];
3351 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
3352 return 0;
3353 if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC)) {
3354 identities = smartlist_create();
3355 SMARTLIST_FOREACH(routers, routerinfo_t *, r,
3357 base16_encode(buf,sizeof(buf),r->cache_info.identity_digest,DIGEST_LEN);
3358 smartlist_add(identities, tor_strdup(buf));
3361 if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC)) {
3362 char *ids = smartlist_join_strings(identities, " ", 0, &len);
3363 size_t ids_len = strlen(ids)+32;
3364 msg = tor_malloc(ids_len);
3365 tor_snprintf(msg, ids_len, "650 NEWDESC %s\r\n", ids);
3366 send_control_event_string(EVENT_NEW_DESC, SHORT_NAMES|ALL_FORMATS, msg);
3367 tor_free(ids);
3368 tor_free(msg);
3370 if (EVENT_IS_INTERESTING1L(EVENT_NEW_DESC)) {
3371 smartlist_t *names = smartlist_create();
3372 char *ids;
3373 size_t names_len;
3374 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
3375 char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
3376 router_get_verbose_nickname(b, ri);
3377 smartlist_add(names, b);
3379 ids = smartlist_join_strings(names, " ", 0, &names_len);
3380 names_len = strlen(ids)+32;
3381 msg = tor_malloc(names_len);
3382 tor_snprintf(msg, names_len, "650 NEWDESC %s\r\n", ids);
3383 send_control_event_string(EVENT_NEW_DESC, LONG_NAMES|ALL_FORMATS, msg);
3384 tor_free(ids);
3385 tor_free(msg);
3386 SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
3387 smartlist_free(names);
3389 if (identities) {
3390 SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
3391 smartlist_free(identities);
3393 return 0;
3396 /** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
3397 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
3398 * <b>error</b> is non-NULL, it is an error code describing the failure
3399 * mode of the mapping.
3402 control_event_address_mapped(const char *from, const char *to, time_t expires,
3403 const char *error)
3405 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
3406 return 0;
3408 if (expires < 3 || expires == TIME_MAX)
3409 send_control_event_extended(EVENT_ADDRMAP, ALL_NAMES,
3410 "650 ADDRMAP %s %s NEVER@%s\r\n", from, to,
3411 error?error:"");
3412 else {
3413 char buf[ISO_TIME_LEN+1];
3414 char buf2[ISO_TIME_LEN+1];
3415 format_local_iso_time(buf,expires);
3416 format_iso_time(buf2,expires);
3417 send_control_event_extended(EVENT_ADDRMAP, ALL_NAMES,
3418 "650 ADDRMAP %s %s \"%s\""
3419 "@%s%sEXPIRES=\"%s\"\r\n",
3420 from, to, buf,
3421 error?error:"", error?" ":"",
3422 buf2);
3425 return 0;
3428 /** The authoritative dirserver has received a new descriptor that
3429 * has passed basic syntax checks and is properly self-signed.
3431 * Notify any interested party of the new descriptor and what has
3432 * been done with it, and also optionally give an explanation/reason. */
3434 control_event_or_authdir_new_descriptor(const char *action,
3435 const char *desc, size_t desclen,
3436 const char *msg)
3438 char firstline[1024];
3439 char *buf;
3440 int totallen;
3441 char *esc = NULL;
3442 size_t esclen;
3444 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
3445 return 0;
3447 tor_snprintf(firstline, sizeof(firstline),
3448 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
3449 action,
3450 msg ? msg : "");
3452 /* Escape the server descriptor properly */
3453 esclen = write_escaped_data(desc, desclen, &esc);
3455 totallen = strlen(firstline) + esclen + 1;
3456 buf = tor_malloc(totallen);
3457 strlcpy(buf, firstline, totallen);
3458 strlcpy(buf+strlen(firstline), esc, totallen);
3459 send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_NAMES|ALL_FORMATS,
3460 buf);
3461 send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_NAMES|ALL_FORMATS,
3462 "650 OK\r\n");
3463 tor_free(esc);
3464 tor_free(buf);
3466 return 0;
3469 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
3470 * an NS event to any controller that cares. */
3472 control_event_networkstatus_changed(smartlist_t *statuses)
3474 smartlist_t *strs;
3475 char *s, *esc = NULL;
3476 if (!EVENT_IS_INTERESTING(EVENT_NS) || !smartlist_len(statuses))
3477 return 0;
3479 strs = smartlist_create();
3480 smartlist_add(strs, tor_strdup("650+NS\r\n"));
3481 SMARTLIST_FOREACH(statuses, routerstatus_t *, rs,
3483 s = networkstatus_getinfo_helper_single(rs);
3484 if (!s) continue;
3485 smartlist_add(strs, s);
3488 s = smartlist_join_strings(strs, "", 0, NULL);
3489 write_escaped_data(s, strlen(s), &esc);
3490 SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
3491 smartlist_free(strs);
3492 tor_free(s);
3493 send_control_event_string(EVENT_NS, ALL_NAMES|ALL_FORMATS, esc);
3494 send_control_event_string(EVENT_NS, ALL_NAMES|ALL_FORMATS,
3495 "650 OK\r\n");
3497 tor_free(esc);
3498 return 0;
3501 /** Called when a single local_routerstatus_t has changed: Sends an NS event
3502 * to any countroller that cares. */
3504 control_event_networkstatus_changed_single(routerstatus_t *rs)
3506 smartlist_t *statuses;
3507 int r;
3509 if (!EVENT_IS_INTERESTING(EVENT_NS))
3510 return 0;
3512 statuses = smartlist_create();
3513 smartlist_add(statuses, rs);
3514 r = control_event_networkstatus_changed(statuses);
3515 smartlist_free(statuses);
3516 return r;
3519 /** Our own router descriptor has changed; tell any controllers that care.
3522 control_event_my_descriptor_changed(void)
3524 send_control_event(EVENT_DESCCHANGED, ALL_NAMES, "650 DESCCHANGED\r\n");
3525 return 0;
3528 /** Helper: sends a status event where <b>type</b> is one of
3529 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
3530 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
3531 * string corresponding to <b>args</b>. */
3532 static int
3533 control_event_status(int type, int severity, const char *format, va_list args)
3535 char format_buf[160];
3536 const char *status, *sev;
3538 switch (type) {
3539 case EVENT_STATUS_GENERAL:
3540 status = "STATUS_GENERAL";
3541 break;
3542 case EVENT_STATUS_CLIENT:
3543 status = "STATUS_CLIENT";
3544 break;
3545 case EVENT_STATUS_SERVER:
3546 status = "STATUS_SEVER";
3547 break;
3548 default:
3549 log_warn(LD_BUG, "Unrecognized status type %d", type);
3550 return -1;
3552 switch (severity) {
3553 case LOG_NOTICE:
3554 sev = "NOTICE";
3555 break;
3556 case LOG_WARN:
3557 sev = "WARN";
3558 break;
3559 case LOG_ERR:
3560 sev = "ERR";
3561 break;
3562 default:
3563 log_warn(LD_BUG, "Unrecognized status severity %d", severity);
3564 return -1;
3566 if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s %s\r\n",
3567 status, sev, format)<0) {
3568 log_warn(LD_BUG, "Format string too long.");
3569 return -1;
3572 send_control_event_impl(type, ALL_NAMES|ALL_FORMATS, 0, format_buf, args);
3573 return 0;
3576 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
3577 * by formatting the arguments using the printf-style <b>format</b>. */
3579 control_event_general_status(int severity, const char *format, ...)
3581 va_list ap;
3582 int r;
3583 if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
3584 return 0;
3586 va_start(ap, format);
3587 r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
3588 va_end(ap);
3589 return r;
3592 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
3593 * by formatting the arguments using the printf-style <b>format</b>. */
3595 control_event_client_status(int severity, const char *format, ...)
3597 va_list ap;
3598 int r;
3599 if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
3600 return 0;
3602 va_start(ap, format);
3603 r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
3604 va_end(ap);
3605 return r;
3608 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
3609 * by formatting the arguments using the printf-style <b>format</b>. */
3611 control_event_server_status(int severity, const char *format, ...)
3613 va_list ap;
3614 int r;
3615 if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
3616 return 0;
3618 va_start(ap, format);
3619 r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
3620 va_end(ap);
3621 return r;
3624 /** Called when the status of an entry guard with the given <b>nickname</b>
3625 * and identity <b>digest</b> has changed to <b>status</b>: tells any
3626 * controllers that care. */
3628 control_event_guard(const char *nickname, const char *digest,
3629 const char *status)
3631 char hbuf[HEX_DIGEST_LEN+1];
3632 base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
3633 if (!EVENT_IS_INTERESTING(EVENT_GUARD))
3634 return 0;
3636 if (EVENT_IS_INTERESTING1L(EVENT_GUARD)) {
3637 char buf[MAX_VERBOSE_NICKNAME_LEN+1];
3638 routerinfo_t *ri = router_get_by_digest(digest);
3639 if (ri) {
3640 router_get_verbose_nickname(buf, ri);
3641 } else {
3642 tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
3644 send_control_event(EVENT_GUARD, LONG_NAMES,
3645 "650 GUARD ENTRY %s %s\r\n", buf, status);
3647 if (EVENT_IS_INTERESTING1S(EVENT_GUARD)) {
3648 send_control_event(EVENT_GUARD, SHORT_NAMES,
3649 "650 GUARD ENTRY $%s %s\r\n", hbuf, status);
3651 return 0;
3654 /** Helper: Return a newly allocated string containing a path to the
3655 * file where we store our authentication cookie. */
3656 static char *
3657 get_cookie_file(void)
3659 or_options_t *options = get_options();
3660 if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
3661 return tor_strdup(options->CookieAuthFile);
3662 } else {
3663 return get_datadir_fname("control_auth_cookie");
3667 /** Choose a random authentication cookie and write it to disk.
3668 * Anybody who can read the cookie from disk will be considered
3669 * authorized to use the control connection. Return -1 if we can't
3670 * write the file, or 0 on success. */
3672 init_cookie_authentication(int enabled)
3674 char *fname;
3675 if (!enabled) {
3676 authentication_cookie_is_set = 0;
3677 return 0;
3680 /* We don't want to generate a new cookie every time we call
3681 * options_act(). One should be enough. */
3682 if (authentication_cookie_is_set)
3683 return 0; /* all set */
3685 fname = get_cookie_file();
3686 crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
3687 authentication_cookie_is_set = 1;
3688 if (write_bytes_to_file(fname, authentication_cookie,
3689 AUTHENTICATION_COOKIE_LEN, 1)) {
3690 log_warn(LD_FS,"Error writing authentication cookie to %s.",
3691 escaped(fname));
3692 tor_free(fname);
3693 return -1;
3695 #ifndef MS_WINDOWS
3696 if (get_options()->CookieAuthFileGroupReadable) {
3697 if (chmod(fname, 0640)) {
3698 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
3701 #endif
3703 tor_free(fname);
3704 return 0;