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