r14602@catbus: nickm | 2007-08-16 13:33:27 -0400
[tor.git] / src / or / control.c
blob80ea17bed0b53871dadba7c76ccf32b950bb8208
1 /* Copyright 2004-2007 Roger Dingledine, Nick Mathewson. */
2 /* See LICENSE for licensing information */
3 /* $Id$ */
4 const char control_c_id[] =
5 "$Id$";
7 /**
8 * \file control.c
9 * \brief Implementation for Tor's control-socket interface.
10 **/
12 #include "or.h"
14 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
15 * finished authentication and is accepting commands. */
16 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN_V1)
19 * See control-spec.txt for full details on protocol.
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
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 LAST_V0_EVENT 0x000B
39 #define EVENT_ADDRMAP 0x000C
40 #define EVENT_AUTHDIR_NEWDESCS 0x000D
41 #define EVENT_DESCCHANGED 0x000E
42 #define EVENT_NS 0x000F
43 #define EVENT_STATUS_CLIENT 0x0010
44 #define EVENT_STATUS_SERVER 0x0011
45 #define EVENT_STATUS_GENERAL 0x0012
46 #define EVENT_GUARD 0x0013
47 #define EVENT_STREAM_BANDWIDTH_USED 0x0014
48 #define _EVENT_MAX 0x0014
49 /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
51 /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
52 * connection is interested in events of type <b>e</b>. We use this
53 * so that we can decide to skip generating event messages that nobody
54 * has interest in without having to walk over the global connection
55 * list to find out.
56 **/
57 typedef uint32_t event_mask_t;
58 static event_mask_t global_event_mask1long = 0;
59 static event_mask_t global_event_mask1short = 0;
61 /** True iff we have disabled log messages from being sent to the controller */
62 static int disable_log_messages = 0;
64 /** Macro: true if any control connection is interested in events of type
65 * <b>e</b>. */
66 #define EVENT_IS_INTERESTING1(e) \
67 ((global_event_mask1long|global_event_mask1short) & (1<<(e)))
68 #define EVENT_IS_INTERESTING1L(e) (global_event_mask1long & (1<<(e)))
69 #define EVENT_IS_INTERESTING1S(e) (global_event_mask1short & (1<<(e)))
70 #define EVENT_IS_INTERESTING(e) \
71 ((global_event_mask1short|global_event_mask1long) \
72 & (1<<(e)))
74 /** If we're using cookie-type authentication, how long should our cookies be?
76 #define AUTHENTICATION_COOKIE_LEN 32
78 /** If true, we've set authentication_cookie to a secret code and
79 * stored it to disk. */
80 static int authentication_cookie_is_set = 0;
81 static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
83 #define SHORT_NAMES 1
84 #define LONG_NAMES 2
85 #define ALL_NAMES (SHORT_NAMES|LONG_NAMES)
86 #define EXTENDED_FORMAT 4
87 #define NONEXTENDED_FORMAT 8
88 #define ALL_FORMATS (EXTENDED_FORMAT|NONEXTENDED_FORMAT)
89 typedef int event_format_t;
91 static void connection_printf_to_buf(control_connection_t *conn,
92 const char *format, ...)
93 CHECK_PRINTF(2,3);
94 /*static*/ size_t write_escaped_data(const char *data, size_t len,
95 int translate_newlines, char **out);
96 /*static*/ size_t read_escaped_data(const char *data, size_t len,
97 int translate_newlines, char **out);
98 static void send_control_done(control_connection_t *conn);
99 static void send_control1_event(uint16_t event, event_format_t which,
100 const char *format, ...)
101 CHECK_PRINTF(3,4);
102 static void send_control1_event_extended(uint16_t event, event_format_t which,
103 const char *format, ...)
104 CHECK_PRINTF(3,4);
105 static int handle_control_setconf(control_connection_t *conn, uint32_t len,
106 char *body);
107 static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
108 char *body);
109 static int handle_control_getconf(control_connection_t *conn, uint32_t len,
110 const char *body);
111 static int handle_control_setevents(control_connection_t *conn, uint32_t len,
112 const char *body);
113 static int handle_control_authenticate(control_connection_t *conn,
114 uint32_t len,
115 const char *body);
116 static int handle_control_saveconf(control_connection_t *conn, uint32_t len,
117 const char *body);
118 static int handle_control_signal(control_connection_t *conn, uint32_t len,
119 const char *body);
120 static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
121 const char *body);
122 static char *list_getinfo_options(void);
123 static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
124 const char *body);
125 static int handle_control_extendcircuit(control_connection_t *conn,
126 uint32_t len,
127 const char *body);
128 static int handle_control_setpurpose(control_connection_t *conn,
129 int for_circuits,
130 uint32_t len, const char *body);
131 static int handle_control_attachstream(control_connection_t *conn,
132 uint32_t len,
133 const char *body);
134 static int handle_control_postdescriptor(control_connection_t *conn,
135 uint32_t len,
136 const char *body);
137 static int handle_control_redirectstream(control_connection_t *conn,
138 uint32_t len,
139 const char *body);
140 static int handle_control_closestream(control_connection_t *conn, uint32_t len,
141 const char *body);
142 static int handle_control_closecircuit(control_connection_t *conn,
143 uint32_t len,
144 const char *body);
145 static int handle_control_usefeature(control_connection_t *conn,
146 uint32_t len,
147 const char *body);
148 static int write_stream_target_to_buf(edge_connection_t *conn, char *buf,
149 size_t len);
150 static void orconn_target_get_name(int long_names, char *buf, size_t len,
151 or_connection_t *conn);
153 /** Given a control event code for a message event, return the corresponding
154 * log severity. */
155 static INLINE int
156 event_to_log_severity(int event)
158 switch (event) {
159 case EVENT_DEBUG_MSG: return LOG_DEBUG;
160 case EVENT_INFO_MSG: return LOG_INFO;
161 case EVENT_NOTICE_MSG: return LOG_NOTICE;
162 case EVENT_WARN_MSG: return LOG_WARN;
163 case EVENT_ERR_MSG: return LOG_ERR;
164 default: return -1;
168 /** Given a log severity, return the corresponding control event code. */
169 static INLINE int
170 log_severity_to_event(int severity)
172 switch (severity) {
173 case LOG_DEBUG: return EVENT_DEBUG_MSG;
174 case LOG_INFO: return EVENT_INFO_MSG;
175 case LOG_NOTICE: return EVENT_NOTICE_MSG;
176 case LOG_WARN: return EVENT_WARN_MSG;
177 case LOG_ERR: return EVENT_ERR_MSG;
178 default: return -1;
182 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
183 * connection's event_mask field. */
184 void
185 control_update_global_event_mask(void)
187 connection_t **conns;
188 int n_conns, i;
189 event_mask_t old_mask, new_mask;
190 old_mask = global_event_mask1short;
191 old_mask |= global_event_mask1long;
193 global_event_mask1short = 0;
194 global_event_mask1long = 0;
195 get_connection_array(&conns, &n_conns);
196 for (i = 0; i < n_conns; ++i) {
197 if (conns[i]->type == CONN_TYPE_CONTROL &&
198 STATE_IS_OPEN(conns[i]->state)) {
199 control_connection_t *conn = TO_CONTROL_CONN(conns[i]);
200 if (conn->use_long_names)
201 global_event_mask1long |= conn->event_mask;
202 else
203 global_event_mask1short |= conn->event_mask;
207 new_mask = global_event_mask1short;
208 new_mask |= global_event_mask1long;
210 /* Handle the aftermath. Set up the log callback to tell us only what
211 * we want to hear...*/
212 control_adjust_event_log_severity();
214 /* ...then, if we've started logging stream bw, clear the appropriate
215 * fields. */
216 if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
217 (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
218 for (i = 0; i < n_conns; ++i) {
219 if (conns[i]->type == CONN_TYPE_AP) {
220 edge_connection_t *conn = TO_EDGE_CONN(conns[i]);
221 conn->n_written = conn->n_read = 0;
227 /** Adjust the log severities that result in control_event_logmsg being called
228 * to match the severity of log messages that any controllers are interested
229 * in. */
230 void
231 control_adjust_event_log_severity(void)
233 int i;
234 int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
236 for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
237 if (EVENT_IS_INTERESTING(i)) {
238 min_log_event = i;
239 break;
242 for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
243 if (EVENT_IS_INTERESTING(i)) {
244 max_log_event = i;
245 break;
248 if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE) ||
249 EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
250 if (min_log_event > EVENT_NOTICE_MSG)
251 min_log_event = EVENT_NOTICE_MSG;
252 if (max_log_event < EVENT_ERR_MSG)
253 max_log_event = EVENT_ERR_MSG;
255 change_callback_log_severity(event_to_log_severity(min_log_event),
256 event_to_log_severity(max_log_event),
257 control_event_logmsg);
260 /** Append a NUL-terminated string <b>s</b> to the end of
261 * <b>conn</b>-\>outbuf
263 static INLINE void
264 connection_write_str_to_buf(const char *s, control_connection_t *conn)
266 size_t len = strlen(s);
267 connection_write_to_buf(s, len, TO_CONN(conn));
270 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
271 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
272 * the contents of <b>data</b> into *<b>out</b>, adding a period
273 * before any period that that appears at the start of a line, and
274 * adding a period-CRLF line at the end. If <b>translate_newlines</b>
275 * is true, replace all LF characters sequences with CRLF. Return the
276 * number of bytes in *<b>out</b>.
278 /* static */ size_t
279 write_escaped_data(const char *data, size_t len, int translate_newlines,
280 char **out)
282 size_t sz_out = len+8;
283 char *outp;
284 const char *end;
285 int i;
286 int start_of_line;
287 for (i=0; i<(int)len; ++i) {
288 if (data[i]== '\n')
289 sz_out += 2; /* Maybe add a CR; maybe add a dot. */
291 *out = outp = tor_malloc(sz_out+1);
292 end = data+len;
293 start_of_line = 1;
294 while (data < end) {
295 if (*data == '\n') {
296 if (translate_newlines)
297 *outp++ = '\r';
298 start_of_line = 1;
299 } else if (*data == '.') {
300 if (start_of_line) {
301 start_of_line = 0;
302 *outp++ = '.';
304 } else {
305 start_of_line = 0;
307 *outp++ = *data++;
309 if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
310 *outp++ = '\r';
311 *outp++ = '\n';
313 *outp++ = '.';
314 *outp++ = '\r';
315 *outp++ = '\n';
316 *outp = '\0'; /* NUL-terminate just in case. */
317 tor_assert((outp - *out) <= (int)sz_out);
318 return outp - *out;
321 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
322 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
323 * the contents of <b>data</b> into *<b>out</b>, removing any period
324 * that appears at the start of a line. If <b>translate_newlines</b>
325 * is true, replace all CRLF sequences with LF. Return the number of
326 * bytes in *<b>out</b>. */
327 /*static*/ size_t
328 read_escaped_data(const char *data, size_t len, int translate_newlines,
329 char **out)
331 char *outp;
332 const char *next;
333 const char *end;
335 *out = outp = tor_malloc(len+1);
337 end = data+len;
339 while (data < end) {
340 if (*data == '.')
341 ++data;
342 if (translate_newlines)
343 next = tor_memmem(data, end-data, "\r\n", 2);
344 else
345 next = tor_memmem(data, end-data, "\r\n.", 3);
346 if (next) {
347 memcpy(outp, data, next-data);
348 outp += (next-data);
349 data = next+2;
350 } else {
351 memcpy(outp, data, end-data);
352 outp += (end-data);
353 *outp = '\0';
354 return outp - *out;
356 if (translate_newlines) {
357 *outp++ = '\n';
358 } else {
359 *outp++ = '\r';
360 *outp++ = '\n';
364 *outp = '\0';
365 return outp - *out;
368 /** Given a pointer to a string starting at <b>start</b> containing
369 * <b>in_len_max</b> characters, decode a string beginning with a single
370 * quote, containing any number of non-quote characters or characters escaped
371 * with a backslash, and ending with a final quote. Place the resulting
372 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
373 * store its length in <b>out_len</b>. On success, return a pointer to the
374 * character immediately following the escaped string. On failure, return
375 * NULL. */
376 static const char *
377 get_escaped_string(const char *start, size_t in_len_max,
378 char **out, size_t *out_len)
380 const char *cp, *end;
381 char *outp;
382 size_t len=0;
384 if (*start != '\"')
385 return NULL;
387 cp = start+1;
388 end = start+in_len_max;
390 /* Calculate length. */
391 while (1) {
392 if (cp >= end)
393 return NULL;
394 else if (*cp == '\\') {
395 if (++cp == end)
396 return NULL; /* Can't escape EOS. */
397 ++cp;
398 ++len;
399 } else if (*cp == '\"') {
400 break;
401 } else {
402 ++cp;
403 ++len;
406 end = cp;
407 outp = *out = tor_malloc(len+1);
408 *out_len = len;
410 cp = start+1;
411 while (cp < end) {
412 if (*cp == '\\')
413 ++cp;
414 *outp++ = *cp++;
416 *outp = '\0';
417 tor_assert((outp - *out) == (int)*out_len);
419 return end+1;
422 /** Acts like sprintf, but writes its formatted string to the end of
423 * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
424 * but it will always end with a CRLF sequence.
426 * Currently the length of the message is limited to 1024 (including the
427 * ending \n\r\0. */
428 static void
429 connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
431 #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
432 va_list ap;
433 char buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE];
434 int r;
435 size_t len;
436 va_start(ap,format);
437 r = tor_vsnprintf(buf, sizeof(buf), format, ap);
438 va_end(ap);
439 if (r<0) {
440 log_warn(LD_BUG, "Unable to format string for controller.");
441 return;
443 len = strlen(buf);
444 if (memcmp("\r\n\0", buf+len-2, 3)) {
445 buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-1] = '\0';
446 buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-2] = '\n';
447 buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-3] = '\r';
449 connection_write_to_buf(buf, len, TO_CONN(conn));
452 /** Send a "DONE" message down the control connection <b>conn</b> */
453 static void
454 send_control_done(control_connection_t *conn)
456 connection_write_str_to_buf("250 OK\r\n", conn);
459 /* Send an event to all v1 controllers that are listening for code
460 * <b>event</b>. The event's body is given by <b>msg</b>.
462 * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
463 * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
464 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
465 * to contollers that <em>have</em> enabled VERBOSE_NAMES.
467 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
468 * respect to the EXTENDED_EVENTS feature. */
469 static void
470 send_control1_event_string(uint16_t event, event_format_t which,
471 const char *msg)
473 connection_t **conns;
474 int n_conns, i;
476 tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);
478 get_connection_array(&conns, &n_conns);
479 for (i = 0; i < n_conns; ++i) {
480 if (conns[i]->type == CONN_TYPE_CONTROL &&
481 !conns[i]->marked_for_close &&
482 conns[i]->state == CONTROL_CONN_STATE_OPEN_V1) {
483 control_connection_t *control_conn = TO_CONTROL_CONN(conns[i]);
484 if (control_conn->use_long_names) {
485 if (!(which & LONG_NAMES))
486 continue;
487 } else {
488 if (!(which & SHORT_NAMES))
489 continue;
491 if (control_conn->use_extended_events) {
492 if (!(which & EXTENDED_FORMAT))
493 continue;
494 } else {
495 if (!(which & NONEXTENDED_FORMAT))
496 continue;
498 if (control_conn->event_mask & (1<<event)) {
499 int is_err = 0;
500 connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
501 if (event == EVENT_ERR_MSG)
502 is_err = 1;
503 else if (event == EVENT_STATUS_GENERAL)
504 is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
505 else if (event == EVENT_STATUS_CLIENT)
506 is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
507 else if (event == EVENT_STATUS_SERVER)
508 is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
509 if (is_err)
510 connection_handle_write(TO_CONN(control_conn), 1);
516 /** Helper for send_control1_event and send_control1_event_extended:
517 * Send an event to all v1 controllers that are listening for code
518 * <b>event</b>. The event's body is created by the printf-style format in
519 * <b>format</b>, and other arguments as provided.
521 * If <b>extended</b> is true, and the format contains a single '@' character,
522 * it will be replaced with a space and all text after that character will be
523 * sent only to controllers that have enabled extended events.
525 * Currently the length of the message is limited to 1024 (including the
526 * ending \n\r\0). */
527 static void
528 send_control1_event_impl(uint16_t event, event_format_t which, int extended,
529 const char *format, va_list ap)
531 /* This is just a little longer than the longest allowed log message */
532 #define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
533 int r;
534 char buf[SEND_CONTROL1_EVENT_BUFFERSIZE];
535 size_t len;
536 char *cp;
538 r = tor_vsnprintf(buf, sizeof(buf), format, ap);
539 if (r<0) {
540 log_warn(LD_BUG, "Unable to format event for controller.");
541 return;
544 len = strlen(buf);
545 if (memcmp("\r\n\0", buf+len-2, 3)) {
546 /* if it is not properly terminated, do it now */
547 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-1] = '\0';
548 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-2] = '\n';
549 buf[SEND_CONTROL1_EVENT_BUFFERSIZE-3] = '\r';
552 if (extended && (cp = strchr(buf, '@'))) {
553 which &= ~ALL_FORMATS;
554 *cp = ' ';
555 send_control1_event_string(event, which|EXTENDED_FORMAT, buf);
556 memcpy(cp, "\r\n\0", 3);
557 send_control1_event_string(event, which|NONEXTENDED_FORMAT, buf);
558 } else {
559 send_control1_event_string(event, which|ALL_FORMATS, buf);
563 /* Send an event to all v1 controllers that are listening for code
564 * <b>event</b>. The event's body is created by the printf-style format in
565 * <b>format</b>, and other arguments as provided.
567 * Currently the length of the message is limited to 1024 (including the
568 * ending \n\r\0. */
569 static void
570 send_control1_event(uint16_t event, event_format_t which,
571 const char *format, ...)
573 va_list ap;
574 va_start(ap, format);
575 send_control1_event_impl(event, which, 0, format, ap);
576 va_end(ap);
579 /* Send an event to all v1 controllers that are listening for code
580 * <b>event</b>. The event's body is created by the printf-style format in
581 * <b>format</b>, and other arguments as provided.
583 * If the format contains a single '@' character, it will be replaced with a
584 * space and all text after that character will be sent only to controllers
585 * that have enabled extended events.
587 * Currently the length of the message is limited to 1024 (including the
588 * ending \n\r\0. */
589 static void
590 send_control1_event_extended(uint16_t event, event_format_t which,
591 const char *format, ...)
593 va_list ap;
594 va_start(ap, format);
595 send_control1_event_impl(event, which, 1, format, ap);
596 va_end(ap);
599 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
600 static origin_circuit_t *
601 get_circ(const char *id)
603 unsigned long n_id;
604 int ok;
605 n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
606 if (!ok)
607 return NULL;
608 return circuit_get_by_global_id(n_id);
611 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
612 static edge_connection_t *
613 get_stream(const char *id)
615 unsigned long n_id;
616 int ok;
617 edge_connection_t *conn;
618 n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
619 if (!ok)
620 return NULL;
621 conn = connection_get_by_global_id(n_id);
622 if (!conn || conn->_base.type != CONN_TYPE_AP)
623 return NULL;
624 return conn;
627 /** Helper for setconf and resetconf. Acts like setconf, except
628 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
629 * contents of body.
631 static int
632 control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
633 int use_defaults, int clear_first)
635 int r;
636 config_line_t *lines=NULL;
637 char *start = body;
638 char *errstring = NULL;
640 if (1) {
641 char *config;
642 smartlist_t *entries = smartlist_create();
643 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
644 * separated by space. break it into a list of configuration entries. */
645 while (*body) {
646 char *eq = body;
647 char *key;
648 char *entry;
649 while (!TOR_ISSPACE(*eq) && *eq != '=')
650 ++eq;
651 key = tor_strndup(body, eq-body);
652 body = eq+1;
653 if (*eq == '=') {
654 char *val;
655 size_t val_len;
656 size_t ent_len;
657 if (*body != '\"') {
658 char *val_start = body;
659 while (!TOR_ISSPACE(*body))
660 body++;
661 val = tor_strndup(val_start, body-val_start);
662 val_len = strlen(val);
663 } else {
664 body = (char*)get_escaped_string(body, (len - (body-start)),
665 &val, &val_len);
666 if (!body) {
667 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
668 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
669 smartlist_free(entries);
670 return 0;
673 ent_len = strlen(key)+val_len+3;
674 entry = tor_malloc(ent_len+1);
675 tor_snprintf(entry, ent_len, "%s %s", key, val);
676 tor_free(key);
677 tor_free(val);
678 } else {
679 entry = key;
681 smartlist_add(entries, entry);
682 while (TOR_ISSPACE(*body))
683 ++body;
686 smartlist_add(entries, tor_strdup(""));
687 config = smartlist_join_strings(entries, "\n", 0, NULL);
688 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
689 smartlist_free(entries);
691 if (config_get_lines(config, &lines) < 0) {
692 log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
693 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
694 conn);
695 tor_free(config);
696 return 0;
698 tor_free(config);
701 if ((r=options_trial_assign(lines, use_defaults,
702 clear_first, &errstring)) < 0) {
703 const char *msg;
704 log_warn(LD_CONTROL,
705 "Controller gave us config lines that didn't validate: %s.",
706 errstring);
707 switch (r) {
708 case -1:
709 msg = "552 Unrecognized option";
710 break;
711 case -2:
712 msg = "513 Unacceptable option value";
713 break;
714 case -3:
715 msg = "553 Transition not allowed";
716 break;
717 case -4:
718 default:
719 msg = "553 Unable to set option";
720 break;
722 connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
723 config_free_lines(lines);
724 tor_free(errstring);
725 return 0;
727 config_free_lines(lines);
728 send_control_done(conn);
729 return 0;
732 /** Called when we receive a SETCONF message: parse the body and try
733 * to update our configuration. Reply with a DONE or ERROR message.
734 * Modifies the contents of body.*/
735 static int
736 handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
738 return control_setconf_helper(conn, len, body, 0, 1);
741 /** Called when we receive a RESETCONF message: parse the body and try
742 * to update our configuration. Reply with a DONE or ERROR message.
743 * Modifies the contents of body. */
744 static int
745 handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
747 return control_setconf_helper(conn, len, body, 1, 1);
750 /** Called when we receive a GETCONF message. Parse the request, and
751 * reply with a CONFVALUE or an ERROR message */
752 static int
753 handle_control_getconf(control_connection_t *conn, uint32_t body_len,
754 const char *body)
756 smartlist_t *questions = NULL;
757 smartlist_t *answers = NULL;
758 smartlist_t *unrecognized = NULL;
759 char *msg = NULL;
760 size_t msg_len;
761 or_options_t *options = get_options();
763 questions = smartlist_create();
764 (void) body_len; /* body is nul-terminated; so we can ignore len. */
765 smartlist_split_string(questions, body, " ",
766 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
767 answers = smartlist_create();
768 unrecognized = smartlist_create();
769 SMARTLIST_FOREACH(questions, char *, q,
771 if (!option_is_recognized(q)) {
772 smartlist_add(unrecognized, q);
773 } else {
774 config_line_t *answer = option_get_assignment(options,q);
776 if (!answer) {
777 const char *name = option_get_canonical_name(q);
778 size_t alen = strlen(name)+8;
779 char *astr = tor_malloc(alen);
780 tor_snprintf(astr, alen, "250-%s\r\n", name);
781 smartlist_add(answers, astr);
784 while (answer) {
785 config_line_t *next;
786 size_t alen = strlen(answer->key)+strlen(answer->value)+8;
787 char *astr = tor_malloc(alen);
788 tor_snprintf(astr, alen, "250-%s=%s\r\n",
789 answer->key, answer->value);
790 smartlist_add(answers, astr);
792 next = answer->next;
793 tor_free(answer->key);
794 tor_free(answer->value);
795 tor_free(answer);
796 answer = next;
801 if (1) {
802 int i,len;
803 if ((len = smartlist_len(unrecognized))) {
804 for (i=0; i < len-1; ++i)
805 connection_printf_to_buf(conn,
806 "552-Unrecognized configuration key \"%s\"\r\n",
807 (char*)smartlist_get(unrecognized, i));
808 connection_printf_to_buf(conn,
809 "552 Unrecognized configuration key \"%s\"\r\n",
810 (char*)smartlist_get(unrecognized, len-1));
811 } else if ((len = smartlist_len(answers))) {
812 char *tmp = smartlist_get(answers, len-1);
813 tor_assert(strlen(tmp)>4);
814 tmp[3] = ' ';
815 msg = smartlist_join_strings(answers, "", 0, &msg_len);
816 connection_write_to_buf(msg, msg_len, TO_CONN(conn));
817 } else {
818 connection_write_str_to_buf("250 OK\r\n", conn);
822 if (answers) {
823 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
824 smartlist_free(answers);
826 if (questions) {
827 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
828 smartlist_free(questions);
830 smartlist_free(unrecognized);
831 tor_free(msg);
833 return 0;
836 /** Called when we get a SETEVENTS message: update conn->event_mask,
837 * and reply with DONE or ERROR. */
838 static int
839 handle_control_setevents(control_connection_t *conn, uint32_t len,
840 const char *body)
842 uint16_t event_code;
843 uint32_t event_mask = 0;
844 unsigned int extended = 0;
845 (void)len;
847 if (1) {
848 smartlist_t *events = smartlist_create();
849 smartlist_split_string(events, body, " ",
850 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
851 SMARTLIST_FOREACH(events, const char *, ev,
853 if (!strcasecmp(ev, "EXTENDED")) {
854 extended = 1;
855 continue;
856 } else if (!strcasecmp(ev, "CIRC"))
857 event_code = EVENT_CIRCUIT_STATUS;
858 else if (!strcasecmp(ev, "STREAM"))
859 event_code = EVENT_STREAM_STATUS;
860 else if (!strcasecmp(ev, "ORCONN"))
861 event_code = EVENT_OR_CONN_STATUS;
862 else if (!strcasecmp(ev, "BW"))
863 event_code = EVENT_BANDWIDTH_USED;
864 else if (!strcasecmp(ev, "DEBUG"))
865 event_code = EVENT_DEBUG_MSG;
866 else if (!strcasecmp(ev, "INFO"))
867 event_code = EVENT_INFO_MSG;
868 else if (!strcasecmp(ev, "NOTICE"))
869 event_code = EVENT_NOTICE_MSG;
870 else if (!strcasecmp(ev, "WARN"))
871 event_code = EVENT_WARN_MSG;
872 else if (!strcasecmp(ev, "ERR"))
873 event_code = EVENT_ERR_MSG;
874 else if (!strcasecmp(ev, "NEWDESC"))
875 event_code = EVENT_NEW_DESC;
876 else if (!strcasecmp(ev, "ADDRMAP"))
877 event_code = EVENT_ADDRMAP;
878 else if (!strcasecmp(ev, "AUTHDIR_NEWDESCS"))
879 event_code = EVENT_AUTHDIR_NEWDESCS;
880 else if (!strcasecmp(ev, "DESCCHANGED"))
881 event_code = EVENT_DESCCHANGED;
882 else if (!strcasecmp(ev, "NS"))
883 event_code = EVENT_NS;
884 else if (!strcasecmp(ev, "STATUS_GENERAL"))
885 event_code = EVENT_STATUS_GENERAL;
886 else if (!strcasecmp(ev, "STATUS_CLIENT"))
887 event_code = EVENT_STATUS_CLIENT;
888 else if (!strcasecmp(ev, "STATUS_SERVER"))
889 event_code = EVENT_STATUS_SERVER;
890 else if (!strcasecmp(ev, "GUARD"))
891 event_code = EVENT_GUARD;
892 else if (!strcasecmp(ev, "GUARDS")) {
893 /* XXX tolerate buggy spec in 0.1.2.5-alpha through 0.1.2.10-rc */
894 event_code = EVENT_GUARD;
895 } else if (!strcasecmp(ev, "STREAM_BW"))
896 event_code = EVENT_STREAM_BANDWIDTH_USED;
897 else {
898 connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
899 ev);
900 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
901 smartlist_free(events);
902 return 0;
904 event_mask |= (1 << event_code);
906 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
907 smartlist_free(events);
909 conn->event_mask = event_mask;
910 if (extended)
911 conn->use_extended_events = 1;
913 control_update_global_event_mask();
914 send_control_done(conn);
915 return 0;
918 /** Decode the hashed, base64'd password stored in <b>hashed</b>. If
919 * <b>buf</b> is provided, store the hashed password in the first
920 * S2K_SPECIFIER_LEN+DIGEST_LEN bytes of <b>buf</b>. Return 0 on
921 * success, -1 on failure.
924 decode_hashed_password(char *buf, const char *hashed)
926 char decoded[64];
927 if (!strcmpstart(hashed, "16:")) {
928 if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
929 || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
930 return -1;
932 } else {
933 if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
934 != S2K_SPECIFIER_LEN+DIGEST_LEN) {
935 return -1;
938 if (buf)
939 memcpy(buf, decoded, S2K_SPECIFIER_LEN+DIGEST_LEN);
940 return 0;
943 /** Called when we get an AUTHENTICATE message. Check whether the
944 * authentication is valid, and if so, update the connection's state to
945 * OPEN. Reply with DONE or ERROR.
947 static int
948 handle_control_authenticate(control_connection_t *conn, uint32_t len,
949 const char *body)
951 int used_quoted_string = 0;
952 or_options_t *options = get_options();
953 const char *errstr = NULL;
954 char *password;
955 size_t password_len;
956 if (1) {
957 if (TOR_ISXDIGIT(body[0])) {
958 int i = 0;
959 while (TOR_ISXDIGIT(body[i]))
960 ++i;
961 password = tor_malloc(i/2 + 1);
962 if (base16_decode(password, i/2+1, body, i)<0) {
963 connection_write_str_to_buf(
964 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
965 "password? If so, the standard requires that you put it in "
966 "double quotes.\r\n", conn);
967 tor_free(password);
968 connection_mark_for_close(TO_CONN(conn));
969 return 0;
971 password_len = i/2;
972 } else if (TOR_ISSPACE(body[0])) {
973 password = tor_strdup("");
974 password_len = 0;
975 } else {
976 if (!get_escaped_string(body, len, &password, &password_len)) {
977 connection_write_str_to_buf("551 Invalid quoted string. You need "
978 "to put the password in double quotes.\r\n", conn);
979 connection_mark_for_close(TO_CONN(conn));
980 return 0;
982 used_quoted_string = 1;
985 if (options->CookieAuthentication) {
986 if (password_len != AUTHENTICATION_COOKIE_LEN) {
987 log_warn(LD_CONTROL, "Got authentication cookie with wrong length (%d)",
988 (int)password_len);
989 errstr = "Wrong length on authentication cookie.";
990 goto err;
991 } else if (memcmp(authentication_cookie, password, password_len)) {
992 log_warn(LD_CONTROL, "Got mismatched authentication cookie");
993 errstr = "Authentication cookie did not match expected value.";
994 goto err;
995 } else {
996 goto ok;
998 } else if (options->HashedControlPassword) {
999 char expected[S2K_SPECIFIER_LEN+DIGEST_LEN];
1000 char received[DIGEST_LEN];
1001 if (decode_hashed_password(expected, options->HashedControlPassword)<0) {
1002 log_warn(LD_CONTROL,
1003 "Couldn't decode HashedControlPassword: invalid base16");
1004 errstr = "Couldn't decode HashedControlPassword value in configuration.";
1005 goto err;
1007 secret_to_key(received,DIGEST_LEN,password,password_len,expected);
1008 if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
1009 goto ok;
1011 if (used_quoted_string)
1012 errstr = "Password did not match HashedControlPassword value from "
1013 "configuration";
1014 else
1015 errstr = "Password did not match HashedControlPassword value from "
1016 "configuration. Maybe you tried a plain text password? "
1017 "If so, the standard requires that you put it in double quotes.";
1018 goto err;
1019 } else {
1020 /* if Tor doesn't demand any stronger authentication, then
1021 * the controller can get in with anything. */
1022 goto ok;
1025 err:
1026 if (1) {
1027 tor_free(password);
1028 if (!errstr)
1029 errstr = "Unknown reason.";
1030 connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n",
1031 errstr);
1033 connection_mark_for_close(TO_CONN(conn));
1034 return 0;
1036 log_info(LD_CONTROL, "Authenticated control connection (%d)", conn->_base.s);
1037 send_control_done(conn);
1038 conn->_base.state = CONTROL_CONN_STATE_OPEN_V1;
1039 tor_free(password);
1040 return 0;
1043 /** Called when we get a SAVECONF command. Try to flush the current options to
1044 * disk, and report success or failure. */
1045 static int
1046 handle_control_saveconf(control_connection_t *conn, uint32_t len,
1047 const char *body)
1049 (void) len;
1050 (void) body;
1051 if (options_save_current()<0) {
1052 connection_write_str_to_buf(
1053 "551 Unable to write configuration to disk.\r\n", conn);
1054 } else {
1055 send_control_done(conn);
1057 return 0;
1060 /** Called when we get a SIGNAL command. React to the provided signal, and
1061 * report success or failure. (If the signal results in a shutdown, success
1062 * may not be reported.) */
1063 static int
1064 handle_control_signal(control_connection_t *conn, uint32_t len,
1065 const char *body)
1067 int sig;
1068 (void)len;
1069 if (1) {
1070 int n = 0;
1071 char *s;
1072 while (body[n] && ! TOR_ISSPACE(body[n]))
1073 ++n;
1074 s = tor_strndup(body, n);
1075 if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
1076 sig = SIGHUP;
1077 else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
1078 sig = SIGINT;
1079 else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
1080 sig = SIGUSR1;
1081 else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
1082 sig = SIGUSR2;
1083 else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
1084 sig = SIGTERM;
1085 else if (!strcasecmp(s, "NEWNYM"))
1086 sig = SIGNEWNYM;
1087 else if (!strcasecmp(s, "CLEARDNSCACHE"))
1088 sig = SIGCLEARDNSCACHE;
1089 else {
1090 connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
1092 sig = -1;
1094 tor_free(s);
1095 if (sig<0)
1096 return 0;
1099 /* Send DONE first, in case the signal makes us shut down. */
1100 send_control_done(conn);
1101 control_signal_act(sig);
1102 return 0;
1105 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1106 * and report success or failrue. */
1107 static int
1108 handle_control_mapaddress(control_connection_t *conn, uint32_t len,
1109 const char *body)
1111 smartlist_t *elts;
1112 smartlist_t *lines;
1113 smartlist_t *reply;
1114 char *r;
1115 size_t sz;
1116 (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
1118 lines = smartlist_create();
1119 elts = smartlist_create();
1120 reply = smartlist_create();
1121 smartlist_split_string(lines, body, " ",
1122 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1123 SMARTLIST_FOREACH(lines, char *, line,
1125 tor_strlower(line);
1126 smartlist_split_string(elts, line, "=", 0, 2);
1127 if (smartlist_len(elts) == 2) {
1128 const char *from = smartlist_get(elts,0);
1129 const char *to = smartlist_get(elts,1);
1130 size_t anslen = strlen(line)+512;
1131 char *ans = tor_malloc(anslen);
1132 if (address_is_invalid_destination(to, 1)) {
1133 tor_snprintf(ans, anslen,
1134 "512-syntax error: invalid address '%s'", to);
1135 smartlist_add(reply, ans);
1136 log_warn(LD_CONTROL,
1137 "Skipping invalid argument '%s' in MapAddress msg", to);
1138 } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
1139 const char *address = addressmap_register_virtual_address(
1140 !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
1141 tor_strdup(to));
1142 if (!address) {
1143 tor_snprintf(ans, anslen,
1144 "451-resource exhausted: skipping '%s'", line);
1145 smartlist_add(reply, ans);
1146 log_warn(LD_CONTROL,
1147 "Unable to allocate address for '%s' in MapAddress msg",
1148 safe_str(line));
1149 } else {
1150 tor_snprintf(ans, anslen, "250-%s=%s", address, to);
1151 smartlist_add(reply, ans);
1153 } else {
1154 addressmap_register(from, tor_strdup(to), 1);
1155 tor_snprintf(ans, anslen, "250-%s", line);
1156 smartlist_add(reply, ans);
1158 } else {
1159 size_t anslen = strlen(line)+256;
1160 char *ans = tor_malloc(anslen);
1161 tor_snprintf(ans, anslen, "512-syntax error: mapping '%s' is "
1162 "not of expected form 'foo=bar'.", line);
1163 smartlist_add(reply, ans);
1164 log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
1165 "number of items.", safe_str(line));
1167 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
1168 smartlist_clear(elts);
1170 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1171 smartlist_free(lines);
1172 smartlist_free(elts);
1174 if (1) {
1175 if (smartlist_len(reply)) {
1176 ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
1177 r = smartlist_join_strings(reply, "\r\n", 1, &sz);
1178 connection_write_to_buf(r, sz, TO_CONN(conn));
1179 tor_free(r);
1180 } else {
1181 const char *response =
1182 "512 syntax error: not enough arguments to mapaddress.\r\n";
1183 connection_write_to_buf(response, strlen(response), TO_CONN(conn));
1187 SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
1188 smartlist_free(reply);
1189 return 0;
1192 /** Implementation helper for GETINFO: knows the answers for various
1193 * trivial-to-implement questions. */
1194 static int
1195 getinfo_helper_misc(control_connection_t *conn, const char *question,
1196 char **answer)
1198 (void) conn;
1199 if (!strcmp(question, "version")) {
1200 *answer = tor_strdup(VERSION);
1201 } else if (!strcmp(question, "config-file")) {
1202 *answer = tor_strdup(get_torrc_fname());
1203 } else if (!strcmp(question, "info/names")) {
1204 *answer = list_getinfo_options();
1205 } else if (!strcmp(question, "events/names")) {
1206 *answer = tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
1207 "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
1208 "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
1209 "GUARD STREAM_BW");
1210 } else if (!strcmp(question, "features/names")) {
1211 *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1212 } else if (!strcmp(question, "address")) {
1213 uint32_t addr;
1214 if (router_pick_published_address(get_options(), &addr) < 0)
1215 return -1;
1216 *answer = tor_dup_addr(addr);
1217 } else if (!strcmp(question, "dir-usage")) {
1218 *answer = directory_dump_request_log();
1219 } else if (!strcmp(question, "fingerprint")) {
1220 routerinfo_t *me = router_get_my_routerinfo();
1221 if (!me) {
1222 *answer = tor_strdup("");
1223 } else {
1224 *answer = tor_malloc(HEX_DIGEST_LEN+1);
1225 base16_encode(*answer, HEX_DIGEST_LEN+1, me->cache_info.identity_digest,
1226 DIGEST_LEN);
1229 return 0;
1232 /** Implementation helper for GETINFO: knows the answers for questions about
1233 * directory information. */
1234 static int
1235 getinfo_helper_dir(control_connection_t *control_conn,
1236 const char *question, char **answer)
1238 if (!strcmpstart(question, "desc/id/")) {
1239 routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
1240 if (ri) {
1241 const char *body = signed_descriptor_get_body(&ri->cache_info);
1242 if (body)
1243 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1245 } else if (!strcmpstart(question, "desc/name/")) {
1246 routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
1247 if (ri) {
1248 const char *body = signed_descriptor_get_body(&ri->cache_info);
1249 if (body)
1250 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1252 } else if (!strcmp(question, "desc/all-recent")) {
1253 routerlist_t *routerlist = router_get_routerlist();
1254 smartlist_t *sl = smartlist_create();
1255 if (routerlist && routerlist->routers) {
1256 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
1258 const char *body = signed_descriptor_get_body(&ri->cache_info);
1259 if (body)
1260 smartlist_add(sl,
1261 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1264 *answer = smartlist_join_strings(sl, "", 0, NULL);
1265 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1266 smartlist_free(sl);
1267 } else if (!strcmpstart(question, "dir/server/")) {
1268 size_t answer_len = 0, url_len = strlen(question)+2;
1269 char *url = tor_malloc(url_len);
1270 smartlist_t *descs = smartlist_create();
1271 const char *msg;
1272 int res;
1273 char *cp;
1274 tor_snprintf(url, url_len, "/tor/%s", question+4);
1275 res = dirserv_get_routerdescs(descs, url, &msg);
1276 if (res) {
1277 log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
1278 return -1;
1280 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1281 answer_len += sd->signed_descriptor_len);
1282 cp = *answer = tor_malloc(answer_len+1);
1283 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1285 memcpy(cp, signed_descriptor_get_body(sd),
1286 sd->signed_descriptor_len);
1287 cp += sd->signed_descriptor_len;
1289 *cp = '\0';
1290 tor_free(url);
1291 smartlist_free(descs);
1292 } else if (!strcmpstart(question, "dir/status/")) {
1293 if (get_options()->DirPort) {
1294 size_t len=0;
1295 char *cp;
1296 smartlist_t *status_list = smartlist_create();
1297 dirserv_get_networkstatus_v2(status_list,
1298 question+strlen("dir/status/"));
1299 SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
1300 cp = *answer = tor_malloc(len+1);
1301 SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
1302 memcpy(cp, d->dir, d->dir_len);
1303 cp += d->dir_len;
1305 *cp = '\0';
1306 smartlist_free(status_list);
1307 } else {
1308 smartlist_t *fp_list = smartlist_create();
1309 smartlist_t *status_list = smartlist_create();
1310 size_t fn_len = strlen(get_options()->DataDirectory)+HEX_DIGEST_LEN+32;
1311 char *fn = tor_malloc(fn_len+1);
1312 char hex_id[HEX_DIGEST_LEN+1];
1313 dirserv_get_networkstatus_v2_fingerprints(
1314 fp_list, question+strlen("dir/status/"));
1315 SMARTLIST_FOREACH(fp_list, const char *, fp, {
1316 char *s;
1317 base16_encode(hex_id, sizeof(hex_id), fp, DIGEST_LEN);
1318 tor_snprintf(fn, fn_len, "%s/cached-status/%s",
1319 get_options()->DataDirectory, hex_id);
1320 s = read_file_to_str(fn, 0, NULL);
1321 if (s)
1322 smartlist_add(status_list, s);
1324 SMARTLIST_FOREACH(fp_list, char *, fp, tor_free(fp));
1325 smartlist_free(fp_list);
1326 *answer = smartlist_join_strings(status_list, "", 0, NULL);
1327 SMARTLIST_FOREACH(status_list, char *, s, tor_free(s));
1328 smartlist_free(status_list);
1330 } else if (!strcmp(question, "network-status")) {
1331 routerlist_t *routerlist = router_get_routerlist();
1332 int verbose = control_conn->use_long_names;
1333 if (!routerlist || !routerlist->routers ||
1334 list_server_status(routerlist->routers, answer, verbose ? 2 : 1) < 0) {
1335 return -1;
1338 return 0;
1341 /** Implementation helper for GETINFO: knows how to generate summaries of the
1342 * current states of things we send events about. */
1343 static int
1344 getinfo_helper_events(control_connection_t *control_conn,
1345 const char *question, char **answer)
1347 if (!strcmp(question, "circuit-status")) {
1348 circuit_t *circ;
1349 smartlist_t *status = smartlist_create();
1350 for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
1351 char *s, *path;
1352 size_t slen;
1353 const char *state;
1354 if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
1355 continue;
1356 if (control_conn->use_long_names)
1357 path = circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ));
1358 else
1359 path = circuit_list_path(TO_ORIGIN_CIRCUIT(circ),0);
1360 if (circ->state == CIRCUIT_STATE_OPEN)
1361 state = "BUILT";
1362 else if (strlen(path))
1363 state = "EXTENDED";
1364 else
1365 state = "LAUNCHED";
1367 slen = strlen(path)+strlen(state)+20;
1368 s = tor_malloc(slen+1);
1369 tor_snprintf(s, slen, "%lu %s %s",
1370 (unsigned long)TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1371 state, path);
1372 smartlist_add(status, s);
1373 tor_free(path);
1375 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1376 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1377 smartlist_free(status);
1378 } else if (!strcmp(question, "stream-status")) {
1379 connection_t **conns;
1380 int n_conns, i;
1381 char buf[256];
1382 smartlist_t *status = smartlist_create();
1383 get_connection_array(&conns, &n_conns);
1384 for (i=0; i < n_conns; ++i) {
1385 const char *state;
1386 edge_connection_t *conn;
1387 char *s;
1388 size_t slen;
1389 circuit_t *circ;
1390 origin_circuit_t *origin_circ = NULL;
1391 if (conns[i]->type != CONN_TYPE_AP ||
1392 conns[i]->marked_for_close ||
1393 conns[i]->state == AP_CONN_STATE_SOCKS_WAIT ||
1394 conns[i]->state == AP_CONN_STATE_NATD_WAIT)
1395 continue;
1396 conn = TO_EDGE_CONN(conns[i]);
1397 switch (conn->_base.state)
1399 case AP_CONN_STATE_CONTROLLER_WAIT:
1400 case AP_CONN_STATE_CIRCUIT_WAIT:
1401 if (conn->socks_request &&
1402 SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
1403 state = "NEWRESOLVE";
1404 else
1405 state = "NEW";
1406 break;
1407 case AP_CONN_STATE_RENDDESC_WAIT:
1408 case AP_CONN_STATE_CONNECT_WAIT:
1409 state = "SENTCONNECT"; break;
1410 case AP_CONN_STATE_RESOLVE_WAIT:
1411 state = "SENTRESOLVE"; break;
1412 case AP_CONN_STATE_OPEN:
1413 state = "SUCCEEDED"; break;
1414 default:
1415 log_warn(LD_BUG, "Asked for stream in unknown state %d",
1416 conn->_base.state);
1417 continue;
1419 circ = circuit_get_by_edge_conn(conn);
1420 if (circ && CIRCUIT_IS_ORIGIN(circ))
1421 origin_circ = TO_ORIGIN_CIRCUIT(circ);
1422 write_stream_target_to_buf(conn, buf, sizeof(buf));
1423 slen = strlen(buf)+strlen(state)+32;
1424 s = tor_malloc(slen+1);
1425 tor_snprintf(s, slen, "%lu %s %lu %s",
1426 (unsigned long) conn->global_identifier,state,
1427 origin_circ?
1428 (unsigned long)origin_circ->global_identifier : 0ul,
1429 buf);
1430 smartlist_add(status, s);
1432 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1433 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1434 smartlist_free(status);
1435 } else if (!strcmp(question, "orconn-status")) {
1436 connection_t **conns;
1437 int n_conns, i;
1438 smartlist_t *status = smartlist_create();
1439 get_connection_array(&conns, &n_conns);
1440 for (i=0; i < n_conns; ++i) {
1441 const char *state;
1442 char *s;
1443 char name[128];
1444 size_t slen;
1445 or_connection_t *conn;
1446 if (conns[i]->type != CONN_TYPE_OR || conns[i]->marked_for_close)
1447 continue;
1448 conn = TO_OR_CONN(conns[i]);
1449 if (conn->_base.state == OR_CONN_STATE_OPEN)
1450 state = "CONNECTED";
1451 else if (conn->nickname)
1452 state = "LAUNCHED";
1453 else
1454 state = "NEW";
1455 orconn_target_get_name(control_conn->use_long_names, name, sizeof(name),
1456 conn);
1457 slen = strlen(name)+strlen(state)+2;
1458 s = tor_malloc(slen+1);
1459 tor_snprintf(s, slen, "%s %s", name, state);
1460 smartlist_add(status, s);
1462 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1463 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1464 smartlist_free(status);
1465 } else if (!strcmpstart(question, "addr-mappings/")) {
1466 time_t min_e, max_e;
1467 smartlist_t *mappings;
1468 if (!strcmp(question, "addr-mappings/all")) {
1469 min_e = 0; max_e = TIME_MAX;
1470 } else if (!strcmp(question, "addr-mappings/cache")) {
1471 min_e = 2; max_e = TIME_MAX;
1472 } else if (!strcmp(question, "addr-mappings/config")) {
1473 min_e = 0; max_e = 0;
1474 } else if (!strcmp(question, "addr-mappings/control")) {
1475 min_e = 1; max_e = 1;
1476 } else {
1477 return 0;
1479 mappings = smartlist_create();
1480 addressmap_get_mappings(mappings, min_e, max_e);
1481 *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
1482 SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
1483 smartlist_free(mappings);
1485 return 0;
1488 /** Callback function for GETINFO: on a given control connection, try to
1489 * answer the question <b>q</b> and store the newly-allocated answer in
1490 * *<b>a</b>. If there's no answer, or an error occurs, just don't set
1491 * <b>a</b>. Return 0.
1493 typedef int (*getinfo_helper_t)(control_connection_t *,
1494 const char *q, char **a);
1496 /** A single item for the GETINFO question-to-answer-function table. */
1497 typedef struct getinfo_item_t {
1498 const char *varname; /**< The value (or prefix) of the question. */
1499 getinfo_helper_t fn; /**< The function that knows the answer: NULL if
1500 * this entry is documentation-only. */
1501 const char *desc; /**< Description of the variable. */
1502 int is_prefix; /** Must varname match exactly, or must it be a prefix? */
1503 } getinfo_item_t;
1505 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
1506 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
1507 #define DOC(name, desc) { name, NULL, desc, 0 }
1509 /** Table mapping questions accepted by GETINFO to the functions that know how
1510 * to answer them. */
1511 static const getinfo_item_t getinfo_items[] = {
1512 ITEM("version", misc, "The current version of Tor."),
1513 ITEM("config-file", misc, "Current location of the \"torrc\" file."),
1514 ITEM("accounting/bytes", accounting,
1515 "Number of bytes read/written so far in the accounting interval."),
1516 ITEM("accounting/bytes-left", accounting,
1517 "Number of bytes left to write/read so far in the accounting interval."),
1518 ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
1519 ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
1520 ITEM("accounting/interval-start", accounting,
1521 "Time when the accounting period starts."),
1522 ITEM("accounting/interval-end", accounting,
1523 "Time when the accounting period ends."),
1524 ITEM("accounting/interval-wake", accounting,
1525 "Time to wake up in this accounting period."),
1526 ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
1527 ITEM("entry-guards", entry_guards,
1528 "Which nodes are we using as entry guards?"),
1529 ITEM("fingerprint", misc, NULL),
1530 PREFIX("config/", config, "Current configuration values."),
1531 DOC("config/names",
1532 "List of configuration options, types, and documentation."),
1533 ITEM("info/names", misc,
1534 "List of GETINFO options, types, and documentation."),
1535 ITEM("events/names", misc,
1536 "Events that the controller can ask for with SETEVENTS."),
1537 ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
1538 PREFIX("desc/id/", dir, "Router descriptors by ID."),
1539 PREFIX("desc/name/", dir, "Router descriptors by nickname."),
1540 ITEM("desc/all-recent", dir,
1541 "All non-expired, non-superseded router descriptors."),
1542 ITEM("ns/all", networkstatus,
1543 "Brief summary of router status (v2 directory format)"),
1544 PREFIX("ns/id/", networkstatus,
1545 "Brief summary of router status by ID (v2 directory format)."),
1546 PREFIX("ns/name/", networkstatus,
1547 "Brief summary of router status by nickname (v2 directory format)."),
1549 PREFIX("unregisterd-servers-", dirserv_unregistered, NULL),
1550 ITEM("network-status", dir,
1551 "Brief summary of router status (v1 directory format)"),
1552 ITEM("circuit-status", events, "List of current circuits originating here."),
1553 ITEM("stream-status", events,"List of current streams."),
1554 ITEM("orconn-status", events, "A list of current OR connections."),
1555 PREFIX("addr-mappings/", events, NULL),
1556 DOC("addr-mappings/all", "Current address mappings."),
1557 DOC("addr-mappings/cache", "Current cached DNS replies."),
1558 DOC("addr-mappings/config", "Current address mappings from configuration."),
1559 DOC("addr-mappings/control", "Current address mappings from controller."),
1561 ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
1562 ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
1563 PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
1564 PREFIX("dir/status/", dir,"Networkstatus docs as retrieved from a DirPort."),
1565 PREFIX("exit-policy/default", policies,
1566 "The default value appended to the configured exit policy."),
1568 { NULL, NULL, NULL, 0 }
1571 /** Allocate and return a list of recognized GETINFO options. */
1572 static char *
1573 list_getinfo_options(void)
1575 int i;
1576 char buf[300];
1577 smartlist_t *lines = smartlist_create();
1578 char *ans;
1579 for (i = 0; getinfo_items[i].varname; ++i) {
1580 if (!getinfo_items[i].desc)
1581 continue;
1583 tor_snprintf(buf, sizeof(buf), "%s%s -- %s\n",
1584 getinfo_items[i].varname,
1585 getinfo_items[i].is_prefix ? "*" : "",
1586 getinfo_items[i].desc);
1587 smartlist_add(lines, tor_strdup(buf));
1589 smartlist_sort_strings(lines);
1591 ans = smartlist_join_strings(lines, "", 0, NULL);
1592 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1593 smartlist_free(lines);
1595 return ans;
1598 /** Lookup the 'getinfo' entry <b>question</b>, and return
1599 * the answer in <b>*answer</b> (or NULL if key not recognized).
1600 * Return 0 if success or unrecognized, or -1 if recognized but
1601 * internal error. */
1602 static int
1603 handle_getinfo_helper(control_connection_t *control_conn,
1604 const char *question, char **answer)
1606 int i;
1607 *answer = NULL; /* unrecognized key by default */
1609 for (i = 0; getinfo_items[i].varname; ++i) {
1610 int match;
1611 if (getinfo_items[i].is_prefix)
1612 match = !strcmpstart(question, getinfo_items[i].varname);
1613 else
1614 match = !strcmp(question, getinfo_items[i].varname);
1615 if (match) {
1616 tor_assert(getinfo_items[i].fn);
1617 return getinfo_items[i].fn(control_conn, question, answer);
1621 return 0; /* unrecognized */
1624 /** Called when we receive a GETINFO command. Try to fetch all requested
1625 * information, and reply with information or error message. */
1626 static int
1627 handle_control_getinfo(control_connection_t *conn, uint32_t len,
1628 const char *body)
1630 smartlist_t *questions = NULL;
1631 smartlist_t *answers = NULL;
1632 smartlist_t *unrecognized = NULL;
1633 char *msg = NULL, *ans = NULL;
1634 (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
1636 questions = smartlist_create();
1637 smartlist_split_string(questions, body, " ",
1638 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1639 answers = smartlist_create();
1640 unrecognized = smartlist_create();
1641 SMARTLIST_FOREACH(questions, const char *, q,
1643 if (handle_getinfo_helper(conn, q, &ans) < 0) {
1644 connection_write_str_to_buf("551 Internal error\r\n", conn);
1645 goto done;
1647 if (!ans) {
1648 smartlist_add(unrecognized, (char*)q);
1649 } else {
1650 smartlist_add(answers, tor_strdup(q));
1651 smartlist_add(answers, ans);
1654 if (smartlist_len(unrecognized)) {
1655 int i;
1656 for (i=0; i < smartlist_len(unrecognized)-1; ++i)
1657 connection_printf_to_buf(conn,
1658 "552-Unrecognized key \"%s\"\r\n",
1659 (char*)smartlist_get(unrecognized, i));
1660 connection_printf_to_buf(conn,
1661 "552 Unrecognized key \"%s\"\r\n",
1662 (char*)smartlist_get(unrecognized, i));
1663 goto done;
1666 if (1) {
1667 int i;
1668 for (i = 0; i < smartlist_len(answers); i += 2) {
1669 char *k = smartlist_get(answers, i);
1670 char *v = smartlist_get(answers, i+1);
1671 if (!strchr(v, '\n') && !strchr(v, '\r')) {
1672 connection_printf_to_buf(conn, "250-%s=", k);
1673 connection_write_str_to_buf(v, conn);
1674 connection_write_str_to_buf("\r\n", conn);
1675 } else {
1676 char *esc = NULL;
1677 size_t len;
1678 len = write_escaped_data(v, strlen(v), 1, &esc);
1679 connection_printf_to_buf(conn, "250+%s=\r\n", k);
1680 connection_write_to_buf(esc, len, TO_CONN(conn));
1681 tor_free(esc);
1684 connection_write_str_to_buf("250 OK\r\n", conn);
1687 done:
1688 if (answers) {
1689 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
1690 smartlist_free(answers);
1692 if (questions) {
1693 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
1694 smartlist_free(questions);
1696 smartlist_free(unrecognized);
1697 tor_free(msg);
1699 return 0;
1702 /** If *<b>string</b> contains a recognized purpose (for
1703 * circuits if <b>for_circuits</b> is 1, else for routers),
1704 * possibly prefaced with the string "purpose=", then assign it
1705 * and return 0. Otherwise return -1.
1707 * If it's prefaced with "purpose=", then set *<b>string</b> to
1708 * the remainder of the string. */
1709 static int
1710 get_purpose(char **string, int for_circuits, uint8_t *purpose)
1712 if (!strcmpstart(*string, "purpose="))
1713 *string += strlen("purpose=");
1715 if (!strcmp(*string, "general"))
1716 *purpose = for_circuits ? CIRCUIT_PURPOSE_C_GENERAL :
1717 ROUTER_PURPOSE_GENERAL;
1718 else if (!strcmp(*string, "controller"))
1719 *purpose = for_circuits ? CIRCUIT_PURPOSE_CONTROLLER :
1720 ROUTER_PURPOSE_CONTROLLER;
1721 else { /* not a recognized purpose */
1722 return -1;
1724 return 0;
1727 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
1728 * circuit, and report success or failure. */
1729 static int
1730 handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
1731 const char *body)
1733 smartlist_t *router_nicknames=NULL, *routers=NULL;
1734 origin_circuit_t *circ = NULL;
1735 int zero_circ;
1736 uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
1737 (void)len;
1739 router_nicknames = smartlist_create();
1741 if (1) {
1742 smartlist_t *args;
1743 args = smartlist_create();
1744 smartlist_split_string(args, body, " ",
1745 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1746 if (smartlist_len(args)<2) {
1747 connection_printf_to_buf(conn,
1748 "512 Missing argument to EXTENDCIRCUIT\r\n");
1749 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
1750 smartlist_free(args);
1751 goto done;
1754 zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
1755 if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
1756 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
1757 (char*)smartlist_get(args, 0));
1759 smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
1761 if (zero_circ && smartlist_len(args)>2) {
1762 char *purp = smartlist_get(args,2);
1763 if (get_purpose(&purp, 1, &intended_purpose) < 0) {
1764 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
1765 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
1766 smartlist_free(args);
1767 goto done;
1770 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
1771 smartlist_free(args);
1772 if (!zero_circ && !circ) {
1773 goto done;
1777 routers = smartlist_create();
1778 SMARTLIST_FOREACH(router_nicknames, const char *, n,
1780 routerinfo_t *r = router_get_by_nickname(n, 1);
1781 if (!r) {
1782 connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
1783 goto done;
1785 smartlist_add(routers, r);
1787 if (!smartlist_len(routers)) {
1788 connection_write_str_to_buf("512 No router names provided\r\n", conn);
1789 goto done;
1792 if (zero_circ) {
1793 /* start a new circuit */
1794 circ = origin_circuit_init(intended_purpose, 0, 0, 0, 0);
1797 /* now circ refers to something that is ready to be extended */
1798 SMARTLIST_FOREACH(routers, routerinfo_t *, r,
1800 extend_info_t *info = extend_info_from_router(r);
1801 circuit_append_new_exit(circ, info);
1802 extend_info_free(info);
1805 /* now that we've populated the cpath, start extending */
1806 if (zero_circ) {
1807 int err_reason = 0;
1808 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
1809 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
1810 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
1811 goto done;
1813 } else {
1814 if (circ->_base.state == CIRCUIT_STATE_OPEN) {
1815 int err_reason = 0;
1816 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
1817 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
1818 log_info(LD_CONTROL,
1819 "send_next_onion_skin failed; circuit marked for closing.");
1820 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
1821 connection_write_str_to_buf("551 Couldn't send onion skinr\n", conn);
1822 goto done;
1827 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
1828 (unsigned long)circ->global_identifier);
1829 if (zero_circ) /* send a 'launched' event, for completeness */
1830 control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
1831 done:
1832 SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
1833 smartlist_free(router_nicknames);
1834 if (routers)
1835 smartlist_free(routers);
1836 return 0;
1839 /** Called when we get a SETCIRCUITPURPOSE (if <b>for_circuits</b>
1840 * is 1) or SETROUTERPURPOSE message. If we can find
1841 * the circuit/router and it's a valid purpose, change it. */
1842 static int
1843 handle_control_setpurpose(control_connection_t *conn, int for_circuits,
1844 uint32_t len, const char *body)
1846 origin_circuit_t *circ = NULL;
1847 routerinfo_t *ri = NULL;
1848 uint8_t new_purpose;
1849 smartlist_t *args = smartlist_create();
1850 (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
1851 smartlist_split_string(args, body, " ",
1852 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1853 if (smartlist_len(args)<2) {
1854 connection_printf_to_buf(conn,
1855 "512 Missing argument to SET%sPURPOSE\r\n",
1856 for_circuits ? "CIRCUIT" : "ROUTER");
1857 goto done;
1860 if (for_circuits) {
1861 if (!(circ = get_circ(smartlist_get(args,0)))) {
1862 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
1863 (char*)smartlist_get(args, 0));
1864 goto done;
1866 } else {
1867 if (!(ri = router_get_by_nickname(smartlist_get(args,0), 0))) {
1868 connection_printf_to_buf(conn, "552 Unknown router \"%s\"\r\n",
1869 (char*)smartlist_get(args, 0));
1870 goto done;
1875 char *purp = smartlist_get(args,1);
1876 if (get_purpose(&purp, for_circuits, &new_purpose) < 0) {
1877 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
1878 goto done;
1882 if (for_circuits)
1883 circ->_base.purpose = new_purpose;
1884 else
1885 ri->purpose = new_purpose;
1886 connection_write_str_to_buf("250 OK\r\n", conn);
1888 done:
1889 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
1890 smartlist_free(args);
1891 return 0;
1894 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
1895 * stream, and report success or failure. */
1896 static int
1897 handle_control_attachstream(control_connection_t *conn, uint32_t len,
1898 const char *body)
1900 edge_connection_t *ap_conn = NULL;
1901 origin_circuit_t *circ = NULL;
1902 int zero_circ;
1903 (void)len;
1905 if (1) {
1906 smartlist_t *args;
1907 args = smartlist_create();
1908 smartlist_split_string(args, body, " ",
1909 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1910 if (smartlist_len(args)<2) {
1911 connection_printf_to_buf(conn,
1912 "512 Missing argument to ATTACHSTREAM\r\n");
1913 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
1914 smartlist_free(args);
1915 return 0;
1918 zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
1920 if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
1921 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
1922 (char*)smartlist_get(args, 0));
1923 } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
1924 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
1925 (char*)smartlist_get(args, 1));
1927 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
1928 smartlist_free(args);
1929 if (!ap_conn || (!zero_circ && !circ))
1930 return 0;
1933 if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT &&
1934 ap_conn->_base.state != AP_CONN_STATE_CONNECT_WAIT &&
1935 ap_conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
1936 connection_write_str_to_buf(
1937 "555 Connection is not managed by controller.\r\n",
1938 conn);
1939 return 0;
1942 /* Do we need to detach it first? */
1943 if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT) {
1944 circuit_t *tmpcirc = circuit_get_by_edge_conn(ap_conn);
1945 connection_edge_end(ap_conn, END_STREAM_REASON_TIMEOUT,
1946 ap_conn->cpath_layer);
1947 /* Un-mark it as ending, since we're going to reuse it. */
1948 ap_conn->_base.edge_has_sent_end = 0;
1949 ap_conn->end_reason = 0;
1950 if (tmpcirc)
1951 circuit_detach_stream(tmpcirc,ap_conn);
1952 ap_conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
1955 if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
1956 connection_write_str_to_buf(
1957 "551 Can't attach stream to non-open, origin circuit\r\n",
1958 conn);
1959 return 0;
1961 if (circ && circuit_get_cpath_len(circ) < 2) {
1962 connection_write_str_to_buf(
1963 "551 Can't attach stream to one-hop circuit.\r\n",
1964 conn);
1965 return 0;
1967 if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ) < 0) {
1968 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
1969 return 0;
1971 send_control_done(conn);
1972 return 0;
1975 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
1976 * descriptor, and report success or failure. */
1977 static int
1978 handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
1979 const char *body)
1981 char *desc;
1982 const char *msg=NULL;
1983 uint8_t purpose = ROUTER_PURPOSE_GENERAL;
1985 if (1) {
1986 char *cp = memchr(body, '\n', len);
1987 smartlist_t *args = smartlist_create();
1988 tor_assert(cp);
1989 *cp++ = '\0';
1990 smartlist_split_string(args, body, " ",
1991 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1992 if (smartlist_len(args)) {
1993 char *purp = smartlist_get(args,0);
1994 if (get_purpose(&purp, 0, &purpose) < 0) {
1995 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
1996 purp);
1997 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
1998 smartlist_free(args);
1999 return 0;
2002 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2003 smartlist_free(args);
2004 read_escaped_data(cp, len-(cp-body), 1, &desc);
2007 switch (router_load_single_router(desc, purpose, &msg)) {
2008 case -1:
2009 if (!msg) msg = "Could not parse descriptor";
2010 connection_printf_to_buf(conn, "554 %s\r\n", msg);
2011 break;
2012 case 0:
2013 if (!msg) msg = "Descriptor not added";
2014 connection_printf_to_buf(conn, "251 %s\r\n",msg);
2015 break;
2016 case 1:
2017 send_control_done(conn);
2018 break;
2021 tor_free(desc);
2022 return 0;
2025 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
2026 * address of the named AP stream, and report success or failure. */
2027 static int
2028 handle_control_redirectstream(control_connection_t *conn, uint32_t len,
2029 const char *body)
2031 edge_connection_t *ap_conn = NULL;
2032 char *new_addr = NULL;
2033 uint16_t new_port = 0;
2034 (void)len;
2035 if (1) {
2036 smartlist_t *args;
2037 args = smartlist_create();
2038 smartlist_split_string(args, body, " ",
2039 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2040 if (smartlist_len(args) < 2)
2041 connection_printf_to_buf(conn,
2042 "512 Missing argument to REDIRECTSTREAM\r\n");
2043 else if (!(ap_conn = get_stream(smartlist_get(args, 0)))
2044 || !ap_conn->socks_request) {
2045 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2046 (char*)smartlist_get(args, 0));
2047 } else {
2048 int ok;
2049 if (smartlist_len(args) > 2) { /* they included a port too */
2050 new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
2051 10, 1, 65535, &ok, NULL);
2053 if (!ok) {
2054 connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
2055 (char*)smartlist_get(args, 2));
2056 } else {
2057 new_addr = tor_strdup(smartlist_get(args, 1));
2061 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2062 smartlist_free(args);
2063 if (!new_addr)
2064 return 0;
2067 strlcpy(ap_conn->socks_request->address, new_addr,
2068 sizeof(ap_conn->socks_request->address));
2069 if (new_port)
2070 ap_conn->socks_request->port = new_port;
2071 tor_free(new_addr);
2072 send_control_done(conn);
2073 return 0;
2076 /** Called when we get a CLOSESTREAM command; try to close the named stream
2077 * and report success or failure. */
2078 static int
2079 handle_control_closestream(control_connection_t *conn, uint32_t len,
2080 const char *body)
2082 edge_connection_t *ap_conn=NULL;
2083 uint8_t reason=0;
2084 (void)len;
2086 if (1) {
2087 smartlist_t *args;
2088 int ok;
2089 args = smartlist_create();
2090 smartlist_split_string(args, body, " ",
2091 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2092 if (smartlist_len(args)<2)
2093 connection_printf_to_buf(conn,
2094 "512 Missing argument to CLOSESTREAM\r\n");
2095 else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
2096 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2097 (char*)smartlist_get(args, 0));
2098 else {
2099 reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
2100 &ok, NULL);
2101 if (!ok) {
2102 connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
2103 (char*)smartlist_get(args, 1));
2104 ap_conn = NULL;
2107 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2108 smartlist_free(args);
2109 if (!ap_conn)
2110 return 0;
2113 connection_mark_unattached_ap(ap_conn, reason);
2114 send_control_done(conn);
2115 return 0;
2118 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
2119 * and report success or failure. */
2120 static int
2121 handle_control_closecircuit(control_connection_t *conn, uint32_t len,
2122 const char *body)
2124 origin_circuit_t *circ = NULL;
2125 int safe = 0;
2126 (void)len;
2128 if (1) {
2129 smartlist_t *args;
2130 args = smartlist_create();
2131 smartlist_split_string(args, body, " ",
2132 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2133 if (smartlist_len(args)<1)
2134 connection_printf_to_buf(conn,
2135 "512 Missing argument to CLOSECIRCUIT\r\n");
2136 else if (!(circ=get_circ(smartlist_get(args, 0))))
2137 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2138 (char*)smartlist_get(args, 0));
2139 else {
2140 int i;
2141 for (i=1; i < smartlist_len(args); ++i) {
2142 if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
2143 safe = 1;
2144 else
2145 log_info(LD_CONTROL, "Skipping unknown option %s",
2146 (char*)smartlist_get(args,i));
2149 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2150 smartlist_free(args);
2151 if (!circ)
2152 return 0;
2155 if (!safe || !circ->p_streams) {
2156 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
2159 send_control_done(conn);
2160 return 0;
2163 /** Called when we get a USEFEATURE command: parse the feature list, and
2164 * set up the control_connection's options properly. */
2165 static int
2166 handle_control_usefeature(control_connection_t *conn,
2167 uint32_t len,
2168 const char *body)
2170 smartlist_t *args;
2171 int verbose_names = 0, extended_events = 0;
2172 int bad = 0;
2173 (void) len; /* body is nul-terminated; it's safe to ignore the length */
2174 args = smartlist_create();
2175 smartlist_split_string(args, body, " ",
2176 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2177 SMARTLIST_FOREACH(args, const char *, arg, {
2178 if (!strcasecmp(arg, "VERBOSE_NAMES"))
2179 verbose_names = 1;
2180 else if (!strcasecmp(arg, "EXTENDED_EVENTS")) /* <- documented */
2181 extended_events = 1;
2182 else if (!strcasecmp(arg, "EXTENDED_FORMAT")) {
2183 /* remove this in 0.1.2.4; EXTENDED_FORMAT only ever worked for a
2184 * little while during 0.1.2.2-alpha-dev. */
2185 log_warn(LD_GENERAL,
2186 "EXTENDED_FORMAT is deprecated; use EXTENDED_EVENTS "
2187 "instead.");
2188 extended_events = 1;
2189 } else {
2190 connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
2191 arg);
2192 bad = 1;
2193 break;
2197 if (!bad) {
2198 if (verbose_names) {
2199 conn->use_long_names = 1;
2200 control_update_global_event_mask();
2202 if (extended_events)
2203 conn->use_extended_events = 1;
2204 send_control_done(conn);
2207 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2208 smartlist_free(args);
2209 return 0;
2212 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
2214 connection_control_finished_flushing(control_connection_t *conn)
2216 tor_assert(conn);
2218 connection_stop_writing(TO_CONN(conn));
2219 return 0;
2222 /** Called when <b>conn</b> has gotten its socket closed. */
2224 connection_control_reached_eof(control_connection_t *conn)
2226 tor_assert(conn);
2228 log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
2229 connection_mark_for_close(TO_CONN(conn));
2230 return 0;
2233 /** Called when data has arrived on a v1 control connection: Try to fetch
2234 * commands from conn->inbuf, and execute them.
2237 connection_control_process_inbuf(control_connection_t *conn)
2239 size_t data_len;
2240 int cmd_len;
2241 char *args;
2243 tor_assert(conn);
2244 tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN_V1 ||
2245 conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V1);
2247 if (!conn->incoming_cmd) {
2248 conn->incoming_cmd = tor_malloc(1024);
2249 conn->incoming_cmd_len = 1024;
2250 conn->incoming_cmd_cur_len = 0;
2253 if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V1 &&
2254 peek_buf_has_control0_command(conn->_base.inbuf)) {
2255 /* Detect v0 commands and send a "no more v0" message. */
2256 size_t body_len;
2257 char buf[128];
2258 set_uint16(buf+2, htons(0x0000)); /* type == error */
2259 set_uint16(buf+4, htons(0x0001)); /* code == internal error */
2260 strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.2.0.x "
2261 "and later; use Tor 0.1.2.x or upgrade your controller",
2262 sizeof(buf)-6);
2263 body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
2264 set_uint16(buf+0, htons(body_len));
2265 connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
2266 connection_mark_for_close(TO_CONN(conn));
2267 conn->_base.hold_open_until_flushed = 1;
2268 return 0;
2271 again:
2272 while (1) {
2273 size_t last_idx;
2274 int r;
2275 /* First, fetch a line. */
2276 do {
2277 data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
2278 r = fetch_from_buf_line(conn->_base.inbuf,
2279 conn->incoming_cmd+conn->incoming_cmd_cur_len,
2280 &data_len);
2281 if (r == 0)
2282 /* Line not all here yet. Wait. */
2283 return 0;
2284 else if (r == -1) {
2285 while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
2286 conn->incoming_cmd_len *= 2;
2287 conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
2288 conn->incoming_cmd_len);
2290 } while (r != 1);
2292 tor_assert(data_len);
2294 last_idx = conn->incoming_cmd_cur_len;
2295 conn->incoming_cmd_cur_len += data_len;
2297 /* We have appended a line to incoming_cmd. Is the command done? */
2298 if (last_idx == 0 && *conn->incoming_cmd != '+')
2299 /* One line command, didn't start with '+'. */
2300 break;
2301 if (last_idx+3 == conn->incoming_cmd_cur_len &&
2302 !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
2303 /* Just appended ".\r\n"; we're done. Remove it. */
2304 conn->incoming_cmd_cur_len -= 3;
2305 break;
2307 /* Otherwise, read another line. */
2309 data_len = conn->incoming_cmd_cur_len;
2310 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
2311 * recognize it.
2313 cmd_len = 0;
2314 while ((size_t)cmd_len < data_len
2315 && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
2316 ++cmd_len;
2318 data_len -= cmd_len;
2319 conn->incoming_cmd[cmd_len]='\0';
2320 args = conn->incoming_cmd+cmd_len+1;
2321 while (*args == ' ' || *args == '\t') {
2322 ++args;
2323 --data_len;
2326 if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
2327 connection_write_str_to_buf("250 closing connection\r\n", conn);
2328 connection_mark_for_close(TO_CONN(conn));
2329 return 0;
2332 if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V1 &&
2333 strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
2334 connection_write_str_to_buf("514 Authentication required.\r\n", conn);
2335 connection_mark_for_close(TO_CONN(conn));
2336 return 0;
2339 if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
2340 if (handle_control_setconf(conn, data_len, args))
2341 return -1;
2342 } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
2343 if (handle_control_resetconf(conn, data_len, args))
2344 return -1;
2345 } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
2346 if (handle_control_getconf(conn, data_len, args))
2347 return -1;
2348 } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
2349 if (handle_control_setevents(conn, data_len, args))
2350 return -1;
2351 } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
2352 if (handle_control_authenticate(conn, data_len, args))
2353 return -1;
2354 } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
2355 if (handle_control_saveconf(conn, data_len, args))
2356 return -1;
2357 } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
2358 if (handle_control_signal(conn, data_len, args))
2359 return -1;
2360 } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
2361 if (handle_control_mapaddress(conn, data_len, args))
2362 return -1;
2363 } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
2364 if (handle_control_getinfo(conn, data_len, args))
2365 return -1;
2366 } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
2367 if (handle_control_extendcircuit(conn, data_len, args))
2368 return -1;
2369 } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
2370 if (handle_control_setpurpose(conn, 1, data_len, args))
2371 return -1;
2372 } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
2373 if (handle_control_setpurpose(conn, 0, data_len, args))
2374 return -1;
2375 } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
2376 if (handle_control_attachstream(conn, data_len, args))
2377 return -1;
2378 } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
2379 if (handle_control_postdescriptor(conn, data_len, args))
2380 return -1;
2381 } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
2382 if (handle_control_redirectstream(conn, data_len, args))
2383 return -1;
2384 } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
2385 if (handle_control_closestream(conn, data_len, args))
2386 return -1;
2387 } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
2388 if (handle_control_closecircuit(conn, data_len, args))
2389 return -1;
2390 } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
2391 if (handle_control_usefeature(conn, data_len, args))
2392 return -1;
2393 } else {
2394 connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
2395 conn->incoming_cmd);
2398 conn->incoming_cmd_cur_len = 0;
2399 goto again;
2402 #if 0
2403 /** Called when data has arrived on a v0 control connection: Try to fetch
2404 * commands from conn->inbuf, and execute them.
2406 static int
2407 connection_control_process_inbuf_v0(control_connection_t *conn)
2409 uint32_t body_len;
2410 uint16_t command_type;
2411 char *body=NULL;
2412 static int have_warned_about_v0_protocol = 0;
2414 again:
2415 /* Try to suck a control message from the buffer. */
2416 switch (fetch_from_buf_control0(conn->_base.inbuf, &body_len, &command_type,
2417 &body,
2418 conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V0))
2420 case -2:
2421 tor_free(body);
2422 log_info(LD_CONTROL,
2423 "Detected v1 control protocol on connection (fd %d)",
2424 conn->_base.s);
2425 conn->_base.state = CONTROL_CONN_STATE_NEEDAUTH_V1;
2426 return connection_control_process_inbuf_v1(conn);
2427 case -1:
2428 tor_free(body);
2429 log_warn(LD_CONTROL, "Error in control command. Failing.");
2430 return -1;
2431 case 0:
2432 /* Control command not all here yet. Wait. */
2433 return 0;
2434 case 1:
2435 /* We got a command. Process it. */
2436 break;
2437 default:
2438 tor_assert(0);
2441 if (!have_warned_about_v0_protocol) {
2442 log_warn(LD_CONTROL, "An application has connected to us using the "
2443 "version 0 control prototol, which has been deprecated since "
2444 "Tor 0.1.1.1-alpha. This protocol will not be supported by "
2445 "future versions of Tor; please use the v1 control protocol "
2446 "instead.");
2447 have_warned_about_v0_protocol = 1;
2450 /* We got a command. If we need authentication, only authentication
2451 * commands will be considered. */
2452 if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V0 &&
2453 command_type != CONTROL0_CMD_AUTHENTICATE) {
2454 log_info(LD_CONTROL, "Rejecting '%s' command; authentication needed.",
2455 control_cmd_to_string(command_type));
2456 send_control0_error(conn, ERR_UNAUTHORIZED, "Authentication required");
2457 tor_free(body);
2458 goto again;
2461 if (command_type == CONTROL0_CMD_FRAGMENTHEADER ||
2462 command_type == CONTROL0_CMD_FRAGMENT) {
2463 if (handle_control_fragments(conn, command_type, body_len, body))
2464 return -1;
2465 tor_free(body);
2466 if (conn->incoming_cmd_cur_len != conn->incoming_cmd_len)
2467 goto again;
2469 command_type = conn->incoming_cmd_type;
2470 body_len = conn->incoming_cmd_len;
2471 body = conn->incoming_cmd;
2472 conn->incoming_cmd = NULL;
2473 } else if (conn->incoming_cmd) {
2474 log_warn(LD_CONTROL, "Dropping incomplete fragmented command");
2475 tor_free(conn->incoming_cmd);
2478 /* Okay, we're willing to process the command. */
2479 switch (command_type)
2481 case CONTROL0_CMD_SETCONF:
2482 if (handle_control_setconf(conn, body_len, body))
2483 return -1;
2484 break;
2485 case CONTROL0_CMD_GETCONF:
2486 if (handle_control_getconf(conn, body_len, body))
2487 return -1;
2488 break;
2489 case CONTROL0_CMD_SETEVENTS:
2490 if (handle_control_setevents(conn, body_len, body))
2491 return -1;
2492 break;
2493 case CONTROL0_CMD_AUTHENTICATE:
2494 if (handle_control_authenticate(conn, body_len, body))
2495 return -1;
2496 break;
2497 case CONTROL0_CMD_SAVECONF:
2498 if (handle_control_saveconf(conn, body_len, body))
2499 return -1;
2500 break;
2501 case CONTROL0_CMD_SIGNAL:
2502 if (handle_control_signal(conn, body_len, body))
2503 return -1;
2504 break;
2505 case CONTROL0_CMD_MAPADDRESS:
2506 if (handle_control_mapaddress(conn, body_len, body))
2507 return -1;
2508 break;
2509 case CONTROL0_CMD_GETINFO:
2510 if (handle_control_getinfo(conn, body_len, body))
2511 return -1;
2512 break;
2513 case CONTROL0_CMD_EXTENDCIRCUIT:
2514 if (handle_control_extendcircuit(conn, body_len, body))
2515 return -1;
2516 break;
2517 case CONTROL0_CMD_ATTACHSTREAM:
2518 if (handle_control_attachstream(conn, body_len, body))
2519 return -1;
2520 break;
2521 case CONTROL0_CMD_POSTDESCRIPTOR:
2522 if (handle_control_postdescriptor(conn, body_len, body))
2523 return -1;
2524 break;
2525 case CONTROL0_CMD_REDIRECTSTREAM:
2526 if (handle_control_redirectstream(conn, body_len, body))
2527 return -1;
2528 break;
2529 case CONTROL0_CMD_CLOSESTREAM:
2530 if (handle_control_closestream(conn, body_len, body))
2531 return -1;
2532 break;
2533 case CONTROL0_CMD_CLOSECIRCUIT:
2534 if (handle_control_closecircuit(conn, body_len, body))
2535 return -1;
2536 break;
2537 case CONTROL0_CMD_ERROR:
2538 case CONTROL0_CMD_DONE:
2539 case CONTROL0_CMD_CONFVALUE:
2540 case CONTROL0_CMD_EVENT:
2541 case CONTROL0_CMD_INFOVALUE:
2542 log_warn(LD_CONTROL, "Received client-only '%s' command; ignoring.",
2543 control_cmd_to_string(command_type));
2544 send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
2545 "Command type only valid from server to tor client");
2546 break;
2547 case CONTROL0_CMD_FRAGMENTHEADER:
2548 case CONTROL0_CMD_FRAGMENT:
2549 log_warn(LD_CONTROL,
2550 "Recieved command fragment out of order; ignoring.");
2551 send_control0_error(conn, ERR_SYNTAX, "Bad fragmentation on command.");
2552 default:
2553 log_warn(LD_CONTROL, "Received unrecognized command type %d; ignoring.",
2554 (int)command_type);
2555 send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
2556 "Unrecognized command type");
2557 break;
2559 tor_free(body);
2560 goto again; /* There might be more data. */
2562 #endif
2564 /** Convert a numeric reason for destroying a circuit into a string for a
2565 * CIRCUIT event. */
2566 static const char *
2567 circuit_end_reason_to_string(int reason)
2569 if (reason >= 0 && reason & END_CIRC_REASON_FLAG_REMOTE)
2570 reason &= ~END_CIRC_REASON_FLAG_REMOTE;
2571 switch (reason) {
2572 case END_CIRC_AT_ORIGIN:
2573 /* This shouldn't get passed here; it's a catch-all reason. */
2574 return "ORIGIN";
2575 case END_CIRC_REASON_NONE:
2576 /* This shouldn't get passed here; it's a catch-all reason. */
2577 return "NONE";
2578 case END_CIRC_REASON_TORPROTOCOL:
2579 return "TORPROTOCOL";
2580 case END_CIRC_REASON_INTERNAL:
2581 return "INTERNAL";
2582 case END_CIRC_REASON_REQUESTED:
2583 return "REQUESTED";
2584 case END_CIRC_REASON_HIBERNATING:
2585 return "HIBERNATING";
2586 case END_CIRC_REASON_RESOURCELIMIT:
2587 return "RESOURCELIMIT";
2588 case END_CIRC_REASON_CONNECTFAILED:
2589 return "CONNECTFAILED";
2590 case END_CIRC_REASON_OR_IDENTITY:
2591 return "OR_IDENTITY";
2592 case END_CIRC_REASON_OR_CONN_CLOSED:
2593 return "OR_CONN_CLOSED";
2594 case END_CIRC_REASON_FINISHED:
2595 return "FINISHED";
2596 case END_CIRC_REASON_TIMEOUT:
2597 return "TIMEOUT";
2598 case END_CIRC_REASON_DESTROYED:
2599 return "DESTROYED";
2600 case END_CIRC_REASON_NOPATH:
2601 return "NOPATH";
2602 case END_CIRC_REASON_NOSUCHSERVICE:
2603 return "NOSUCHSERVICE";
2604 default:
2605 log_warn(LD_BUG, "Unrecognized reason code %d", (int)reason);
2606 return NULL;
2610 /** Something has happened to circuit <b>circ</b>: tell any interested
2611 * control connections. */
2613 control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
2614 int reason_code)
2616 char *path=NULL;
2617 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
2618 return 0;
2619 tor_assert(circ);
2621 if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS))
2622 path = circuit_list_path(circ,0);
2623 if (EVENT_IS_INTERESTING1(EVENT_CIRCUIT_STATUS)) {
2624 const char *status;
2625 char reason_buf[64];
2626 int providing_reason=0;
2627 switch (tp)
2629 case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
2630 case CIRC_EVENT_BUILT: status = "BUILT"; break;
2631 case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
2632 case CIRC_EVENT_FAILED: status = "FAILED"; break;
2633 case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
2634 default:
2635 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
2636 return 0;
2639 if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
2640 const char *reason_str = circuit_end_reason_to_string(reason_code);
2641 char *reason = NULL;
2642 providing_reason=1;
2643 if (!reason_str) {
2644 reason = tor_malloc(16);
2645 tor_snprintf(reason, 16, "UNKNOWN_%d", reason_code);
2646 reason_str = reason;
2648 if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
2649 tor_snprintf(reason_buf, sizeof(reason_buf),
2650 "REASON=DESTROYED REMOTE_REASON=%s", reason_str);
2651 } else {
2652 tor_snprintf(reason_buf, sizeof(reason_buf),
2653 "REASON=%s", reason_str);
2655 tor_free(reason);
2658 if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS)) {
2659 const char *sp = strlen(path) ? " " : "";
2660 if (providing_reason)
2661 send_control1_event_extended(EVENT_CIRCUIT_STATUS, SHORT_NAMES,
2662 "650 CIRC %lu %s%s%s@%s\r\n",
2663 (unsigned long)circ->global_identifier,
2664 status, sp, path, reason_buf);
2665 else
2666 send_control1_event_extended(EVENT_CIRCUIT_STATUS, SHORT_NAMES,
2667 "650 CIRC %lu %s%s%s\r\n",
2668 (unsigned long)circ->global_identifier,
2669 status, sp, path);
2671 if (EVENT_IS_INTERESTING1L(EVENT_CIRCUIT_STATUS)) {
2672 char *vpath = circuit_list_path_for_controller(circ);
2673 const char *sp = strlen(vpath) ? " " : "";
2674 if (providing_reason)
2675 send_control1_event_extended(EVENT_CIRCUIT_STATUS, LONG_NAMES,
2676 "650 CIRC %lu %s%s%s@%s\r\n",
2677 (unsigned long)circ->global_identifier,
2678 status, sp, vpath, reason_buf);
2679 else
2680 send_control1_event_extended(EVENT_CIRCUIT_STATUS, LONG_NAMES,
2681 "650 CIRC %lu %s%s%s\r\n",
2682 (unsigned long)circ->global_identifier,
2683 status, sp, vpath);
2684 tor_free(vpath);
2687 tor_free(path);
2689 return 0;
2692 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
2693 * <b>buf</b>, determine the address:port combination requested on
2694 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
2695 * failure. */
2696 static int
2697 write_stream_target_to_buf(edge_connection_t *conn, char *buf, size_t len)
2699 char buf2[256];
2700 if (conn->chosen_exit_name)
2701 if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
2702 return -1;
2703 if (tor_snprintf(buf, len, "%s%s%s:%d",
2704 conn->socks_request->address,
2705 conn->chosen_exit_name ? buf2 : "",
2706 !conn->chosen_exit_name &&
2707 connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
2708 conn->socks_request->port)<0)
2709 return -1;
2710 return 0;
2713 /** Convert the reason for ending a stream <b>reason</b> into the format used
2714 * in STREAM events. Return NULL if the reason is unrecognized. */
2715 static const char *
2716 stream_end_reason_to_string(int reason)
2718 reason &= END_STREAM_REASON_MASK;
2719 switch (reason) {
2720 case END_STREAM_REASON_MISC: return "MISC";
2721 case END_STREAM_REASON_RESOLVEFAILED: return "RESOLVEFAILED";
2722 case END_STREAM_REASON_CONNECTREFUSED: return "CONNECTREFUSED";
2723 case END_STREAM_REASON_EXITPOLICY: return "EXITPOLICY";
2724 case END_STREAM_REASON_DESTROY: return "DESTROY";
2725 case END_STREAM_REASON_DONE: return "DONE";
2726 case END_STREAM_REASON_TIMEOUT: return "TIMEOUT";
2727 case END_STREAM_REASON_HIBERNATING: return "HIBERNATING";
2728 case END_STREAM_REASON_INTERNAL: return "INTERNAL";
2729 case END_STREAM_REASON_RESOURCELIMIT: return "RESOURCELIMIT";
2730 case END_STREAM_REASON_CONNRESET: return "CONNRESET";
2731 case END_STREAM_REASON_TORPROTOCOL: return "TORPROTOCOL";
2732 case END_STREAM_REASON_NOTDIRECTORY: return "NOTDIRECTORY";
2734 case END_STREAM_REASON_CANT_ATTACH: return "CANT_ATTACH";
2735 case END_STREAM_REASON_NET_UNREACHABLE: return "NET_UNREACHABLE";
2736 case END_STREAM_REASON_SOCKSPROTOCOL: return "SOCKS_PROTOCOL";
2738 default: return NULL;
2742 /** Something has happened to the stream associated with AP connection
2743 * <b>conn</b>: tell any interested control connections. */
2745 control_event_stream_status(edge_connection_t *conn, stream_status_event_t tp,
2746 int reason_code)
2748 char buf[256];
2749 tor_assert(conn->socks_request);
2751 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
2752 return 0;
2754 if (tp == STREAM_EVENT_CLOSED &&
2755 (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
2756 return 0;
2758 write_stream_target_to_buf(conn, buf, sizeof(buf));
2759 if (EVENT_IS_INTERESTING1(EVENT_STREAM_STATUS)) {
2760 char reason_buf[64];
2761 const char *status;
2762 circuit_t *circ;
2763 origin_circuit_t *origin_circ = NULL;
2764 reason_buf[0] = '\0';
2765 switch (tp)
2767 case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
2768 case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
2769 case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
2770 case STREAM_EVENT_FAILED: status = "FAILED"; break;
2771 case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
2772 case STREAM_EVENT_NEW: status = "NEW"; break;
2773 case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
2774 case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
2775 case STREAM_EVENT_REMAP: status = "REMAP"; break;
2776 default:
2777 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
2778 return 0;
2780 if (reason_code && (tp == STREAM_EVENT_FAILED ||
2781 tp == STREAM_EVENT_CLOSED ||
2782 tp == STREAM_EVENT_FAILED_RETRIABLE)) {
2783 const char *reason_str = stream_end_reason_to_string(reason_code);
2784 char *r = NULL;
2785 if (!reason_str) {
2786 r = tor_malloc(16);
2787 tor_snprintf(r, 16, "UNKNOWN_%d", reason_code);
2788 reason_str = r;
2790 if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
2791 tor_snprintf(reason_buf, sizeof(reason_buf),
2792 "REASON=END REMOTE_REASON=%s", reason_str);
2793 else
2794 tor_snprintf(reason_buf, sizeof(reason_buf),
2795 "REASON=%s", reason_str);
2796 tor_free(r);
2797 } else if (reason_code && tp == STREAM_EVENT_REMAP) {
2798 switch (reason_code) {
2799 case REMAP_STREAM_SOURCE_CACHE:
2800 strlcpy(reason_buf, "SOURCE=CACHE", sizeof(reason_buf));
2801 break;
2802 case REMAP_STREAM_SOURCE_EXIT:
2803 strlcpy(reason_buf, "SOURCE=EXIT", sizeof(reason_buf));
2804 break;
2805 default:
2806 tor_snprintf(reason_buf, sizeof(reason_buf), "REASON=UNKNOWN_%d",
2807 reason_code);
2808 break;
2811 circ = circuit_get_by_edge_conn(conn);
2812 if (circ && CIRCUIT_IS_ORIGIN(circ))
2813 origin_circ = TO_ORIGIN_CIRCUIT(circ);
2814 send_control1_event_extended(EVENT_STREAM_STATUS, ALL_NAMES,
2815 "650 STREAM %lu %s %lu %s@%s\r\n",
2816 (unsigned long)conn->global_identifier, status,
2817 origin_circ?
2818 (unsigned long)origin_circ->global_identifier : 0ul,
2819 buf, reason_buf);
2820 /* XXX need to specify its intended exit, etc? */
2822 return 0;
2825 /** Figure out the best name for the target router of an OR connection
2826 * <b>conn</b>, and write it into the <b>len</b>-character buffer
2827 * <b>name</b>. Use verbose names if <b>long_names</b> is set. */
2828 static void
2829 orconn_target_get_name(int long_names,
2830 char *name, size_t len, or_connection_t *conn)
2832 if (! long_names) {
2833 if (conn->nickname)
2834 strlcpy(name, conn->nickname, len);
2835 else
2836 tor_snprintf(name, len, "%s:%d",
2837 conn->_base.address, conn->_base.port);
2838 } else {
2839 routerinfo_t *ri = router_get_by_digest(conn->identity_digest);
2840 if (ri) {
2841 tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
2842 router_get_verbose_nickname(name, ri);
2843 } else if (! tor_digest_is_zero(conn->identity_digest)) {
2844 name[0] = '$';
2845 base16_encode(name+1, len-1, conn->identity_digest,
2846 DIGEST_LEN);
2847 } else {
2848 tor_snprintf(name, len, "%s:%d",
2849 conn->_base.address, conn->_base.port);
2854 /** Convert a TOR_TLS_* error code into an END_OR_CONN_* reason. */
2856 control_tls_error_to_reason(int e)
2858 switch (e) {
2859 case TOR_TLS_ERROR_IO:
2860 return END_OR_CONN_REASON_TLS_IO_ERROR;
2861 case TOR_TLS_ERROR_CONNREFUSED:
2862 return END_OR_CONN_REASON_TCP_REFUSED;
2863 case TOR_TLS_ERROR_CONNRESET:
2864 return END_OR_CONN_REASON_TLS_CONNRESET;
2865 case TOR_TLS_ERROR_NO_ROUTE:
2866 return END_OR_CONN_REASON_TLS_NO_ROUTE;
2867 case TOR_TLS_ERROR_TIMEOUT:
2868 return END_OR_CONN_REASON_TLS_TIMEOUT;
2869 case TOR_TLS_WANTREAD:
2870 case TOR_TLS_WANTWRITE:
2871 case TOR_TLS_CLOSE:
2872 case TOR_TLS_DONE:
2873 return END_OR_CONN_REASON_DONE;
2874 default:
2875 return END_OR_CONN_REASON_TLS_MISC;
2879 /** Convert the reason for ending an OR connection <b>r</b> into the format
2880 * used in ORCONN events. Return NULL if the reason is unrecognized. */
2881 static const char *
2882 or_conn_end_reason_to_string(int r)
2884 switch (r) {
2885 case END_OR_CONN_REASON_DONE:
2886 return "REASON=DONE";
2887 case END_OR_CONN_REASON_TCP_REFUSED:
2888 return "REASON=CONNECTREFUSED";
2889 case END_OR_CONN_REASON_OR_IDENTITY:
2890 return "REASON=IDENTITY";
2891 case END_OR_CONN_REASON_TLS_CONNRESET:
2892 return "REASON=CONNECTRESET";
2893 case END_OR_CONN_REASON_TLS_TIMEOUT:
2894 return "REASON=TIMEOUT";
2895 case END_OR_CONN_REASON_TLS_NO_ROUTE:
2896 return "REASON=NOROUTE";
2897 case END_OR_CONN_REASON_TLS_IO_ERROR:
2898 return "REASON=IOERROR";
2899 case END_OR_CONN_REASON_TLS_MISC:
2900 return "REASON=MISC";
2901 case 0:
2902 return "";
2903 default:
2904 log_warn(LD_BUG, "Unrecognized or_conn reason code %d", r);
2905 return "REASON=BOGUS";
2909 /** Called when the status of an OR connection <b>conn</b> changes: tell any
2910 * interested control connections. <b>tp</b> is the new status for the
2911 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
2912 * may be the reason why.
2915 control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
2916 int reason)
2918 int ncircs = 0;
2920 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
2921 return 0;
2923 if (EVENT_IS_INTERESTING1(EVENT_OR_CONN_STATUS)) {
2924 const char *status;
2925 char name[128];
2926 char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
2927 switch (tp)
2929 case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
2930 case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
2931 case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
2932 case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
2933 case OR_CONN_EVENT_NEW: status = "NEW"; break;
2934 default:
2935 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
2936 return 0;
2938 ncircs = circuit_count_pending_on_or_conn(conn);
2939 ncircs += conn->n_circuits;
2940 if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
2941 tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
2942 reason ? " " : "", ncircs);
2945 if (EVENT_IS_INTERESTING1S(EVENT_OR_CONN_STATUS)) {
2946 orconn_target_get_name(0, name, sizeof(name), conn);
2947 send_control1_event_extended(EVENT_OR_CONN_STATUS, SHORT_NAMES,
2948 "650 ORCONN %s %s@%s%s\r\n",
2949 name, status,
2950 or_conn_end_reason_to_string(reason), ncircs_buf);
2952 if (EVENT_IS_INTERESTING1L(EVENT_OR_CONN_STATUS)) {
2953 orconn_target_get_name(1, name, sizeof(name), conn);
2954 send_control1_event_extended(EVENT_OR_CONN_STATUS, LONG_NAMES,
2955 "650 ORCONN %s %s@%s%s\r\n",
2956 name, status,
2957 or_conn_end_reason_to_string(reason), ncircs_buf);
2960 return 0;
2963 /** A second or more has elapsed: tell any interested control
2964 * connections how much bandwidth streams have used. */
2966 control_event_stream_bandwidth_used(void)
2968 connection_t **carray;
2969 edge_connection_t *conn;
2970 int n, i;
2972 if (EVENT_IS_INTERESTING1(EVENT_STREAM_BANDWIDTH_USED)) {
2974 get_connection_array(&carray, &n);
2976 for (i = 0; i < n; ++i) {
2977 if (carray[i]->type != CONN_TYPE_AP)
2978 continue;
2979 conn = TO_EDGE_CONN(carray[i]);
2980 if (!conn->n_read && !conn->n_written)
2981 continue;
2983 send_control1_event(EVENT_STREAM_BANDWIDTH_USED, ALL_NAMES,
2984 "650 STREAM_BW %lu %lu %lu\r\n",
2985 (unsigned long)conn->global_identifier,
2986 (unsigned long)conn->n_read,
2987 (unsigned long)conn->n_written);
2989 conn->n_written = conn->n_read = 0;
2993 return 0;
2996 /** A second or more has elapsed: tell any interested control
2997 * connections how much bandwidth we used. */
2999 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
3001 if (EVENT_IS_INTERESTING1(EVENT_BANDWIDTH_USED)) {
3002 send_control1_event(EVENT_BANDWIDTH_USED, ALL_NAMES,
3003 "650 BW %lu %lu\r\n",
3004 (unsigned long)n_read,
3005 (unsigned long)n_written);
3008 return 0;
3011 /** Called when we are sending a log message to the controllers: suspend
3012 * sending further log messages to the controllers until we're done. Used by
3013 * CONN_LOG_PROTECT. */
3014 void
3015 disable_control_logging(void)
3017 ++disable_log_messages;
3020 /** We're done sending a log message to the controllers: re-enable controller
3021 * logging. Used by CONN_LOG_PROTECT. */
3022 void
3023 enable_control_logging(void)
3025 if (--disable_log_messages < 0)
3026 tor_assert(0);
3029 /** We got a log message: tell any interested control connections. */
3030 void
3031 control_event_logmsg(int severity, uint32_t domain, const char *msg)
3033 int event;
3034 if (disable_log_messages)
3035 return;
3037 if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
3038 severity <= LOG_NOTICE) {
3039 char *esc = esc_for_log(msg);
3040 ++disable_log_messages;
3041 control_event_general_status(severity, "BUG REASON=\"%s\"", esc);
3042 --disable_log_messages;
3043 tor_free(esc);
3046 event = log_severity_to_event(severity);
3047 if (event >= 0 && EVENT_IS_INTERESTING1(event)) {
3048 char *b = NULL;
3049 const char *s;
3050 if (strchr(msg, '\n')) {
3051 char *cp;
3052 b = tor_strdup(msg);
3053 for (cp = b; *cp; ++cp)
3054 if (*cp == '\r' || *cp == '\n')
3055 *cp = ' ';
3057 switch (severity) {
3058 case LOG_DEBUG: s = "DEBUG"; break;
3059 case LOG_INFO: s = "INFO"; break;
3060 case LOG_NOTICE: s = "NOTICE"; break;
3061 case LOG_WARN: s = "WARN"; break;
3062 case LOG_ERR: s = "ERR"; break;
3063 default: s = "UnknownLogSeverity"; break;
3065 ++disable_log_messages;
3066 send_control1_event(event, ALL_NAMES, "650 %s %s\r\n", s, b?b:msg);
3067 --disable_log_messages;
3068 tor_free(b);
3072 /** Called whenever we receive new router descriptors: tell any
3073 * interested control connections. <b>routers</b> is a list of
3074 * DIGEST_LEN-byte identity digests.
3077 control_event_descriptors_changed(smartlist_t *routers)
3079 size_t len;
3080 char *msg;
3081 smartlist_t *identities = NULL;
3082 char buf[HEX_DIGEST_LEN+1];
3084 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
3085 return 0;
3086 if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC)) {
3087 identities = smartlist_create();
3088 SMARTLIST_FOREACH(routers, routerinfo_t *, r,
3090 base16_encode(buf,sizeof(buf),r->cache_info.identity_digest,DIGEST_LEN);
3091 smartlist_add(identities, tor_strdup(buf));
3094 if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC)) {
3095 char *ids = smartlist_join_strings(identities, " ", 0, &len);
3096 size_t len = strlen(ids)+32;
3097 msg = tor_malloc(len);
3098 tor_snprintf(msg, len, "650 NEWDESC %s\r\n", ids);
3099 send_control1_event_string(EVENT_NEW_DESC, SHORT_NAMES|ALL_FORMATS, msg);
3100 tor_free(ids);
3101 tor_free(msg);
3103 if (EVENT_IS_INTERESTING1L(EVENT_NEW_DESC)) {
3104 smartlist_t *names = smartlist_create();
3105 char *ids;
3106 size_t len;
3107 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
3108 char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
3109 router_get_verbose_nickname(b, ri);
3110 smartlist_add(names, b);
3112 ids = smartlist_join_strings(names, " ", 0, &len);
3113 len = strlen(ids)+32;
3114 msg = tor_malloc(len);
3115 tor_snprintf(msg, len, "650 NEWDESC %s\r\n", ids);
3116 send_control1_event_string(EVENT_NEW_DESC, LONG_NAMES|ALL_FORMATS, msg);
3117 tor_free(ids);
3118 tor_free(msg);
3119 SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
3120 smartlist_free(names);
3122 if (identities) {
3123 SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
3124 smartlist_free(identities);
3126 return 0;
3129 /** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
3130 * <b>expires</b> values less than 3 are special; see connection_edge.c. */
3132 control_event_address_mapped(const char *from, const char *to, time_t expires)
3134 if (!EVENT_IS_INTERESTING1(EVENT_ADDRMAP))
3135 return 0;
3137 if (expires < 3)
3138 send_control1_event(EVENT_ADDRMAP, ALL_NAMES,
3139 "650 ADDRMAP %s %s NEVER\r\n", from, to);
3140 else {
3141 char buf[ISO_TIME_LEN+1];
3142 format_local_iso_time(buf,expires);
3143 send_control1_event(EVENT_ADDRMAP, ALL_NAMES,
3144 "650 ADDRMAP %s %s \"%s\"\r\n",
3145 from, to, buf);
3148 return 0;
3151 /** The authoritative dirserver has received a new descriptor that
3152 * has passed basic syntax checks and is properly self-signed.
3154 * Notify any interested party of the new descriptor and what has
3155 * been done with it, and also optionally give an explanation/reason. */
3157 control_event_or_authdir_new_descriptor(const char *action,
3158 const char *descriptor,
3159 const char *msg)
3161 char firstline[1024];
3162 char *buf;
3163 int totallen;
3164 char *esc = NULL;
3165 size_t esclen;
3167 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
3168 return 0;
3170 tor_snprintf(firstline, sizeof(firstline),
3171 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
3172 action,
3173 msg ? msg : "");
3175 /* Escape the server descriptor properly */
3176 esclen = write_escaped_data(descriptor, strlen(descriptor), 1, &esc);
3178 totallen = strlen(firstline) + esclen + 1;
3179 buf = tor_malloc(totallen);
3180 strlcpy(buf, firstline, totallen);
3181 strlcpy(buf+strlen(firstline), esc, totallen);
3182 send_control1_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_NAMES|ALL_FORMATS,
3183 buf);
3185 tor_free(esc);
3186 tor_free(buf);
3188 return 0;
3191 /** Called when the local_routerstatus_ts <b>statuses</b> have changed: sends
3192 * an NS event to any controller that cares. */
3194 control_event_networkstatus_changed(smartlist_t *statuses)
3196 smartlist_t *strs;
3197 char *s;
3198 if (!EVENT_IS_INTERESTING(EVENT_NS) || !smartlist_len(statuses))
3199 return 0;
3201 strs = smartlist_create();
3202 smartlist_add(strs, tor_strdup("650+NS\r\n"));
3203 SMARTLIST_FOREACH(statuses, local_routerstatus_t *, rs,
3205 s = networkstatus_getinfo_helper_single(&rs->status);
3206 if (!s) continue;
3207 smartlist_add(strs, s);
3209 smartlist_add(strs, tor_strdup("\r\n.\r\n"));
3211 s = smartlist_join_strings(strs, "", 0, NULL);
3212 SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
3213 smartlist_free(strs);
3214 send_control1_event_string(EVENT_NS, ALL_NAMES|ALL_FORMATS, s);
3215 tor_free(s);
3216 return 0;
3219 /** Called when a single local_routerstatus_t has changed: Sends an NS event
3220 * to any countroller that cares. */
3222 control_event_networkstatus_changed_single(local_routerstatus_t *rs)
3224 smartlist_t *statuses;
3225 int r;
3227 if (!EVENT_IS_INTERESTING(EVENT_NS))
3228 return 0;
3230 statuses = smartlist_create();
3231 smartlist_add(statuses, rs);
3232 r = control_event_networkstatus_changed(statuses);
3233 smartlist_free(statuses);
3234 return r;
3237 /** Our own router descriptor has changed; tell any controllers that care.
3240 control_event_my_descriptor_changed(void)
3242 send_control1_event(EVENT_DESCCHANGED, ALL_NAMES, "650 DESCCHANGED\r\n");
3243 return 0;
3246 /** Helper: sends a status event where <b>type</b> is one of
3247 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
3248 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
3249 * string corresponding to <b>args</b>. */
3250 static int
3251 control_event_status(int type, int severity, const char *format, va_list args)
3253 char format_buf[160];
3254 const char *status, *sev;
3256 switch (type) {
3257 case EVENT_STATUS_GENERAL:
3258 status = "STATUS_GENERAL";
3259 break;
3260 case EVENT_STATUS_CLIENT:
3261 status = "STATUS_CLIENT";
3262 break;
3263 case EVENT_STATUS_SERVER:
3264 status = "STATUS_SEVER";
3265 break;
3266 default:
3267 log_warn(LD_BUG, "Unrecognized status type %d", type);
3268 return -1;
3270 switch (severity) {
3271 case LOG_NOTICE:
3272 sev = "NOTICE";
3273 break;
3274 case LOG_WARN:
3275 sev = "WARN";
3276 break;
3277 case LOG_ERR:
3278 sev = "ERR";
3279 break;
3280 default:
3281 log_warn(LD_BUG, "Unrecognized status severity %d", severity);
3282 return -1;
3284 if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s %s\r\n",
3285 status, sev, format)<0) {
3286 log_warn(LD_BUG, "Format string too long.");
3287 return -1;
3290 send_control1_event_impl(type, ALL_NAMES|ALL_FORMATS, 0, format_buf, args);
3291 return 0;
3294 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
3295 * by formatting the arguments using the printf-style <b>format</b>. */
3297 control_event_general_status(int severity, const char *format, ...)
3299 va_list ap;
3300 int r;
3301 if (!EVENT_IS_INTERESTING1(EVENT_STATUS_GENERAL))
3302 return 0;
3304 va_start(ap, format);
3305 r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
3306 va_end(ap);
3307 return r;
3310 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
3311 * by formatting the arguments using the printf-style <b>format</b>. */
3313 control_event_client_status(int severity, const char *format, ...)
3315 va_list ap;
3316 int r;
3317 if (!EVENT_IS_INTERESTING1(EVENT_STATUS_CLIENT))
3318 return 0;
3320 va_start(ap, format);
3321 r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
3322 va_end(ap);
3323 return r;
3326 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
3327 * by formatting the arguments using the printf-style <b>format</b>. */
3329 control_event_server_status(int severity, const char *format, ...)
3331 va_list ap;
3332 int r;
3333 if (!EVENT_IS_INTERESTING1(EVENT_STATUS_SERVER))
3334 return 0;
3336 va_start(ap, format);
3337 r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
3338 va_end(ap);
3339 return r;
3342 /** Called when the status of an entry guard with the given <b>nickname</b>
3343 * and identity <b>digest</b> has changed to <b>status</b>: tells any
3344 * controllers that care. */
3346 control_event_guard(const char *nickname, const char *digest,
3347 const char *status)
3349 char hbuf[HEX_DIGEST_LEN+1];
3350 base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
3351 if (!EVENT_IS_INTERESTING1(EVENT_GUARD))
3352 return 0;
3354 if (EVENT_IS_INTERESTING1L(EVENT_GUARD)) {
3355 char buf[MAX_VERBOSE_NICKNAME_LEN+1];
3356 routerinfo_t *ri = router_get_by_digest(digest);
3357 if (ri) {
3358 router_get_verbose_nickname(buf, ri);
3359 } else {
3360 tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
3362 send_control1_event(EVENT_GUARD, LONG_NAMES,
3363 "650 GUARD ENTRY %s %s\r\n", buf, status);
3365 if (EVENT_IS_INTERESTING1S(EVENT_GUARD)) {
3366 send_control1_event(EVENT_GUARD, SHORT_NAMES,
3367 "650 GUARD ENTRY $%s %s\r\n", hbuf, status);
3369 return 0;
3372 /** Choose a random authentication cookie and write it to disk.
3373 * Anybody who can read the cookie from disk will be considered
3374 * authorized to use the control connection. Return -1 if we can't
3375 * write the file, or 0 on success */
3377 init_cookie_authentication(int enabled)
3379 char fname[512];
3381 if (!enabled) {
3382 authentication_cookie_is_set = 0;
3383 return 0;
3386 if (authentication_cookie_is_set)
3387 return 0;
3389 tor_snprintf(fname, sizeof(fname), "%s/control_auth_cookie",
3390 get_options()->DataDirectory);
3391 crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
3392 authentication_cookie_is_set = 1;
3393 if (write_bytes_to_file(fname, authentication_cookie,
3394 AUTHENTICATION_COOKIE_LEN, 1)) {
3395 log_warn(LD_FS,"Error writing authentication cookie to %s.",
3396 escaped(fname));
3397 return -1;
3400 return 0;