1 /* Copyright 2004-2007 Roger Dingledine, Nick Mathewson. */
2 /* See LICENSE for licensing information */
4 const char control_c_id
[] =
9 * \brief Implementation for Tor's control-socket interface.
10 * See doc/spec/control-spec.txt for full details on protocol.
13 #define CONTROL_PRIVATE
17 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
18 * finished authentication and is accepting commands. */
19 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
21 /* Recognized asynchronous event types. It's okay to expand this list
22 * because it is used both as a list of v0 event types, and as indices
23 * into the bitfield to determine which controllers want which events.
25 #define _EVENT_MIN 0x0001
26 #define EVENT_CIRCUIT_STATUS 0x0001
27 #define EVENT_STREAM_STATUS 0x0002
28 #define EVENT_OR_CONN_STATUS 0x0003
29 #define EVENT_BANDWIDTH_USED 0x0004
30 #define EVENT_LOG_OBSOLETE 0x0005 /* Can reclaim this. */
31 #define EVENT_NEW_DESC 0x0006
32 #define EVENT_DEBUG_MSG 0x0007
33 #define EVENT_INFO_MSG 0x0008
34 #define EVENT_NOTICE_MSG 0x0009
35 #define EVENT_WARN_MSG 0x000A
36 #define EVENT_ERR_MSG 0x000B
37 #define EVENT_ADDRMAP 0x000C
38 // #define EVENT_AUTHDIR_NEWDESCS 0x000D
39 #define EVENT_DESCCHANGED 0x000E
40 #define EVENT_NS 0x000F
41 #define EVENT_STATUS_CLIENT 0x0010
42 #define EVENT_STATUS_SERVER 0x0011
43 #define EVENT_STATUS_GENERAL 0x0012
44 #define EVENT_GUARD 0x0013
45 #define EVENT_STREAM_BANDWIDTH_USED 0x0014
46 #define _EVENT_MAX 0x0014
47 /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
49 /** Bitfield: The bit 1<<e is set if <b>any</b> open control
50 * connection is interested in events of type <b>e</b>. We use this
51 * so that we can decide to skip generating event messages that nobody
52 * has interest in without having to walk over the global connection
55 typedef uint32_t event_mask_t
;
56 static event_mask_t global_event_mask1long
= 0;
57 static event_mask_t global_event_mask1short
= 0;
59 /** True iff we have disabled log messages from being sent to the controller */
60 static int disable_log_messages
= 0;
62 /** Macro: true if any control connection is interested in events of type
64 #define EVENT_IS_INTERESTING(e) \
65 ((global_event_mask1long|global_event_mask1short) & (1<<(e)))
66 #define EVENT_IS_INTERESTING1L(e) (global_event_mask1long & (1<<(e)))
67 #define EVENT_IS_INTERESTING1S(e) (global_event_mask1short & (1<<(e)))
69 /** If we're using cookie-type authentication, how long should our cookies be?
71 #define AUTHENTICATION_COOKIE_LEN 32
73 /** If true, we've set authentication_cookie to a secret code and
74 * stored it to disk. */
75 static int authentication_cookie_is_set
= 0;
76 static char authentication_cookie
[AUTHENTICATION_COOKIE_LEN
];
80 #define ALL_NAMES (SHORT_NAMES|LONG_NAMES)
81 #define EXTENDED_FORMAT 4
82 #define NONEXTENDED_FORMAT 8
83 #define ALL_FORMATS (EXTENDED_FORMAT|NONEXTENDED_FORMAT)
84 typedef int event_format_t
;
86 static void connection_printf_to_buf(control_connection_t
*conn
,
87 const char *format
, ...)
89 static void send_control_done(control_connection_t
*conn
);
90 static void send_control_event(uint16_t event
, event_format_t which
,
91 const char *format
, ...)
93 static void send_control_event_extended(uint16_t event
, event_format_t which
,
94 const char *format
, ...)
96 static int handle_control_setconf(control_connection_t
*conn
, uint32_t len
,
98 static int handle_control_resetconf(control_connection_t
*conn
, uint32_t len
,
100 static int handle_control_getconf(control_connection_t
*conn
, uint32_t len
,
102 static int handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
104 static int handle_control_authenticate(control_connection_t
*conn
,
107 static int handle_control_saveconf(control_connection_t
*conn
, uint32_t len
,
109 static int handle_control_signal(control_connection_t
*conn
, uint32_t len
,
111 static int handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
113 static char *list_getinfo_options(void);
114 static int handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
116 static int handle_control_extendcircuit(control_connection_t
*conn
,
119 static int handle_control_setpurpose(control_connection_t
*conn
,
121 uint32_t len
, const char *body
);
122 static int handle_control_attachstream(control_connection_t
*conn
,
125 static int handle_control_postdescriptor(control_connection_t
*conn
,
128 static int handle_control_redirectstream(control_connection_t
*conn
,
131 static int handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
133 static int handle_control_closecircuit(control_connection_t
*conn
,
136 static int handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
138 static int handle_control_usefeature(control_connection_t
*conn
,
141 static int write_stream_target_to_buf(edge_connection_t
*conn
, char *buf
,
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
150 event_to_log_severity(int 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
;
162 /** Given a log severity, return the corresponding control event code. */
164 log_severity_to_event(int 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
;
176 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
177 * connection's event_mask field. */
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
;
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
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
225 control_adjust_event_log_severity(void)
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
)) {
236 for (i
= EVENT_ERR_MSG
; i
>= EVENT_DEBUG_MSG
; --i
) {
237 if (EVENT_IS_INTERESTING(i
)) {
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
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>.
282 write_escaped_data(const char *data
, size_t len
, char **out
)
284 size_t sz_out
= len
+8;
286 const char *start
= data
, *end
;
289 for (i
=0; i
<(int)len
; ++i
) {
291 sz_out
+= 2; /* Maybe add a CR; maybe add a dot. */
293 *out
= outp
= tor_malloc(sz_out
+1);
298 if (data
> start
&& data
[-1] != '\r')
301 } else if (*data
== '.') {
311 if (outp
< *out
+2 || memcmp(outp
-2, "\r\n", 2)) {
318 *outp
= '\0'; /* NUL-terminate just in case. */
319 tor_assert((outp
- *out
) <= (int)sz_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>. */
330 read_escaped_data(const char *data
, size_t len
, char **out
)
336 *out
= outp
= tor_malloc(len
+1);
341 /* we're at the start of a line. */
344 next
= memchr(data
, '\n', end
-data
);
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')
350 memcpy(outp
, data
, 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. */
355 memcpy(outp
, data
, end
-data
);
367 /** Given a pointer to a string starting at <b>start</b> containing
368 * <b>in_len_max</b> characters, decode a string beginning with one double
369 * quote, containing any number of non-quote characters or characters escaped
370 * with a backslash, and ending with a final double quote. Place the resulting
371 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
372 * store its length in <b>out_len</b>. On success, return a pointer to the
373 * character immediately following the escaped string. On failure, return
376 get_escaped_string(const char *start
, size_t in_len_max
,
377 char **out
, size_t *out_len
)
379 const char *cp
, *end
;
387 end
= start
+in_len_max
;
389 /* Calculate length. */
393 else if (*cp
== '\\') {
395 return NULL
; /* Can't escape EOS. */
398 } else if (*cp
== '\"') {
406 outp
= *out
= tor_malloc(len
+1);
416 tor_assert((outp
- *out
) == (int)*out_len
);
421 /** Acts like sprintf, but writes its formatted string to the end of
422 * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
423 * but it will always end with a CRLF sequence.
425 * Currently the length of the message is limited to 1024 (including the
428 connection_printf_to_buf(control_connection_t
*conn
, const char *format
, ...)
430 #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
432 char buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
];
436 r
= tor_vsnprintf(buf
, sizeof(buf
), format
, ap
);
439 log_warn(LD_BUG
, "Unable to format string for controller.");
443 if (memcmp("\r\n\0", buf
+len
-2, 3)) {
444 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-1] = '\0';
445 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-2] = '\n';
446 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-3] = '\r';
448 connection_write_to_buf(buf
, len
, TO_CONN(conn
));
451 /** Send a "DONE" message down the control connection <b>conn</b> */
453 send_control_done(control_connection_t
*conn
)
455 connection_write_str_to_buf("250 OK\r\n", conn
);
458 /* Send an event to all v1 controllers that are listening for code
459 * <b>event</b>. The event's body is given by <b>msg</b>.
461 * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
462 * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
463 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
464 * to contollers that <em>have</em> enabled VERBOSE_NAMES.
466 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
467 * respect to the EXTENDED_EVENTS feature. */
469 send_control_event_string(uint16_t event
, event_format_t which
,
472 smartlist_t
*conns
= get_connection_array();
473 tor_assert(event
>= _EVENT_MIN
&& event
<= _EVENT_MAX
);
475 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
477 if (conn
->type
== CONN_TYPE_CONTROL
&&
478 !conn
->marked_for_close
&&
479 conn
->state
== CONTROL_CONN_STATE_OPEN
) {
480 control_connection_t
*control_conn
= TO_CONTROL_CONN(conn
);
481 if (control_conn
->use_long_names
) {
482 if (!(which
& LONG_NAMES
))
485 if (!(which
& SHORT_NAMES
))
488 if (control_conn
->use_extended_events
) {
489 if (!(which
& EXTENDED_FORMAT
))
492 if (!(which
& NONEXTENDED_FORMAT
))
495 if (control_conn
->event_mask
& (1<<event
)) {
497 connection_write_to_buf(msg
, strlen(msg
), TO_CONN(control_conn
));
498 if (event
== EVENT_ERR_MSG
)
500 else if (event
== EVENT_STATUS_GENERAL
)
501 is_err
= !strcmpstart(msg
, "STATUS_GENERAL ERR ");
502 else if (event
== EVENT_STATUS_CLIENT
)
503 is_err
= !strcmpstart(msg
, "STATUS_CLIENT ERR ");
504 else if (event
== EVENT_STATUS_SERVER
)
505 is_err
= !strcmpstart(msg
, "STATUS_SERVER ERR ");
507 connection_handle_write(TO_CONN(control_conn
), 1);
513 /** Helper for send_control1_event and send_control1_event_extended:
514 * Send an event to all v1 controllers that are listening for code
515 * <b>event</b>. The event's body is created by the printf-style format in
516 * <b>format</b>, and other arguments as provided.
518 * If <b>extended</b> is true, and the format contains a single '@' character,
519 * it will be replaced with a space and all text after that character will be
520 * sent only to controllers that have enabled extended events.
522 * Currently the length of the message is limited to 1024 (including the
525 send_control_event_impl(uint16_t event
, event_format_t which
, int extended
,
526 const char *format
, va_list ap
)
528 /* This is just a little longer than the longest allowed log message */
529 #define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
531 char buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
];
535 r
= tor_vsnprintf(buf
, sizeof(buf
), format
, ap
);
537 log_warn(LD_BUG
, "Unable to format event for controller.");
542 if (memcmp("\r\n\0", buf
+len
-2, 3)) {
543 /* if it is not properly terminated, do it now */
544 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-1] = '\0';
545 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-2] = '\n';
546 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-3] = '\r';
549 if (extended
&& (cp
= strchr(buf
, '@'))) {
550 which
&= ~ALL_FORMATS
;
552 send_control_event_string(event
, which
|EXTENDED_FORMAT
, buf
);
553 memcpy(cp
, "\r\n\0", 3);
554 send_control_event_string(event
, which
|NONEXTENDED_FORMAT
, buf
);
556 send_control_event_string(event
, which
|ALL_FORMATS
, buf
);
560 /* Send an event to all v1 controllers that are listening for code
561 * <b>event</b>. The event's body is created by the printf-style format in
562 * <b>format</b>, and other arguments as provided.
564 * Currently the length of the message is limited to 1024 (including the
567 send_control_event(uint16_t event
, event_format_t which
,
568 const char *format
, ...)
571 va_start(ap
, format
);
572 send_control_event_impl(event
, which
, 0, format
, ap
);
576 /* Send an event to all v1 controllers that are listening for code
577 * <b>event</b>. The event's body is created by the printf-style format in
578 * <b>format</b>, and other arguments as provided.
580 * If the format contains a single '@' character, it will be replaced with a
581 * space and all text after that character will be sent only to controllers
582 * that have enabled extended events.
584 * Currently the length of the message is limited to 1024 (including the
587 send_control_event_extended(uint16_t event
, event_format_t which
,
588 const char *format
, ...)
591 va_start(ap
, format
);
592 send_control_event_impl(event
, which
, 1, format
, ap
);
596 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
597 static origin_circuit_t
*
598 get_circ(const char *id
)
602 n_id
= tor_parse_ulong(id
, 10, 0, ULONG_MAX
, &ok
, NULL
);
605 return circuit_get_by_global_id(n_id
);
608 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
609 static edge_connection_t
*
610 get_stream(const char *id
)
614 edge_connection_t
*conn
;
615 n_id
= tor_parse_ulong(id
, 10, 0, ULONG_MAX
, &ok
, NULL
);
618 conn
= connection_get_by_global_id(n_id
);
619 if (!conn
|| conn
->_base
.type
!= CONN_TYPE_AP
)
624 /** Helper for setconf and resetconf. Acts like setconf, except
625 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
629 control_setconf_helper(control_connection_t
*conn
, uint32_t len
, char *body
,
633 config_line_t
*lines
=NULL
;
635 char *errstring
= NULL
;
636 const int clear_first
= 1;
639 smartlist_t
*entries
= smartlist_create();
641 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
642 * separated by space. break it into a list of configuration entries. */
647 while (!TOR_ISSPACE(*eq
) && *eq
!= '=')
649 key
= tor_strndup(body
, eq
-body
);
656 char *val_start
= body
;
657 while (!TOR_ISSPACE(*body
))
659 val
= tor_strndup(val_start
, body
-val_start
);
660 val_len
= strlen(val
);
662 body
= (char*)get_escaped_string(body
, (len
- (body
-start
)),
665 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn
);
666 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
667 smartlist_free(entries
);
671 ent_len
= strlen(key
)+val_len
+3;
672 entry
= tor_malloc(ent_len
+1);
673 tor_snprintf(entry
, ent_len
, "%s %s", key
, val
);
679 smartlist_add(entries
, entry
);
680 while (TOR_ISSPACE(*body
))
684 smartlist_add(entries
, tor_strdup(""));
685 config
= smartlist_join_strings(entries
, "\n", 0, NULL
);
686 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
687 smartlist_free(entries
);
689 if (config_get_lines(config
, &lines
) < 0) {
690 log_warn(LD_CONTROL
,"Controller gave us config lines we can't parse.");
691 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
698 if ((r
=options_trial_assign(lines
, use_defaults
,
699 clear_first
, &errstring
)) < 0) {
702 "Controller gave us config lines that didn't validate: %s",
706 msg
= "552 Unrecognized option";
709 msg
= "513 Unacceptable option value";
712 msg
= "553 Transition not allowed";
716 msg
= "553 Unable to set option";
719 connection_printf_to_buf(conn
, "%s: %s\r\n", msg
, errstring
);
720 config_free_lines(lines
);
724 config_free_lines(lines
);
725 send_control_done(conn
);
729 /** Called when we receive a SETCONF message: parse the body and try
730 * to update our configuration. Reply with a DONE or ERROR message.
731 * Modifies the contents of body.*/
733 handle_control_setconf(control_connection_t
*conn
, uint32_t len
, char *body
)
735 return control_setconf_helper(conn
, len
, body
, 0);
738 /** Called when we receive a RESETCONF message: parse the body and try
739 * to update our configuration. Reply with a DONE or ERROR message.
740 * Modifies the contents of body. */
742 handle_control_resetconf(control_connection_t
*conn
, uint32_t len
, char *body
)
744 return control_setconf_helper(conn
, len
, body
, 1);
747 /** Called when we receive a GETCONF message. Parse the request, and
748 * reply with a CONFVALUE or an ERROR message */
750 handle_control_getconf(control_connection_t
*conn
, uint32_t body_len
,
753 smartlist_t
*questions
= NULL
;
754 smartlist_t
*answers
= NULL
;
755 smartlist_t
*unrecognized
= NULL
;
758 or_options_t
*options
= get_options();
761 questions
= smartlist_create();
762 (void) body_len
; /* body is nul-terminated; so we can ignore len. */
763 smartlist_split_string(questions
, body
, " ",
764 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
765 answers
= smartlist_create();
766 unrecognized
= smartlist_create();
767 SMARTLIST_FOREACH(questions
, char *, q
,
769 if (!option_is_recognized(q
)) {
770 smartlist_add(unrecognized
, q
);
772 config_line_t
*answer
= option_get_assignment(options
,q
);
774 const char *name
= option_get_canonical_name(q
);
775 size_t alen
= strlen(name
)+8;
776 char *astr
= tor_malloc(alen
);
777 tor_snprintf(astr
, alen
, "250-%s\r\n", name
);
778 smartlist_add(answers
, astr
);
783 size_t alen
= strlen(answer
->key
)+strlen(answer
->value
)+8;
784 char *astr
= tor_malloc(alen
);
785 tor_snprintf(astr
, alen
, "250-%s=%s\r\n",
786 answer
->key
, answer
->value
);
787 smartlist_add(answers
, astr
);
790 tor_free(answer
->key
);
791 tor_free(answer
->value
);
798 if ((len
= smartlist_len(unrecognized
))) {
799 for (i
=0; i
< len
-1; ++i
)
800 connection_printf_to_buf(conn
,
801 "552-Unrecognized configuration key \"%s\"\r\n",
802 (char*)smartlist_get(unrecognized
, i
));
803 connection_printf_to_buf(conn
,
804 "552 Unrecognized configuration key \"%s\"\r\n",
805 (char*)smartlist_get(unrecognized
, len
-1));
806 } else if ((len
= smartlist_len(answers
))) {
807 char *tmp
= smartlist_get(answers
, len
-1);
808 tor_assert(strlen(tmp
)>4);
810 msg
= smartlist_join_strings(answers
, "", 0, &msg_len
);
811 connection_write_to_buf(msg
, msg_len
, TO_CONN(conn
));
813 connection_write_str_to_buf("250 OK\r\n", conn
);
817 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
818 smartlist_free(answers
);
821 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
822 smartlist_free(questions
);
824 smartlist_free(unrecognized
);
830 /** Called when we get a SETEVENTS message: update conn->event_mask,
831 * and reply with DONE or ERROR. */
833 handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
837 uint32_t event_mask
= 0;
838 unsigned int extended
= 0;
839 smartlist_t
*events
= smartlist_create();
843 smartlist_split_string(events
, body
, " ",
844 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
845 SMARTLIST_FOREACH(events
, const char *, ev
,
847 if (!strcasecmp(ev
, "EXTENDED")) {
850 } else if (!strcasecmp(ev
, "CIRC"))
851 event_code
= EVENT_CIRCUIT_STATUS
;
852 else if (!strcasecmp(ev
, "STREAM"))
853 event_code
= EVENT_STREAM_STATUS
;
854 else if (!strcasecmp(ev
, "ORCONN"))
855 event_code
= EVENT_OR_CONN_STATUS
;
856 else if (!strcasecmp(ev
, "BW"))
857 event_code
= EVENT_BANDWIDTH_USED
;
858 else if (!strcasecmp(ev
, "DEBUG"))
859 event_code
= EVENT_DEBUG_MSG
;
860 else if (!strcasecmp(ev
, "INFO"))
861 event_code
= EVENT_INFO_MSG
;
862 else if (!strcasecmp(ev
, "NOTICE"))
863 event_code
= EVENT_NOTICE_MSG
;
864 else if (!strcasecmp(ev
, "WARN"))
865 event_code
= EVENT_WARN_MSG
;
866 else if (!strcasecmp(ev
, "ERR"))
867 event_code
= EVENT_ERR_MSG
;
868 else if (!strcasecmp(ev
, "NEWDESC"))
869 event_code
= EVENT_NEW_DESC
;
870 else if (!strcasecmp(ev
, "ADDRMAP"))
871 event_code
= EVENT_ADDRMAP
;
872 else if (!strcasecmp(ev
, "AUTHDIR_NEWDESCS"))
873 event_code
= EVENT_AUTHDIR_NEWDESCS
;
874 else if (!strcasecmp(ev
, "DESCCHANGED"))
875 event_code
= EVENT_DESCCHANGED
;
876 else if (!strcasecmp(ev
, "NS"))
877 event_code
= EVENT_NS
;
878 else if (!strcasecmp(ev
, "STATUS_GENERAL"))
879 event_code
= EVENT_STATUS_GENERAL
;
880 else if (!strcasecmp(ev
, "STATUS_CLIENT"))
881 event_code
= EVENT_STATUS_CLIENT
;
882 else if (!strcasecmp(ev
, "STATUS_SERVER"))
883 event_code
= EVENT_STATUS_SERVER
;
884 else if (!strcasecmp(ev
, "GUARD"))
885 event_code
= EVENT_GUARD
;
886 else if (!strcasecmp(ev
, "GUARDS")) {
887 /* XXXX021 This check is here to tolerate the controllers that
888 * depended on the buggy spec in 0.1.2.5-alpha through 0.1.2.10-rc.
889 * Once those versions are obsolete, stop supporting this. */
890 log_warn(LD_CONTROL
, "Controller used obsolete 'GUARDS' event name; "
891 "use GUARD instead.");
892 event_code
= EVENT_GUARD
;
893 } else if (!strcasecmp(ev
, "STREAM_BW"))
894 event_code
= EVENT_STREAM_BANDWIDTH_USED
;
896 connection_printf_to_buf(conn
, "552 Unrecognized event \"%s\"\r\n",
898 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
899 smartlist_free(events
);
902 event_mask
|= (1 << event_code
);
904 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
905 smartlist_free(events
);
907 conn
->event_mask
= event_mask
;
909 conn
->use_extended_events
= 1;
911 control_update_global_event_mask();
912 send_control_done(conn
);
916 /** Decode the hashed, base64'd password stored in <b>hashed</b>. If
917 * <b>buf</b> is provided, store the hashed password in the first
918 * S2K_SPECIFIER_LEN+DIGEST_LEN bytes of <b>buf</b>. Return 0 on
919 * success, -1 on failure.
922 decode_hashed_password(char *buf
, const char *hashed
)
925 if (!strcmpstart(hashed
, "16:")) {
926 if (base16_decode(decoded
, sizeof(decoded
), hashed
+3, strlen(hashed
+3))<0
927 || strlen(hashed
+3) != (S2K_SPECIFIER_LEN
+DIGEST_LEN
)*2) {
931 if (base64_decode(decoded
, sizeof(decoded
), hashed
, strlen(hashed
))
932 != S2K_SPECIFIER_LEN
+DIGEST_LEN
) {
937 memcpy(buf
, decoded
, S2K_SPECIFIER_LEN
+DIGEST_LEN
);
941 /** Called when we get an AUTHENTICATE message. Check whether the
942 * authentication is valid, and if so, update the connection's state to
943 * OPEN. Reply with DONE or ERROR.
946 handle_control_authenticate(control_connection_t
*conn
, uint32_t len
,
949 int used_quoted_string
= 0;
950 or_options_t
*options
= get_options();
951 const char *errstr
= NULL
;
956 int bad_cookie
=0, bad_password
=0;
958 if (TOR_ISXDIGIT(body
[0])) {
960 while (TOR_ISXDIGIT(*cp
))
965 password
= tor_malloc(password_len
+ 1);
966 if (base16_decode(password
, password_len
+1, body
, i
)<0) {
967 connection_write_str_to_buf(
968 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
969 "password? If so, the standard requires that you put it in "
970 "double quotes.\r\n", conn
);
971 connection_mark_for_close(TO_CONN(conn
));
975 } else if (TOR_ISSPACE(body
[0])) {
976 password
= tor_strdup("");
979 if (!get_escaped_string(body
, len
, &password
, &password_len
)) {
980 connection_write_str_to_buf("551 Invalid quoted string. You need "
981 "to put the password in double quotes.\r\n", conn
);
982 connection_mark_for_close(TO_CONN(conn
));
985 used_quoted_string
= 1;
988 if (!options
->CookieAuthentication
&& !options
->HashedControlPassword
) {
989 /* if Tor doesn't demand any stronger authentication, then
990 * the controller can get in with anything. */
994 if (options
->CookieAuthentication
) {
995 int also_password
= options
->HashedControlPassword
!= NULL
;
996 if (password_len
!= AUTHENTICATION_COOKIE_LEN
) {
997 if (!also_password
) {
998 log_warn(LD_CONTROL
, "Got authentication cookie with wrong length "
999 "(%d)", (int)password_len
);
1000 errstr
= "Wrong length on authentication cookie.";
1004 } else if (memcmp(authentication_cookie
, password
, password_len
)) {
1005 if (!also_password
) {
1006 log_warn(LD_CONTROL
, "Got mismatched authentication cookie");
1007 errstr
= "Authentication cookie did not match expected value.";
1016 if (options
->HashedControlPassword
) {
1017 char expected
[S2K_SPECIFIER_LEN
+DIGEST_LEN
];
1018 char received
[DIGEST_LEN
];
1019 int also_cookie
= options
->CookieAuthentication
;
1020 if (decode_hashed_password(expected
, options
->HashedControlPassword
)<0) {
1022 log_warn(LD_CONTROL
,
1023 "Couldn't decode HashedControlPassword: invalid base16");
1024 errstr
="Couldn't decode HashedControlPassword value in configuration.";
1028 secret_to_key(received
,DIGEST_LEN
,password
,password_len
,expected
);
1029 if (!memcmp(expected
+S2K_SPECIFIER_LEN
, received
, DIGEST_LEN
))
1032 if (used_quoted_string
)
1033 errstr
= "Password did not match HashedControlPassword value from "
1036 errstr
= "Password did not match HashedControlPassword value from "
1037 "configuration. Maybe you tried a plain text password? "
1038 "If so, the standard requires that you put it in double quotes.";
1045 /** We only get here if both kinds of authentication failed. */
1046 tor_assert(bad_password
&& bad_cookie
);
1047 log_warn(LD_CONTROL
, "Bad password or authentication cookie on controller.");
1048 errstr
= "Password did not match HashedControlPassword *or* authentication "
1054 errstr
= "Unknown reason.";
1055 connection_printf_to_buf(conn
, "515 Authentication failed: %s\r\n",
1057 connection_mark_for_close(TO_CONN(conn
));
1060 log_info(LD_CONTROL
, "Authenticated control connection (%d)", conn
->_base
.s
);
1061 send_control_done(conn
);
1062 conn
->_base
.state
= CONTROL_CONN_STATE_OPEN
;
1067 /** Called when we get a SAVECONF command. Try to flush the current options to
1068 * disk, and report success or failure. */
1070 handle_control_saveconf(control_connection_t
*conn
, uint32_t len
,
1075 if (options_save_current()<0) {
1076 connection_write_str_to_buf(
1077 "551 Unable to write configuration to disk.\r\n", conn
);
1079 send_control_done(conn
);
1084 /** Called when we get a SIGNAL command. React to the provided signal, and
1085 * report success or failure. (If the signal results in a shutdown, success
1086 * may not be reported.) */
1088 handle_control_signal(control_connection_t
*conn
, uint32_t len
,
1097 while (body
[n
] && ! TOR_ISSPACE(body
[n
]))
1099 s
= tor_strndup(body
, n
);
1100 if (!strcasecmp(s
, "RELOAD") || !strcasecmp(s
, "HUP"))
1102 else if (!strcasecmp(s
, "SHUTDOWN") || !strcasecmp(s
, "INT"))
1104 else if (!strcasecmp(s
, "DUMP") || !strcasecmp(s
, "USR1"))
1106 else if (!strcasecmp(s
, "DEBUG") || !strcasecmp(s
, "USR2"))
1108 else if (!strcasecmp(s
, "HALT") || !strcasecmp(s
, "TERM"))
1110 else if (!strcasecmp(s
, "NEWNYM"))
1112 else if (!strcasecmp(s
, "CLEARDNSCACHE"))
1113 sig
= SIGCLEARDNSCACHE
;
1115 connection_printf_to_buf(conn
, "552 Unrecognized signal code \"%s\"\r\n",
1123 /* Send DONE first, in case the signal makes us shut down. */
1124 send_control_done(conn
);
1125 control_signal_act(sig
);
1129 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1130 * and report success or failrue. */
1132 handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
1140 (void) len
; /* body is nul-terminated, so it's safe to ignore the length. */
1142 lines
= smartlist_create();
1143 elts
= smartlist_create();
1144 reply
= smartlist_create();
1145 smartlist_split_string(lines
, body
, " ",
1146 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1147 SMARTLIST_FOREACH(lines
, char *, line
,
1150 smartlist_split_string(elts
, line
, "=", 0, 2);
1151 if (smartlist_len(elts
) == 2) {
1152 const char *from
= smartlist_get(elts
,0);
1153 const char *to
= smartlist_get(elts
,1);
1154 size_t anslen
= strlen(line
)+512;
1155 char *ans
= tor_malloc(anslen
);
1156 if (address_is_invalid_destination(to
, 1)) {
1157 tor_snprintf(ans
, anslen
,
1158 "512-syntax error: invalid address '%s'", to
);
1159 smartlist_add(reply
, ans
);
1160 log_warn(LD_CONTROL
,
1161 "Skipping invalid argument '%s' in MapAddress msg", to
);
1162 } else if (!strcmp(from
, ".") || !strcmp(from
, "0.0.0.0")) {
1163 const char *address
= addressmap_register_virtual_address(
1164 !strcmp(from
,".") ? RESOLVED_TYPE_HOSTNAME
: RESOLVED_TYPE_IPV4
,
1167 tor_snprintf(ans
, anslen
,
1168 "451-resource exhausted: skipping '%s'", line
);
1169 smartlist_add(reply
, ans
);
1170 log_warn(LD_CONTROL
,
1171 "Unable to allocate address for '%s' in MapAddress msg",
1174 tor_snprintf(ans
, anslen
, "250-%s=%s", address
, to
);
1175 smartlist_add(reply
, ans
);
1178 addressmap_register(from
, tor_strdup(to
), 1);
1179 tor_snprintf(ans
, anslen
, "250-%s", line
);
1180 smartlist_add(reply
, ans
);
1183 size_t anslen
= strlen(line
)+256;
1184 char *ans
= tor_malloc(anslen
);
1185 tor_snprintf(ans
, anslen
, "512-syntax error: mapping '%s' is "
1186 "not of expected form 'foo=bar'.", line
);
1187 smartlist_add(reply
, ans
);
1188 log_info(LD_CONTROL
, "Skipping MapAddress '%s': wrong "
1189 "number of items.", safe_str(line
));
1191 SMARTLIST_FOREACH(elts
, char *, cp
, tor_free(cp
));
1192 smartlist_clear(elts
);
1194 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
1195 smartlist_free(lines
);
1196 smartlist_free(elts
);
1198 if (smartlist_len(reply
)) {
1199 ((char*)smartlist_get(reply
,smartlist_len(reply
)-1))[3] = ' ';
1200 r
= smartlist_join_strings(reply
, "\r\n", 1, &sz
);
1201 connection_write_to_buf(r
, sz
, TO_CONN(conn
));
1204 const char *response
=
1205 "512 syntax error: not enough arguments to mapaddress.\r\n";
1206 connection_write_to_buf(response
, strlen(response
), TO_CONN(conn
));
1209 SMARTLIST_FOREACH(reply
, char *, cp
, tor_free(cp
));
1210 smartlist_free(reply
);
1214 /** Implementation helper for GETINFO: knows the answers for various
1215 * trivial-to-implement questions. */
1217 getinfo_helper_misc(control_connection_t
*conn
, const char *question
,
1221 if (!strcmp(question
, "version")) {
1222 *answer
= tor_strdup(get_version());
1223 } else if (!strcmp(question
, "config-file")) {
1224 *answer
= tor_strdup(get_torrc_fname());
1225 } else if (!strcmp(question
, "info/names")) {
1226 *answer
= list_getinfo_options();
1227 } else if (!strcmp(question
, "events/names")) {
1228 *answer
= tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
1229 "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
1230 "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
1232 } else if (!strcmp(question
, "features/names")) {
1233 *answer
= tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1234 } else if (!strcmp(question
, "address")) {
1236 if (router_pick_published_address(get_options(), &addr
) < 0)
1238 *answer
= tor_dup_addr(addr
);
1239 } else if (!strcmp(question
, "dir-usage")) {
1240 *answer
= directory_dump_request_log();
1241 } else if (!strcmp(question
, "fingerprint")) {
1242 routerinfo_t
*me
= router_get_my_routerinfo();
1245 *answer
= tor_malloc(HEX_DIGEST_LEN
+1);
1246 base16_encode(*answer
, HEX_DIGEST_LEN
+1, me
->cache_info
.identity_digest
,
1252 /** Awful hack: return a newly allocated string based on a routerinfo and
1253 * (possibly) an extrainfo, sticking the read-history and write-history from
1254 * <b>ei</b> into the resulting string. The thing you get back won't
1255 * necessarily have a valid signature.
1257 * New code should never use this; it's for backward compatibiliy.
1259 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1260 * not be NUL-terminated. */
1262 munge_extrainfo_into_routerinfo(const char *ri_body
, signed_descriptor_t
*ri
,
1263 signed_descriptor_t
*ei
)
1265 char *out
= NULL
, *outp
;
1267 const char *router_sig
;
1268 const char *ei_body
= signed_descriptor_get_body(ei
);
1269 size_t ri_len
= ri
->signed_descriptor_len
;
1270 size_t ei_len
= ei
->signed_descriptor_len
;
1274 outp
= out
= tor_malloc(ri_len
+ei_len
+1);
1275 if (!(router_sig
= tor_memstr(ri_body
, ri_len
, "\nrouter-signature")))
1278 memcpy(out
, ri_body
, router_sig
-ri_body
);
1279 outp
+= router_sig
-ri_body
;
1281 for (i
=0; i
< 2; ++i
) {
1282 const char *kwd
= i
?"\nwrite-history ":"\nread-history ";
1283 const char *cp
, *eol
;
1284 if (!(cp
= tor_memstr(ei_body
, ei_len
, kwd
)))
1287 eol
= memchr(cp
, '\n', ei_len
- (cp
-ei_body
));
1288 memcpy(outp
, cp
, eol
-cp
+1);
1291 memcpy(outp
, router_sig
, ri_len
- (router_sig
-ri_body
));
1293 tor_assert(outp
-out
< (int)(ri_len
+ei_len
+1));
1298 return tor_strndup(ri_body
, ri
->signed_descriptor_len
);
1301 /** Implementation helper for GETINFO: knows the answers for questions about
1302 * directory information. */
1304 getinfo_helper_dir(control_connection_t
*control_conn
,
1305 const char *question
, char **answer
)
1307 if (!strcmpstart(question
, "desc/id/")) {
1308 routerinfo_t
*ri
= router_get_by_hexdigest(question
+strlen("desc/id/"));
1310 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1312 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
1314 } else if (!strcmpstart(question
, "desc/name/")) {
1315 routerinfo_t
*ri
= router_get_by_nickname(question
+strlen("desc/name/"),1);
1317 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1319 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
1321 } else if (!strcmp(question
, "desc/all-recent")) {
1322 routerlist_t
*routerlist
= router_get_routerlist();
1323 smartlist_t
*sl
= smartlist_create();
1324 if (routerlist
&& routerlist
->routers
) {
1325 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
1327 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1330 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
1333 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
1334 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
1336 } else if (!strcmp(question
, "desc/all-recent-extrainfo-hack")) {
1337 /* XXXX Remove this once Torstat asks for extrainfos. */
1338 routerlist_t
*routerlist
= router_get_routerlist();
1339 smartlist_t
*sl
= smartlist_create();
1340 if (routerlist
&& routerlist
->routers
) {
1341 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
1343 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1344 signed_descriptor_t
*ei
= extrainfo_get_by_descriptor_digest(
1345 ri
->cache_info
.extra_info_digest
);
1347 smartlist_add(sl
, munge_extrainfo_into_routerinfo(body
,
1348 &ri
->cache_info
, ei
));
1351 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
1355 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
1356 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
1358 } else if (!strcmpstart(question
, "dir/server/")) {
1359 size_t answer_len
= 0, url_len
= strlen(question
)+2;
1360 char *url
= tor_malloc(url_len
);
1361 smartlist_t
*descs
= smartlist_create();
1365 tor_snprintf(url
, url_len
, "/tor/%s", question
+4);
1366 res
= dirserv_get_routerdescs(descs
, url
, &msg
);
1368 log_warn(LD_CONTROL
, "getinfo '%s': %s", question
, msg
);
1371 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
1372 answer_len
+= sd
->signed_descriptor_len
);
1373 cp
= *answer
= tor_malloc(answer_len
+1);
1374 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
1376 memcpy(cp
, signed_descriptor_get_body(sd
),
1377 sd
->signed_descriptor_len
);
1378 cp
+= sd
->signed_descriptor_len
;
1382 smartlist_free(descs
);
1383 } else if (!strcmpstart(question
, "dir/status/")) {
1384 if (dirserver_mode(get_options())) {
1387 smartlist_t
*status_list
= smartlist_create();
1388 dirserv_get_networkstatus_v2(status_list
,
1389 question
+strlen("dir/status/"));
1390 SMARTLIST_FOREACH(status_list
, cached_dir_t
*, d
, len
+= d
->dir_len
);
1391 cp
= *answer
= tor_malloc(len
+1);
1392 SMARTLIST_FOREACH(status_list
, cached_dir_t
*, d
, {
1393 memcpy(cp
, d
->dir
, d
->dir_len
);
1397 smartlist_free(status_list
);
1399 smartlist_t
*fp_list
= smartlist_create();
1400 smartlist_t
*status_list
= smartlist_create();
1401 size_t fn_len
= strlen(get_options()->DataDirectory
)+HEX_DIGEST_LEN
+32;
1402 char *fn
= tor_malloc(fn_len
+1);
1403 char hex_id
[HEX_DIGEST_LEN
+1];
1404 dirserv_get_networkstatus_v2_fingerprints(
1405 fp_list
, question
+strlen("dir/status/"));
1406 SMARTLIST_FOREACH(fp_list
, const char *, fp
, {
1408 base16_encode(hex_id
, sizeof(hex_id
), fp
, DIGEST_LEN
);
1409 tor_snprintf(fn
, fn_len
, "%s/cached-status/%s",
1410 get_options()->DataDirectory
, hex_id
);
1411 s
= read_file_to_str(fn
, 0, NULL
);
1413 smartlist_add(status_list
, s
);
1415 SMARTLIST_FOREACH(fp_list
, char *, fp
, tor_free(fp
));
1416 smartlist_free(fp_list
);
1417 *answer
= smartlist_join_strings(status_list
, "", 0, NULL
);
1418 SMARTLIST_FOREACH(status_list
, char *, s
, tor_free(s
));
1419 smartlist_free(status_list
);
1421 } else if (!strcmp(question
, "network-status")) {
1422 routerlist_t
*routerlist
= router_get_routerlist();
1423 int verbose
= control_conn
->use_long_names
;
1424 if (!routerlist
|| !routerlist
->routers
||
1425 list_server_status(routerlist
->routers
, answer
, verbose
? 2 : 1) < 0) {
1428 } else if (!strcmpstart(question
, "extra-info/digest/")) {
1429 question
+= strlen("extra-info/digest/");
1430 if (strlen(question
) == HEX_DIGEST_LEN
) {
1432 signed_descriptor_t
*sd
;
1433 base16_decode(d
, sizeof(d
), question
, strlen(question
));
1434 sd
= extrainfo_get_by_descriptor_digest(d
);
1436 const char *body
= signed_descriptor_get_body(sd
);
1438 *answer
= tor_strndup(body
, sd
->signed_descriptor_len
);
1446 /** Implementation helper for GETINFO: knows how to generate summaries of the
1447 * current states of things we send events about. */
1449 getinfo_helper_events(control_connection_t
*control_conn
,
1450 const char *question
, char **answer
)
1452 if (!strcmp(question
, "circuit-status")) {
1454 smartlist_t
*status
= smartlist_create();
1455 for (circ
= _circuit_get_global_list(); circ
; circ
= circ
->next
) {
1459 if (! CIRCUIT_IS_ORIGIN(circ
) || circ
->marked_for_close
)
1461 if (control_conn
->use_long_names
)
1462 path
= circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ
));
1464 path
= circuit_list_path(TO_ORIGIN_CIRCUIT(circ
),0);
1465 if (circ
->state
== CIRCUIT_STATE_OPEN
)
1467 else if (strlen(path
))
1472 slen
= strlen(path
)+strlen(state
)+20;
1473 s
= tor_malloc(slen
+1);
1474 tor_snprintf(s
, slen
, "%lu %s%s%s",
1475 (unsigned long)TO_ORIGIN_CIRCUIT(circ
)->global_identifier
,
1476 state
, *path
? " " : "", path
);
1477 smartlist_add(status
, s
);
1480 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1481 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1482 smartlist_free(status
);
1483 } else if (!strcmp(question
, "stream-status")) {
1484 smartlist_t
*conns
= get_connection_array();
1485 smartlist_t
*status
= smartlist_create();
1487 SMARTLIST_FOREACH(conns
, connection_t
*, base_conn
,
1490 edge_connection_t
*conn
;
1494 origin_circuit_t
*origin_circ
= NULL
;
1495 if (base_conn
->type
!= CONN_TYPE_AP
||
1496 base_conn
->marked_for_close
||
1497 base_conn
->state
== AP_CONN_STATE_SOCKS_WAIT
||
1498 base_conn
->state
== AP_CONN_STATE_NATD_WAIT
)
1500 conn
= TO_EDGE_CONN(base_conn
);
1501 switch (conn
->_base
.state
)
1503 case AP_CONN_STATE_CONTROLLER_WAIT
:
1504 case AP_CONN_STATE_CIRCUIT_WAIT
:
1505 if (conn
->socks_request
&&
1506 SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
))
1507 state
= "NEWRESOLVE";
1511 case AP_CONN_STATE_RENDDESC_WAIT
:
1512 case AP_CONN_STATE_CONNECT_WAIT
:
1513 state
= "SENTCONNECT"; break;
1514 case AP_CONN_STATE_RESOLVE_WAIT
:
1515 state
= "SENTRESOLVE"; break;
1516 case AP_CONN_STATE_OPEN
:
1517 state
= "SUCCEEDED"; break;
1519 log_warn(LD_BUG
, "Asked for stream in unknown state %d",
1523 circ
= circuit_get_by_edge_conn(conn
);
1524 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
1525 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
1526 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
1527 slen
= strlen(buf
)+strlen(state
)+32;
1528 s
= tor_malloc(slen
+1);
1529 tor_snprintf(s
, slen
, "%lu %s %lu %s",
1530 (unsigned long) conn
->global_identifier
,state
,
1532 (unsigned long)origin_circ
->global_identifier
: 0ul,
1534 smartlist_add(status
, s
);
1536 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1537 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1538 smartlist_free(status
);
1539 } else if (!strcmp(question
, "orconn-status")) {
1540 smartlist_t
*conns
= get_connection_array();
1541 smartlist_t
*status
= smartlist_create();
1542 SMARTLIST_FOREACH(conns
, connection_t
*, base_conn
,
1548 or_connection_t
*conn
;
1549 if (base_conn
->type
!= CONN_TYPE_OR
|| base_conn
->marked_for_close
)
1551 conn
= TO_OR_CONN(base_conn
);
1552 if (conn
->_base
.state
== OR_CONN_STATE_OPEN
)
1553 state
= "CONNECTED";
1554 else if (conn
->nickname
)
1558 orconn_target_get_name(control_conn
->use_long_names
, name
, sizeof(name
),
1560 slen
= strlen(name
)+strlen(state
)+2;
1561 s
= tor_malloc(slen
+1);
1562 tor_snprintf(s
, slen
, "%s %s", name
, state
);
1563 smartlist_add(status
, s
);
1565 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1566 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1567 smartlist_free(status
);
1568 } else if (!strcmpstart(question
, "addr-mappings/") ||
1569 !strcmpstart(question
, "address-mappings/")) {
1570 /* XXXX020 Warn about deprecated addr-mappings variant? Or wait for
1572 time_t min_e
, max_e
;
1573 smartlist_t
*mappings
;
1574 int want_expiry
= !strcmpstart(question
, "address-mappings/");
1575 question
+= strlen(want_expiry
? "address-mappings/"
1576 : "addr-mappings/");
1577 if (!strcmp(question
, "all")) {
1578 min_e
= 0; max_e
= TIME_MAX
;
1579 } else if (!strcmp(question
, "cache")) {
1580 min_e
= 2; max_e
= TIME_MAX
;
1581 } else if (!strcmp(question
, "config")) {
1582 min_e
= 0; max_e
= 0;
1583 } else if (!strcmp(question
, "control")) {
1584 min_e
= 1; max_e
= 1;
1588 mappings
= smartlist_create();
1589 addressmap_get_mappings(mappings
, min_e
, max_e
, want_expiry
);
1590 *answer
= smartlist_join_strings(mappings
, "\r\n", 0, NULL
);
1591 SMARTLIST_FOREACH(mappings
, char *, cp
, tor_free(cp
));
1592 smartlist_free(mappings
);
1593 } else if (!strcmpstart(question
, "status/")) {
1594 /* Note that status/ is not a catch-all for events; there's only supposed
1595 * to be a status GETINFO if there's a corresponding STATUS event. */
1596 if (!strcmp(question
, "status/circuit-established")) {
1597 *answer
= tor_strdup(has_completed_circuit
? "1" : "0");
1598 } else if (!strcmp(question
, "status/enough-dir-info")) {
1599 *answer
= tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
1600 } else if (!strcmp(question
, "status/good-server-descriptor")) {
1601 *answer
= tor_strdup(directories_have_accepted_server_descriptor()
1603 } else if (!strcmp(question
, "status/reachability-succeeded/or")) {
1604 *answer
= tor_strdup(check_whether_orport_reachable() ? "1" : "0");
1605 } else if (!strcmp(question
, "status/reachability-succeeded/dir")) {
1606 *answer
= tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
1607 } else if (!strcmp(question
, "status/reachability-succeeded")) {
1608 *answer
= tor_malloc(16);
1609 tor_snprintf(*answer
, 16, "OR=%d DIR=%d",
1610 check_whether_orport_reachable() ? 1 : 0,
1611 check_whether_dirport_reachable() ? 1 : 0);
1612 } else if (!strcmpstart(question
, "status/version/")) {
1613 combined_version_status_t st
;
1614 int is_server
= server_mode(get_options());
1616 recommended
= compute_recommended_versions(time(NULL
),
1617 !is_server
, VERSION
, &st
);
1618 if (!strcmp(question
, "status/version/recommended")) {
1619 *answer
= recommended
;
1622 tor_free(recommended
);
1623 if (!strcmp(question
, "status/version/current")) {
1624 switch (st
.consensus
)
1626 case VS_RECOMMENDED
: *answer
= tor_strdup("recommended"); break;
1627 case VS_OLD
: *answer
= tor_strdup("obsolete"); break;
1628 case VS_NEW
: *answer
= tor_strdup("new"); break;
1629 case VS_NEW_IN_SERIES
: *answer
= tor_strdup("new in series"); break;
1630 case VS_UNRECOMMENDED
: *answer
= tor_strdup("unrecommended"); break;
1631 default: tor_fragile_assert();
1633 } else if (!strcmp(question
, "status/version/num-versioning")) {
1635 tor_snprintf(s
, sizeof(s
), "%d", st
.n_versioning
);
1636 *answer
= tor_strdup(s
);
1637 } else if (!strcmp(question
, "status/version/num-concurring")) {
1639 tor_snprintf(s
, sizeof(s
), "%d", st
.n_concurring
);
1640 *answer
= tor_strdup(s
);
1649 /** Callback function for GETINFO: on a given control connection, try to
1650 * answer the question <b>q</b> and store the newly-allocated answer in
1651 * *<b>a</b>. If there's no answer, or an error occurs, just don't set
1652 * <b>a</b>. Return 0.
1654 typedef int (*getinfo_helper_t
)(control_connection_t
*,
1655 const char *q
, char **a
);
1657 /** A single item for the GETINFO question-to-answer-function table. */
1658 typedef struct getinfo_item_t
{
1659 const char *varname
; /**< The value (or prefix) of the question. */
1660 getinfo_helper_t fn
; /**< The function that knows the answer: NULL if
1661 * this entry is documentation-only. */
1662 const char *desc
; /**< Description of the variable. */
1663 int is_prefix
; /** Must varname match exactly, or must it be a prefix? */
1666 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
1667 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
1668 #define DOC(name, desc) { name, NULL, desc, 0 }
1670 /** Table mapping questions accepted by GETINFO to the functions that know how
1671 * to answer them. */
1672 static const getinfo_item_t getinfo_items
[] = {
1673 ITEM("version", misc
, "The current version of Tor."),
1674 ITEM("config-file", misc
, "Current location of the \"torrc\" file."),
1675 ITEM("accounting/bytes", accounting
,
1676 "Number of bytes read/written so far in the accounting interval."),
1677 ITEM("accounting/bytes-left", accounting
,
1678 "Number of bytes left to write/read so far in the accounting interval."),
1679 ITEM("accounting/enabled", accounting
, "Is accounting currently enabled?"),
1680 ITEM("accounting/hibernating", accounting
, "Are we hibernating or awake?"),
1681 ITEM("accounting/interval-start", accounting
,
1682 "Time when the accounting period starts."),
1683 ITEM("accounting/interval-end", accounting
,
1684 "Time when the accounting period ends."),
1685 ITEM("accounting/interval-wake", accounting
,
1686 "Time to wake up in this accounting period."),
1687 ITEM("helper-nodes", entry_guards
, NULL
), /* deprecated */
1688 ITEM("entry-guards", entry_guards
,
1689 "Which nodes are we using as entry guards?"),
1690 ITEM("fingerprint", misc
, NULL
),
1691 PREFIX("config/", config
, "Current configuration values."),
1693 "List of configuration options, types, and documentation."),
1694 ITEM("info/names", misc
,
1695 "List of GETINFO options, types, and documentation."),
1696 ITEM("events/names", misc
,
1697 "Events that the controller can ask for with SETEVENTS."),
1698 ITEM("features/names", misc
, "What arguments can USEFEATURE take?"),
1699 PREFIX("desc/id/", dir
, "Router descriptors by ID."),
1700 PREFIX("desc/name/", dir
, "Router descriptors by nickname."),
1701 ITEM("desc/all-recent", dir
,
1702 "All non-expired, non-superseded router descriptors."),
1703 ITEM("desc/all-recent-extrainfo-hack", dir
, NULL
), /* Hack. */
1704 PREFIX("extra-info/digest/", dir
, "Extra-info documents by digest."),
1705 ITEM("ns/all", networkstatus
,
1706 "Brief summary of router status (v2 directory format)"),
1707 PREFIX("ns/id/", networkstatus
,
1708 "Brief summary of router status by ID (v2 directory format)."),
1709 PREFIX("ns/name/", networkstatus
,
1710 "Brief summary of router status by nickname (v2 directory format)."),
1712 PREFIX("unregistered-servers-", dirserv_unregistered
, NULL
),
1713 ITEM("network-status", dir
,
1714 "Brief summary of router status (v1 directory format)"),
1715 ITEM("circuit-status", events
, "List of current circuits originating here."),
1716 ITEM("stream-status", events
,"List of current streams."),
1717 ITEM("orconn-status", events
, "A list of current OR connections."),
1718 PREFIX("address-mappings/", events
, NULL
),
1719 DOC("address-mappings/all", "Current address mappings."),
1720 DOC("address-mappings/cache", "Current cached DNS replies."),
1721 DOC("address-mappings/config",
1722 "Current address mappings from configuration."),
1723 DOC("address-mappings/control", "Current address mappings from controller."),
1724 PREFIX("addr-mappings/", events
, NULL
),
1725 DOC("addr-mappings/all", "Current address mappings without expiry times."),
1726 DOC("addr-mappings/cache",
1727 "Current cached DNS replies without expiry times."),
1728 DOC("addr-mappings/config",
1729 "Current address mappings from configuration without expiry times."),
1730 DOC("addr-mappings/control",
1731 "Current address mappings from controller without expiry times."),
1732 PREFIX("status/", events
, NULL
),
1733 DOC("status/circuit-established",
1734 "Whether we think client functionality is working."),
1735 DOC("status/enough-dir-info",
1736 "Whether we have enough up-to-date directory information to build "
1738 DOC("status/version/recommended", "List of currently recommended versions."),
1739 DOC("status/version/current", "Status of the current version."),
1740 DOC("status/version/num-versioning", "Number of versioning authorities."),
1741 DOC("status/version/num-concurring",
1742 "Number of versioning authorities agreeing on the status of the "
1744 ITEM("address", misc
, "IP address of this Tor host, if we can guess it."),
1745 ITEM("dir-usage", misc
, "Breakdown of bytes transferred over DirPort."),
1746 PREFIX("dir/server/", dir
,"Router descriptors as retrieved from a DirPort."),
1747 PREFIX("dir/status/", dir
,"Networkstatus docs as retrieved from a DirPort."),
1748 PREFIX("exit-policy/default", policies
,
1749 "The default value appended to the configured exit policy."),
1751 { NULL
, NULL
, NULL
, 0 }
1754 /** Allocate and return a list of recognized GETINFO options. */
1756 list_getinfo_options(void)
1760 smartlist_t
*lines
= smartlist_create();
1762 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
1763 if (!getinfo_items
[i
].desc
)
1766 tor_snprintf(buf
, sizeof(buf
), "%s%s -- %s\n",
1767 getinfo_items
[i
].varname
,
1768 getinfo_items
[i
].is_prefix
? "*" : "",
1769 getinfo_items
[i
].desc
);
1770 smartlist_add(lines
, tor_strdup(buf
));
1772 smartlist_sort_strings(lines
);
1774 ans
= smartlist_join_strings(lines
, "", 0, NULL
);
1775 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
1776 smartlist_free(lines
);
1781 /** Lookup the 'getinfo' entry <b>question</b>, and return
1782 * the answer in <b>*answer</b> (or NULL if key not recognized).
1783 * Return 0 if success or unrecognized, or -1 if recognized but
1784 * internal error. */
1786 handle_getinfo_helper(control_connection_t
*control_conn
,
1787 const char *question
, char **answer
)
1790 *answer
= NULL
; /* unrecognized key by default */
1792 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
1794 if (getinfo_items
[i
].is_prefix
)
1795 match
= !strcmpstart(question
, getinfo_items
[i
].varname
);
1797 match
= !strcmp(question
, getinfo_items
[i
].varname
);
1799 tor_assert(getinfo_items
[i
].fn
);
1800 return getinfo_items
[i
].fn(control_conn
, question
, answer
);
1804 return 0; /* unrecognized */
1807 /** Called when we receive a GETINFO command. Try to fetch all requested
1808 * information, and reply with information or error message. */
1810 handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
1813 smartlist_t
*questions
= NULL
;
1814 smartlist_t
*answers
= NULL
;
1815 smartlist_t
*unrecognized
= NULL
;
1816 char *msg
= NULL
, *ans
= NULL
;
1818 (void) len
; /* body is nul-terminated, so it's safe to ignore the length. */
1820 questions
= smartlist_create();
1821 smartlist_split_string(questions
, body
, " ",
1822 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1823 answers
= smartlist_create();
1824 unrecognized
= smartlist_create();
1825 SMARTLIST_FOREACH(questions
, const char *, q
,
1827 if (handle_getinfo_helper(conn
, q
, &ans
) < 0) {
1828 connection_write_str_to_buf("551 Internal error\r\n", conn
);
1832 smartlist_add(unrecognized
, (char*)q
);
1834 smartlist_add(answers
, tor_strdup(q
));
1835 smartlist_add(answers
, ans
);
1838 if (smartlist_len(unrecognized
)) {
1839 for (i
=0; i
< smartlist_len(unrecognized
)-1; ++i
)
1840 connection_printf_to_buf(conn
,
1841 "552-Unrecognized key \"%s\"\r\n",
1842 (char*)smartlist_get(unrecognized
, i
));
1843 connection_printf_to_buf(conn
,
1844 "552 Unrecognized key \"%s\"\r\n",
1845 (char*)smartlist_get(unrecognized
, i
));
1849 for (i
= 0; i
< smartlist_len(answers
); i
+= 2) {
1850 char *k
= smartlist_get(answers
, i
);
1851 char *v
= smartlist_get(answers
, i
+1);
1852 if (!strchr(v
, '\n') && !strchr(v
, '\r')) {
1853 connection_printf_to_buf(conn
, "250-%s=", k
);
1854 connection_write_str_to_buf(v
, conn
);
1855 connection_write_str_to_buf("\r\n", conn
);
1859 esc_len
= write_escaped_data(v
, strlen(v
), &esc
);
1860 connection_printf_to_buf(conn
, "250+%s=\r\n", k
);
1861 connection_write_to_buf(esc
, esc_len
, TO_CONN(conn
));
1865 connection_write_str_to_buf("250 OK\r\n", conn
);
1869 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
1870 smartlist_free(answers
);
1873 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
1874 smartlist_free(questions
);
1876 smartlist_free(unrecognized
);
1882 /** If *<b>string</b> contains a recognized purpose (for
1883 * circuits if <b>for_circuits</b> is 1, else for routers),
1884 * possibly prefaced with the string "purpose=", then assign it
1885 * and return 0. Otherwise return -1.
1887 * If it's prefaced with "purpose=", then set *<b>string</b> to
1888 * the remainder of the string. */
1890 get_purpose(char **string
, int for_circuits
, uint8_t *purpose
)
1892 if (!strcmpstart(*string
, "purpose="))
1893 *string
+= strlen("purpose=");
1895 if (!for_circuits
) {
1896 int r
= router_purpose_from_string(*string
);
1897 if (r
== ROUTER_PURPOSE_UNKNOWN
)
1903 if (!strcmp(*string
, "general"))
1904 *purpose
= CIRCUIT_PURPOSE_C_GENERAL
;
1905 else if (!strcmp(*string
, "controller"))
1906 *purpose
= CIRCUIT_PURPOSE_CONTROLLER
;
1907 else { /* not a recognized purpose */
1913 /** Return a newly allocated smartlist containing the arguments to the command
1914 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
1915 * or if <b>max_args</b> is nonnegative and there are more than
1916 * <b>max_args</b> arguments, send a 512 error to the controller, using
1917 * <b>command</b> as the command name in the error message. */
1918 static smartlist_t
*
1919 getargs_helper(const char *command
, control_connection_t
*conn
,
1920 const char *body
, int min_args
, int max_args
)
1922 smartlist_t
*args
= smartlist_create();
1923 smartlist_split_string(args
, body
, " ",
1924 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1925 if (smartlist_len(args
) < min_args
) {
1926 connection_printf_to_buf(conn
, "512 Missing argument to %s\r\n",command
);
1928 } else if (max_args
>= 0 && smartlist_len(args
) > max_args
) {
1929 connection_printf_to_buf(conn
, "512 Too many arguments to %s\r\n",command
);
1934 SMARTLIST_FOREACH(args
, char *, s
, tor_free(s
));
1935 smartlist_free(args
);
1939 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
1940 * circuit, and report success or failure. */
1942 handle_control_extendcircuit(control_connection_t
*conn
, uint32_t len
,
1945 smartlist_t
*router_nicknames
=NULL
, *routers
=NULL
;
1946 origin_circuit_t
*circ
= NULL
;
1948 uint8_t intended_purpose
= CIRCUIT_PURPOSE_C_GENERAL
;
1952 router_nicknames
= smartlist_create();
1954 args
= getargs_helper("EXTENDCIRCUIT", conn
, body
, 2, -1);
1958 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,0));
1959 if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
,0)))) {
1960 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
1961 (char*)smartlist_get(args
, 0));
1963 smartlist_split_string(router_nicknames
, smartlist_get(args
,1), ",", 0, 0);
1965 if (zero_circ
&& smartlist_len(args
)>2) {
1966 char *purp
= smartlist_get(args
,2);
1967 if (get_purpose(&purp
, 1, &intended_purpose
) < 0) {
1968 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
1969 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
1970 smartlist_free(args
);
1974 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
1975 smartlist_free(args
);
1976 if (!zero_circ
&& !circ
) {
1980 routers
= smartlist_create();
1981 SMARTLIST_FOREACH(router_nicknames
, const char *, n
,
1983 routerinfo_t
*r
= router_get_by_nickname(n
, 1);
1985 connection_printf_to_buf(conn
, "552 No such router \"%s\"\r\n", n
);
1988 smartlist_add(routers
, r
);
1990 if (!smartlist_len(routers
)) {
1991 connection_write_str_to_buf("512 No router names provided\r\n", conn
);
1996 /* start a new circuit */
1997 circ
= origin_circuit_init(intended_purpose
, 0, 0, 0, 0);
2000 /* now circ refers to something that is ready to be extended */
2001 SMARTLIST_FOREACH(routers
, routerinfo_t
*, r
,
2003 extend_info_t
*info
= extend_info_from_router(r
);
2004 circuit_append_new_exit(circ
, info
);
2005 extend_info_free(info
);
2008 /* now that we've populated the cpath, start extending */
2011 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
2012 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
2013 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
2017 if (circ
->_base
.state
== CIRCUIT_STATE_OPEN
) {
2019 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
2020 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
2021 log_info(LD_CONTROL
,
2022 "send_next_onion_skin failed; circuit marked for closing.");
2023 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
2024 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn
);
2030 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
2031 (unsigned long)circ
->global_identifier
);
2032 if (zero_circ
) /* send a 'launched' event, for completeness */
2033 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
2035 SMARTLIST_FOREACH(router_nicknames
, char *, n
, tor_free(n
));
2036 smartlist_free(router_nicknames
);
2038 smartlist_free(routers
);
2042 /** Called when we get a SETCIRCUITPURPOSE (if <b>for_circuits</b>
2043 * is 1) or SETROUTERPURPOSE message. If we can find
2044 * the circuit/router and it's a valid purpose, change it. */
2046 handle_control_setpurpose(control_connection_t
*conn
, int for_circuits
,
2047 uint32_t len
, const char *body
)
2049 /* XXXX020 this should maybe be two functions; almost no code is acutally
2051 origin_circuit_t
*circ
= NULL
;
2052 routerinfo_t
*ri
= NULL
;
2053 uint8_t new_purpose
;
2055 const char *command
=
2056 for_circuits
? "SETCIRCUITPURPOSE" : "SETROUTERPURPOSE";
2057 (void) len
; /* body is nul-terminated, so it's safe to ignore the length. */
2059 args
= getargs_helper(command
, conn
, body
, 2, -1);
2064 if (!(circ
= get_circ(smartlist_get(args
,0)))) {
2065 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2066 (char*)smartlist_get(args
, 0));
2070 if (!(ri
= router_get_by_nickname(smartlist_get(args
,0), 0))) {
2071 connection_printf_to_buf(conn
, "552 Unknown router \"%s\"\r\n",
2072 (char*)smartlist_get(args
, 0));
2078 char *purp
= smartlist_get(args
,1);
2079 if (get_purpose(&purp
, for_circuits
, &new_purpose
) < 0) {
2080 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
2086 circ
->_base
.purpose
= new_purpose
;
2088 ri
->purpose
= new_purpose
;
2089 connection_write_str_to_buf("250 OK\r\n", conn
);
2093 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2094 smartlist_free(args
);
2099 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
2100 * stream, and report success or failure. */
2102 handle_control_attachstream(control_connection_t
*conn
, uint32_t len
,
2105 edge_connection_t
*ap_conn
= NULL
;
2106 origin_circuit_t
*circ
= NULL
;
2109 crypt_path_t
*cpath
=NULL
;
2110 int hop
=0, hop_line_ok
=1;
2113 args
= getargs_helper("ATTACHSTREAM", conn
, body
, 2, -1);
2117 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,1));
2119 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))) {
2120 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2121 (char*)smartlist_get(args
, 0));
2122 } else if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
, 1)))) {
2123 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2124 (char*)smartlist_get(args
, 1));
2125 } else if (circ
&& smartlist_len(args
) > 2) {
2126 char *hopstring
= smartlist_get(args
, 2);
2127 if (!strcasecmpstart(hopstring
, "HOP=")) {
2128 hopstring
+= strlen("HOP=");
2129 hop
= tor_parse_ulong(hopstring
, 10, 0, ULONG_MAX
,
2130 &hop_line_ok
, NULL
);
2131 if (!hop_line_ok
) { /* broken hop line */
2132 connection_printf_to_buf(conn
, "552 Bad value hop=%s\r\n", hopstring
);
2136 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2137 smartlist_free(args
);
2138 if (!ap_conn
|| (!zero_circ
&& !circ
) || !hop_line_ok
)
2141 if (ap_conn
->_base
.state
!= AP_CONN_STATE_CONTROLLER_WAIT
&&
2142 ap_conn
->_base
.state
!= AP_CONN_STATE_CONNECT_WAIT
&&
2143 ap_conn
->_base
.state
!= AP_CONN_STATE_RESOLVE_WAIT
) {
2144 connection_write_str_to_buf(
2145 "555 Connection is not managed by controller.\r\n",
2150 /* Do we need to detach it first? */
2151 if (ap_conn
->_base
.state
!= AP_CONN_STATE_CONTROLLER_WAIT
) {
2152 circuit_t
*tmpcirc
= circuit_get_by_edge_conn(ap_conn
);
2153 connection_edge_end(ap_conn
, END_STREAM_REASON_TIMEOUT
);
2154 /* Un-mark it as ending, since we're going to reuse it. */
2155 ap_conn
->_base
.edge_has_sent_end
= 0;
2156 ap_conn
->end_reason
= 0;
2158 circuit_detach_stream(tmpcirc
,ap_conn
);
2159 ap_conn
->_base
.state
= AP_CONN_STATE_CONTROLLER_WAIT
;
2162 if (circ
&& (circ
->_base
.state
!= CIRCUIT_STATE_OPEN
)) {
2163 connection_write_str_to_buf(
2164 "551 Can't attach stream to non-open origin circuit\r\n",
2168 if (circ
&& (circuit_get_cpath_len(circ
)<2 || hop
==1)) {
2169 connection_write_str_to_buf(
2170 "551 Can't attach stream to one-hop circuit.\r\n", conn
);
2173 if (circ
&& hop
>0) {
2174 /* find this hop in the circuit, and set cpath */
2175 cpath
= circuit_get_cpath_hop(circ
, hop
);
2177 connection_printf_to_buf(conn
,
2178 "551 Circuit doesn't have %d hops.\r\n", hop
);
2182 if (connection_ap_handshake_rewrite_and_attach(ap_conn
, circ
, cpath
) < 0) {
2183 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn
);
2186 send_control_done(conn
);
2190 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
2191 * descriptor, and report success or failure. */
2193 handle_control_postdescriptor(control_connection_t
*conn
, uint32_t len
,
2197 const char *msg
=NULL
;
2198 uint8_t purpose
= ROUTER_PURPOSE_GENERAL
;
2200 char *cp
= memchr(body
, '\n', len
);
2201 smartlist_t
*args
= smartlist_create();
2205 smartlist_split_string(args
, body
, " ",
2206 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2207 if (smartlist_len(args
)) {
2208 char *purp
= smartlist_get(args
,0);
2209 if (get_purpose(&purp
, 0, &purpose
) < 0) {
2210 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n",
2212 SMARTLIST_FOREACH(args
, char *, arg
, tor_free(arg
));
2213 smartlist_free(args
);
2217 SMARTLIST_FOREACH(args
, char *, arg
, tor_free(arg
));
2218 smartlist_free(args
);
2219 read_escaped_data(cp
, len
-(cp
-body
), &desc
);
2221 switch (router_load_single_router(desc
, purpose
, &msg
)) {
2223 if (!msg
) msg
= "Could not parse descriptor";
2224 connection_printf_to_buf(conn
, "554 %s\r\n", msg
);
2227 if (!msg
) msg
= "Descriptor not added";
2228 connection_printf_to_buf(conn
, "251 %s\r\n",msg
);
2231 send_control_done(conn
);
2239 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
2240 * address of the named AP stream, and report success or failure. */
2242 handle_control_redirectstream(control_connection_t
*conn
, uint32_t len
,
2245 edge_connection_t
*ap_conn
= NULL
;
2246 char *new_addr
= NULL
;
2247 uint16_t new_port
= 0;
2251 args
= getargs_helper("REDIRECTSTREAM", conn
, body
, 2, -1);
2255 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))
2256 || !ap_conn
->socks_request
) {
2257 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2258 (char*)smartlist_get(args
, 0));
2261 if (smartlist_len(args
) > 2) { /* they included a port too */
2262 new_port
= (uint16_t) tor_parse_ulong(smartlist_get(args
, 2),
2263 10, 1, 65535, &ok
, NULL
);
2266 connection_printf_to_buf(conn
, "512 Cannot parse port \"%s\"\r\n",
2267 (char*)smartlist_get(args
, 2));
2269 new_addr
= tor_strdup(smartlist_get(args
, 1));
2273 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2274 smartlist_free(args
);
2278 strlcpy(ap_conn
->socks_request
->address
, new_addr
,
2279 sizeof(ap_conn
->socks_request
->address
));
2281 ap_conn
->socks_request
->port
= new_port
;
2283 send_control_done(conn
);
2287 /** Called when we get a CLOSESTREAM command; try to close the named stream
2288 * and report success or failure. */
2290 handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
2293 edge_connection_t
*ap_conn
=NULL
;
2299 args
= getargs_helper("CLOSESTREAM", conn
, body
, 2, -1);
2303 else if (!(ap_conn
= get_stream(smartlist_get(args
, 0))))
2304 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2305 (char*)smartlist_get(args
, 0));
2307 reason
= (uint8_t) tor_parse_ulong(smartlist_get(args
,1), 10, 0, 255,
2310 connection_printf_to_buf(conn
, "552 Unrecognized reason \"%s\"\r\n",
2311 (char*)smartlist_get(args
, 1));
2315 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2316 smartlist_free(args
);
2320 connection_mark_unattached_ap(ap_conn
, reason
);
2321 send_control_done(conn
);
2325 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
2326 * and report success or failure. */
2328 handle_control_closecircuit(control_connection_t
*conn
, uint32_t len
,
2331 origin_circuit_t
*circ
= NULL
;
2336 args
= getargs_helper("CLOSECIRCUIT", conn
, body
, 1, -1);
2340 if (!(circ
=get_circ(smartlist_get(args
, 0))))
2341 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2342 (char*)smartlist_get(args
, 0));
2345 for (i
=1; i
< smartlist_len(args
); ++i
) {
2346 if (!strcasecmp(smartlist_get(args
, i
), "IfUnused"))
2349 log_info(LD_CONTROL
, "Skipping unknown option %s",
2350 (char*)smartlist_get(args
,i
));
2353 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2354 smartlist_free(args
);
2358 if (!safe
|| !circ
->p_streams
) {
2359 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_REQUESTED
);
2362 send_control_done(conn
);
2366 /** Called when we get a RESOLVE command: start trying to resolve
2367 * the listed addresses. */
2369 handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
2374 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
2376 if (!(conn
->event_mask
& (1L<<EVENT_ADDRMAP
))) {
2377 log_warn(LD_CONTROL
, "Controller asked us to resolve an address, but "
2378 "isn't listening for ADDRMAP events. It probably won't see "
2381 args
= smartlist_create();
2382 smartlist_split_string(args
, body
, " ",
2383 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2384 if (smartlist_len(args
) &&
2385 !strcasecmp(smartlist_get(args
, 0), "mode=reverse")) {
2386 char *cp
= smartlist_get(args
, 0);
2387 smartlist_del_keeporder(args
, 0);
2391 SMARTLIST_FOREACH(args
, const char *, arg
, {
2392 dnsserv_launch_request(arg
, is_reverse
);
2395 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2396 smartlist_free(args
);
2398 send_control_done(conn
);
2402 /** Called when we get a PROTOCOLINFO command: send back a reply. */
2404 handle_control_protocolinfo(control_connection_t
*conn
, uint32_t len
,
2407 const char *bad_arg
= NULL
;
2411 conn
->have_sent_protocolinfo
= 1;
2412 args
= smartlist_create();
2413 smartlist_split_string(args
, body
, " ",
2414 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2415 SMARTLIST_FOREACH(args
, const char *, arg
, {
2417 tor_parse_long(arg
, 10, 0, LONG_MAX
, &ok
, NULL
);
2424 connection_printf_to_buf(conn
, "513 No such version %s\r\n",
2426 /* Don't tolerate bad arguments when not authenticated. */
2427 if (!STATE_IS_OPEN(TO_CONN(conn
)->state
))
2428 connection_mark_for_close(TO_CONN(conn
));
2431 or_options_t
*options
= get_options();
2432 int cookies
= options
->CookieAuthentication
;
2433 char *cfile
= get_cookie_file();
2434 char *esc_cfile
= esc_for_log(cfile
);
2437 int passwd
= (options
->HashedControlPassword
!= NULL
) &&
2438 strlen(options
->HashedControlPassword
);
2439 smartlist_t
*mlist
= smartlist_create();
2441 smartlist_add(mlist
, (char*)"COOKIE");
2443 smartlist_add(mlist
, (char*)"HASHEDPASSWORD");
2444 if (!cookies
&& !passwd
)
2445 smartlist_add(mlist
, (char*)"NULL");
2446 methods
= smartlist_join_strings(mlist
, ",", 0, NULL
);
2447 smartlist_free(mlist
);
2450 connection_printf_to_buf(conn
,
2451 "250-PROTOCOLINFO 1\r\n"
2452 "250-AUTH METHODS=%s%s%s\r\n"
2453 "250-VERSION Tor=%s\r\n"
2456 cookies
?" COOKIEFILE=":"",
2457 cookies
?esc_cfile
:"",
2461 tor_free(esc_cfile
);
2464 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2465 smartlist_free(args
);
2469 /** Called when we get a USEFEATURE command: parse the feature list, and
2470 * set up the control_connection's options properly. */
2472 handle_control_usefeature(control_connection_t
*conn
,
2477 int verbose_names
= 0, extended_events
= 0;
2479 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
2480 args
= smartlist_create();
2481 smartlist_split_string(args
, body
, " ",
2482 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2483 SMARTLIST_FOREACH(args
, const char *, arg
, {
2484 if (!strcasecmp(arg
, "VERBOSE_NAMES"))
2486 else if (!strcasecmp(arg
, "EXTENDED_EVENTS")) /* <- documented */
2487 extended_events
= 1;
2488 else if (!strcasecmp(arg
, "EXTENDED_FORMAT")) {
2489 /* remove this in 0.1.2.4; EXTENDED_FORMAT only ever worked for a
2490 * little while during 0.1.2.2-alpha-dev. */
2491 log_warn(LD_GENERAL
,
2492 "EXTENDED_FORMAT is deprecated; use EXTENDED_EVENTS "
2494 extended_events
= 1;
2496 connection_printf_to_buf(conn
, "552 Unrecognized feature \"%s\"\r\n",
2504 if (verbose_names
) {
2505 conn
->use_long_names
= 1;
2506 control_update_global_event_mask();
2508 if (extended_events
)
2509 conn
->use_extended_events
= 1;
2510 send_control_done(conn
);
2513 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2514 smartlist_free(args
);
2518 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
2520 connection_control_finished_flushing(control_connection_t
*conn
)
2524 connection_stop_writing(TO_CONN(conn
));
2528 /** Called when <b>conn</b> has gotten its socket closed. */
2530 connection_control_reached_eof(control_connection_t
*conn
)
2534 log_info(LD_CONTROL
,"Control connection reached EOF. Closing.");
2535 connection_mark_for_close(TO_CONN(conn
));
2539 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
2540 * stage of the protocol. */
2542 is_valid_initial_command(control_connection_t
*conn
, const char *cmd
)
2544 if (conn
->_base
.state
== CONTROL_CONN_STATE_OPEN
)
2546 if (!strcasecmp(cmd
, "PROTOCOLINFO"))
2547 return !conn
->have_sent_protocolinfo
;
2548 if (!strcasecmp(cmd
, "AUTHENTICATE") ||
2549 !strcasecmp(cmd
, "QUIT"))
2554 /** Called when data has arrived on a v1 control connection: Try to fetch
2555 * commands from conn->inbuf, and execute them.
2558 connection_control_process_inbuf(control_connection_t
*conn
)
2565 tor_assert(conn
->_base
.state
== CONTROL_CONN_STATE_OPEN
||
2566 conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH
);
2568 if (!conn
->incoming_cmd
) {
2569 conn
->incoming_cmd
= tor_malloc(1024);
2570 conn
->incoming_cmd_len
= 1024;
2571 conn
->incoming_cmd_cur_len
= 0;
2574 if (conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
2575 peek_buf_has_control0_command(conn
->_base
.inbuf
)) {
2576 /* Detect v0 commands and send a "no more v0" message. */
2579 set_uint16(buf
+2, htons(0x0000)); /* type == error */
2580 set_uint16(buf
+4, htons(0x0001)); /* code == internal error */
2581 strlcpy(buf
+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
2582 "and later; upgrade your controller.",
2584 body_len
= 2+strlen(buf
+6)+2; /* code, msg, nul. */
2585 set_uint16(buf
+0, htons(body_len
));
2586 connection_write_to_buf(buf
, 4+body_len
, TO_CONN(conn
));
2587 connection_mark_for_close(TO_CONN(conn
));
2588 conn
->_base
.hold_open_until_flushed
= 1;
2596 /* First, fetch a line. */
2598 data_len
= conn
->incoming_cmd_len
- conn
->incoming_cmd_cur_len
;
2599 r
= fetch_from_buf_line(conn
->_base
.inbuf
,
2600 conn
->incoming_cmd
+conn
->incoming_cmd_cur_len
,
2603 /* Line not all here yet. Wait. */
2606 while (conn
->incoming_cmd_len
< data_len
+conn
->incoming_cmd_cur_len
)
2607 conn
->incoming_cmd_len
*= 2;
2608 conn
->incoming_cmd
= tor_realloc(conn
->incoming_cmd
,
2609 conn
->incoming_cmd_len
);
2613 tor_assert(data_len
);
2615 last_idx
= conn
->incoming_cmd_cur_len
;
2616 conn
->incoming_cmd_cur_len
+= data_len
;
2618 /* We have appended a line to incoming_cmd. Is the command done? */
2619 if (last_idx
== 0 && *conn
->incoming_cmd
!= '+')
2620 /* One line command, didn't start with '+'. */
2622 /* XXXX this code duplication is kind of dumb. */
2623 if (last_idx
+3 == conn
->incoming_cmd_cur_len
&&
2624 !memcmp(conn
->incoming_cmd
+ last_idx
, ".\r\n", 3)) {
2625 /* Just appended ".\r\n"; we're done. Remove it. */
2626 conn
->incoming_cmd_cur_len
-= 3;
2628 } else if (last_idx
+2 == conn
->incoming_cmd_cur_len
&&
2629 !memcmp(conn
->incoming_cmd
+ last_idx
, ".\n", 2)) {
2630 /* Just appended ".\n"; we're done. Remove it. */
2631 conn
->incoming_cmd_cur_len
-= 2;
2634 /* Otherwise, read another line. */
2636 data_len
= conn
->incoming_cmd_cur_len
;
2637 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
2641 while ((size_t)cmd_len
< data_len
2642 && !TOR_ISSPACE(conn
->incoming_cmd
[cmd_len
]))
2645 data_len
-= cmd_len
;
2646 conn
->incoming_cmd
[cmd_len
]='\0';
2647 args
= conn
->incoming_cmd
+cmd_len
+1;
2648 while (*args
== ' ' || *args
== '\t') {
2653 /* Quit is always valid. */
2654 if (!strcasecmp(conn
->incoming_cmd
, "QUIT")) {
2655 connection_write_str_to_buf("250 closing connection\r\n", conn
);
2656 connection_mark_for_close(TO_CONN(conn
));
2660 if (conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
2661 !is_valid_initial_command(conn
, conn
->incoming_cmd
)) {
2662 connection_write_str_to_buf("514 Authentication required.\r\n", conn
);
2663 connection_mark_for_close(TO_CONN(conn
));
2667 if (!strcasecmp(conn
->incoming_cmd
, "SETCONF")) {
2668 if (handle_control_setconf(conn
, data_len
, args
))
2670 } else if (!strcasecmp(conn
->incoming_cmd
, "RESETCONF")) {
2671 if (handle_control_resetconf(conn
, data_len
, args
))
2673 } else if (!strcasecmp(conn
->incoming_cmd
, "GETCONF")) {
2674 if (handle_control_getconf(conn
, data_len
, args
))
2676 } else if (!strcasecmp(conn
->incoming_cmd
, "SETEVENTS")) {
2677 if (handle_control_setevents(conn
, data_len
, args
))
2679 } else if (!strcasecmp(conn
->incoming_cmd
, "AUTHENTICATE")) {
2680 if (handle_control_authenticate(conn
, data_len
, args
))
2682 } else if (!strcasecmp(conn
->incoming_cmd
, "SAVECONF")) {
2683 if (handle_control_saveconf(conn
, data_len
, args
))
2685 } else if (!strcasecmp(conn
->incoming_cmd
, "SIGNAL")) {
2686 if (handle_control_signal(conn
, data_len
, args
))
2688 } else if (!strcasecmp(conn
->incoming_cmd
, "MAPADDRESS")) {
2689 if (handle_control_mapaddress(conn
, data_len
, args
))
2691 } else if (!strcasecmp(conn
->incoming_cmd
, "GETINFO")) {
2692 if (handle_control_getinfo(conn
, data_len
, args
))
2694 } else if (!strcasecmp(conn
->incoming_cmd
, "EXTENDCIRCUIT")) {
2695 if (handle_control_extendcircuit(conn
, data_len
, args
))
2697 } else if (!strcasecmp(conn
->incoming_cmd
, "SETCIRCUITPURPOSE")) {
2698 if (handle_control_setpurpose(conn
, 1, data_len
, args
))
2700 } else if (!strcasecmp(conn
->incoming_cmd
, "SETROUTERPURPOSE")) {
2701 if (handle_control_setpurpose(conn
, 0, data_len
, args
))
2703 } else if (!strcasecmp(conn
->incoming_cmd
, "ATTACHSTREAM")) {
2704 if (handle_control_attachstream(conn
, data_len
, args
))
2706 } else if (!strcasecmp(conn
->incoming_cmd
, "+POSTDESCRIPTOR")) {
2707 if (handle_control_postdescriptor(conn
, data_len
, args
))
2709 } else if (!strcasecmp(conn
->incoming_cmd
, "REDIRECTSTREAM")) {
2710 if (handle_control_redirectstream(conn
, data_len
, args
))
2712 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSESTREAM")) {
2713 if (handle_control_closestream(conn
, data_len
, args
))
2715 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSECIRCUIT")) {
2716 if (handle_control_closecircuit(conn
, data_len
, args
))
2718 } else if (!strcasecmp(conn
->incoming_cmd
, "USEFEATURE")) {
2719 if (handle_control_usefeature(conn
, data_len
, args
))
2721 } else if (!strcasecmp(conn
->incoming_cmd
, "RESOLVE")) {
2722 if (handle_control_resolve(conn
, data_len
, args
))
2724 } else if (!strcasecmp(conn
->incoming_cmd
, "PROTOCOLINFO")) {
2725 if (handle_control_protocolinfo(conn
, data_len
, args
))
2728 connection_printf_to_buf(conn
, "510 Unrecognized command \"%s\"\r\n",
2729 conn
->incoming_cmd
);
2732 conn
->incoming_cmd_cur_len
= 0;
2736 /** Convert a numeric reason for destroying a circuit into a string for a
2739 circuit_end_reason_to_string(int reason
)
2741 if (reason
>= 0 && reason
& END_CIRC_REASON_FLAG_REMOTE
)
2742 reason
&= ~END_CIRC_REASON_FLAG_REMOTE
;
2744 case END_CIRC_AT_ORIGIN
:
2745 /* This shouldn't get passed here; it's a catch-all reason. */
2747 case END_CIRC_REASON_NONE
:
2748 /* This shouldn't get passed here; it's a catch-all reason. */
2750 case END_CIRC_REASON_TORPROTOCOL
:
2751 return "TORPROTOCOL";
2752 case END_CIRC_REASON_INTERNAL
:
2754 case END_CIRC_REASON_REQUESTED
:
2756 case END_CIRC_REASON_HIBERNATING
:
2757 return "HIBERNATING";
2758 case END_CIRC_REASON_RESOURCELIMIT
:
2759 return "RESOURCELIMIT";
2760 case END_CIRC_REASON_CONNECTFAILED
:
2761 return "CONNECTFAILED";
2762 case END_CIRC_REASON_OR_IDENTITY
:
2763 return "OR_IDENTITY";
2764 case END_CIRC_REASON_OR_CONN_CLOSED
:
2765 return "OR_CONN_CLOSED";
2766 case END_CIRC_REASON_FINISHED
:
2768 case END_CIRC_REASON_TIMEOUT
:
2770 case END_CIRC_REASON_DESTROYED
:
2772 case END_CIRC_REASON_NOPATH
:
2774 case END_CIRC_REASON_NOSUCHSERVICE
:
2775 return "NOSUCHSERVICE";
2777 log_warn(LD_BUG
, "Unrecognized reason code %d", (int)reason
);
2782 /** Something has happened to circuit <b>circ</b>: tell any interested
2783 * control connections. */
2785 control_event_circuit_status(origin_circuit_t
*circ
, circuit_status_event_t tp
,
2789 char reason_buf
[64];
2790 int providing_reason
=0;
2792 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS
))
2796 if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS
))
2797 path
= circuit_list_path(circ
,0);
2801 case CIRC_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
2802 case CIRC_EVENT_BUILT
: status
= "BUILT"; break;
2803 case CIRC_EVENT_EXTENDED
: status
= "EXTENDED"; break;
2804 case CIRC_EVENT_FAILED
: status
= "FAILED"; break;
2805 case CIRC_EVENT_CLOSED
: status
= "CLOSED"; break;
2807 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
2811 if (tp
== CIRC_EVENT_FAILED
|| tp
== CIRC_EVENT_CLOSED
) {
2812 const char *reason_str
= circuit_end_reason_to_string(reason_code
);
2813 char *reason
= NULL
;
2816 reason
= tor_malloc(16);
2817 tor_snprintf(reason
, 16, "UNKNOWN_%d", reason_code
);
2818 reason_str
= reason
;
2820 if (reason_code
> 0 && reason_code
& END_CIRC_REASON_FLAG_REMOTE
) {
2821 tor_snprintf(reason_buf
, sizeof(reason_buf
),
2822 "REASON=DESTROYED REMOTE_REASON=%s", reason_str
);
2824 tor_snprintf(reason_buf
, sizeof(reason_buf
),
2825 "REASON=%s", reason_str
);
2830 if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS
)) {
2831 const char *sp
= strlen(path
) ? " " : "";
2832 if (providing_reason
)
2833 send_control_event_extended(EVENT_CIRCUIT_STATUS
, SHORT_NAMES
,
2834 "650 CIRC %lu %s%s%s@%s\r\n",
2835 (unsigned long)circ
->global_identifier
,
2836 status
, sp
, path
, reason_buf
);
2838 send_control_event_extended(EVENT_CIRCUIT_STATUS
, SHORT_NAMES
,
2839 "650 CIRC %lu %s%s%s\r\n",
2840 (unsigned long)circ
->global_identifier
,
2843 if (EVENT_IS_INTERESTING1L(EVENT_CIRCUIT_STATUS
)) {
2844 char *vpath
= circuit_list_path_for_controller(circ
);
2845 const char *sp
= strlen(vpath
) ? " " : "";
2846 if (providing_reason
)
2847 send_control_event_extended(EVENT_CIRCUIT_STATUS
, LONG_NAMES
,
2848 "650 CIRC %lu %s%s%s@%s\r\n",
2849 (unsigned long)circ
->global_identifier
,
2850 status
, sp
, vpath
, reason_buf
);
2852 send_control_event_extended(EVENT_CIRCUIT_STATUS
, LONG_NAMES
,
2853 "650 CIRC %lu %s%s%s\r\n",
2854 (unsigned long)circ
->global_identifier
,
2864 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
2865 * <b>buf</b>, determine the address:port combination requested on
2866 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
2869 write_stream_target_to_buf(edge_connection_t
*conn
, char *buf
, size_t len
)
2872 if (conn
->chosen_exit_name
)
2873 if (tor_snprintf(buf2
, sizeof(buf2
), ".%s.exit", conn
->chosen_exit_name
)<0)
2875 if (tor_snprintf(buf
, len
, "%s%s%s:%d",
2876 conn
->socks_request
->address
,
2877 conn
->chosen_exit_name
? buf2
: "",
2878 !conn
->chosen_exit_name
&&
2879 connection_edge_is_rendezvous_stream(conn
) ? ".onion" : "",
2880 conn
->socks_request
->port
)<0)
2885 /** Convert the reason for ending a stream <b>reason</b> into the format used
2886 * in STREAM events. Return NULL if the reason is unrecognized. */
2888 stream_end_reason_to_string(int reason
)
2890 reason
&= END_STREAM_REASON_MASK
;
2892 case END_STREAM_REASON_MISC
: return "MISC";
2893 case END_STREAM_REASON_RESOLVEFAILED
: return "RESOLVEFAILED";
2894 case END_STREAM_REASON_CONNECTREFUSED
: return "CONNECTREFUSED";
2895 case END_STREAM_REASON_EXITPOLICY
: return "EXITPOLICY";
2896 case END_STREAM_REASON_DESTROY
: return "DESTROY";
2897 case END_STREAM_REASON_DONE
: return "DONE";
2898 case END_STREAM_REASON_TIMEOUT
: return "TIMEOUT";
2899 case END_STREAM_REASON_HIBERNATING
: return "HIBERNATING";
2900 case END_STREAM_REASON_INTERNAL
: return "INTERNAL";
2901 case END_STREAM_REASON_RESOURCELIMIT
: return "RESOURCELIMIT";
2902 case END_STREAM_REASON_CONNRESET
: return "CONNRESET";
2903 case END_STREAM_REASON_TORPROTOCOL
: return "TORPROTOCOL";
2904 case END_STREAM_REASON_NOTDIRECTORY
: return "NOTDIRECTORY";
2906 case END_STREAM_REASON_CANT_ATTACH
: return "CANT_ATTACH";
2907 case END_STREAM_REASON_NET_UNREACHABLE
: return "NET_UNREACHABLE";
2908 case END_STREAM_REASON_SOCKSPROTOCOL
: return "SOCKS_PROTOCOL";
2910 default: return NULL
;
2914 /** Something has happened to the stream associated with AP connection
2915 * <b>conn</b>: tell any interested control connections. */
2917 control_event_stream_status(edge_connection_t
*conn
, stream_status_event_t tp
,
2920 char reason_buf
[64];
2921 char addrport_buf
[64];
2924 origin_circuit_t
*origin_circ
= NULL
;
2926 tor_assert(conn
->socks_request
);
2928 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS
))
2931 if (tp
== STREAM_EVENT_CLOSED
&&
2932 (reason_code
& END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
))
2935 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
2937 reason_buf
[0] = '\0';
2940 case STREAM_EVENT_SENT_CONNECT
: status
= "SENTCONNECT"; break;
2941 case STREAM_EVENT_SENT_RESOLVE
: status
= "SENTRESOLVE"; break;
2942 case STREAM_EVENT_SUCCEEDED
: status
= "SUCCEEDED"; break;
2943 case STREAM_EVENT_FAILED
: status
= "FAILED"; break;
2944 case STREAM_EVENT_CLOSED
: status
= "CLOSED"; break;
2945 case STREAM_EVENT_NEW
: status
= "NEW"; break;
2946 case STREAM_EVENT_NEW_RESOLVE
: status
= "NEWRESOLVE"; break;
2947 case STREAM_EVENT_FAILED_RETRIABLE
: status
= "DETACHED"; break;
2948 case STREAM_EVENT_REMAP
: status
= "REMAP"; break;
2950 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
2953 if (reason_code
&& (tp
== STREAM_EVENT_FAILED
||
2954 tp
== STREAM_EVENT_CLOSED
||
2955 tp
== STREAM_EVENT_FAILED_RETRIABLE
)) {
2956 const char *reason_str
= stream_end_reason_to_string(reason_code
);
2960 tor_snprintf(r
, 16, "UNKNOWN_%d", reason_code
);
2963 if (reason_code
& END_STREAM_REASON_FLAG_REMOTE
)
2964 tor_snprintf(reason_buf
, sizeof(reason_buf
),
2965 "REASON=END REMOTE_REASON=%s", reason_str
);
2967 tor_snprintf(reason_buf
, sizeof(reason_buf
),
2968 "REASON=%s", reason_str
);
2970 } else if (reason_code
&& tp
== STREAM_EVENT_REMAP
) {
2971 switch (reason_code
) {
2972 case REMAP_STREAM_SOURCE_CACHE
:
2973 strlcpy(reason_buf
, "SOURCE=CACHE", sizeof(reason_buf
));
2975 case REMAP_STREAM_SOURCE_EXIT
:
2976 strlcpy(reason_buf
, "SOURCE=EXIT", sizeof(reason_buf
));
2979 tor_snprintf(reason_buf
, sizeof(reason_buf
), "REASON=UNKNOWN_%d",
2985 if (tp
== STREAM_EVENT_NEW
) {
2986 tor_snprintf(addrport_buf
,sizeof(addrport_buf
), "%sSOURCE_ADDR=%s:%d",
2987 strlen(reason_buf
) ? " " : "",
2988 TO_CONN(conn
)->address
, TO_CONN(conn
)->port
);
2990 addrport_buf
[0] = '\0';
2993 circ
= circuit_get_by_edge_conn(conn
);
2994 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
2995 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
2996 send_control_event_extended(EVENT_STREAM_STATUS
, ALL_NAMES
,
2997 "650 STREAM %lu %s %lu %s@%s%s\r\n",
2998 (unsigned long)conn
->global_identifier
, status
,
3000 (unsigned long)origin_circ
->global_identifier
: 0ul,
3001 buf
, reason_buf
, addrport_buf
);
3003 /* XXX need to specify its intended exit, etc? */
3008 /** Figure out the best name for the target router of an OR connection
3009 * <b>conn</b>, and write it into the <b>len</b>-character buffer
3010 * <b>name</b>. Use verbose names if <b>long_names</b> is set. */
3012 orconn_target_get_name(int long_names
,
3013 char *name
, size_t len
, or_connection_t
*conn
)
3017 strlcpy(name
, conn
->nickname
, len
);
3019 tor_snprintf(name
, len
, "%s:%d",
3020 conn
->_base
.address
, conn
->_base
.port
);
3022 routerinfo_t
*ri
= router_get_by_digest(conn
->identity_digest
);
3024 tor_assert(len
> MAX_VERBOSE_NICKNAME_LEN
);
3025 router_get_verbose_nickname(name
, ri
);
3026 } else if (! tor_digest_is_zero(conn
->identity_digest
)) {
3028 base16_encode(name
+1, len
-1, conn
->identity_digest
,
3031 tor_snprintf(name
, len
, "%s:%d",
3032 conn
->_base
.address
, conn
->_base
.port
);
3037 /** Convert a TOR_TLS_* error code into an END_OR_CONN_* reason. */
3039 control_tls_error_to_reason(int e
)
3042 case TOR_TLS_ERROR_IO
:
3043 return END_OR_CONN_REASON_TLS_IO_ERROR
;
3044 case TOR_TLS_ERROR_CONNREFUSED
:
3045 return END_OR_CONN_REASON_TCP_REFUSED
;
3046 case TOR_TLS_ERROR_CONNRESET
:
3047 return END_OR_CONN_REASON_TLS_CONNRESET
;
3048 case TOR_TLS_ERROR_NO_ROUTE
:
3049 return END_OR_CONN_REASON_TLS_NO_ROUTE
;
3050 case TOR_TLS_ERROR_TIMEOUT
:
3051 return END_OR_CONN_REASON_TLS_TIMEOUT
;
3052 case TOR_TLS_WANTREAD
:
3053 case TOR_TLS_WANTWRITE
:
3056 return END_OR_CONN_REASON_DONE
;
3058 return END_OR_CONN_REASON_TLS_MISC
;
3062 /** Convert the reason for ending an OR connection <b>r</b> into the format
3063 * used in ORCONN events. Return NULL if the reason is unrecognized. */
3065 or_conn_end_reason_to_string(int r
)
3068 case END_OR_CONN_REASON_DONE
:
3069 return "REASON=DONE";
3070 case END_OR_CONN_REASON_TCP_REFUSED
:
3071 return "REASON=CONNECTREFUSED";
3072 case END_OR_CONN_REASON_OR_IDENTITY
:
3073 return "REASON=IDENTITY";
3074 case END_OR_CONN_REASON_TLS_CONNRESET
:
3075 return "REASON=CONNECTRESET";
3076 case END_OR_CONN_REASON_TLS_TIMEOUT
:
3077 return "REASON=TIMEOUT";
3078 case END_OR_CONN_REASON_TLS_NO_ROUTE
:
3079 return "REASON=NOROUTE";
3080 case END_OR_CONN_REASON_TLS_IO_ERROR
:
3081 return "REASON=IOERROR";
3082 case END_OR_CONN_REASON_TLS_MISC
:
3083 return "REASON=MISC";
3087 log_warn(LD_BUG
, "Unrecognized or_conn reason code %d", r
);
3088 return "REASON=BOGUS";
3092 /** Called when the status of an OR connection <b>conn</b> changes: tell any
3093 * interested control connections. <b>tp</b> is the new status for the
3094 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
3095 * may be the reason why.
3098 control_event_or_conn_status(or_connection_t
*conn
, or_conn_status_event_t tp
,
3104 char ncircs_buf
[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
3106 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS
))
3111 case OR_CONN_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
3112 case OR_CONN_EVENT_CONNECTED
: status
= "CONNECTED"; break;
3113 case OR_CONN_EVENT_FAILED
: status
= "FAILED"; break;
3114 case OR_CONN_EVENT_CLOSED
: status
= "CLOSED"; break;
3115 case OR_CONN_EVENT_NEW
: status
= "NEW"; break;
3117 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3120 ncircs
= circuit_count_pending_on_or_conn(conn
);
3121 ncircs
+= conn
->n_circuits
;
3122 if (ncircs
&& (tp
== OR_CONN_EVENT_FAILED
|| tp
== OR_CONN_EVENT_CLOSED
)) {
3123 tor_snprintf(ncircs_buf
, sizeof(ncircs_buf
), "%sNCIRCS=%d",
3124 reason
? " " : "", ncircs
);
3127 if (EVENT_IS_INTERESTING1S(EVENT_OR_CONN_STATUS
)) {
3128 orconn_target_get_name(0, name
, sizeof(name
), conn
);
3129 send_control_event_extended(EVENT_OR_CONN_STATUS
, SHORT_NAMES
,
3130 "650 ORCONN %s %s@%s%s\r\n",
3132 or_conn_end_reason_to_string(reason
), ncircs_buf
);
3134 if (EVENT_IS_INTERESTING1L(EVENT_OR_CONN_STATUS
)) {
3135 orconn_target_get_name(1, name
, sizeof(name
), conn
);
3136 send_control_event_extended(EVENT_OR_CONN_STATUS
, LONG_NAMES
,
3137 "650 ORCONN %s %s@%s%s\r\n",
3139 or_conn_end_reason_to_string(reason
), ncircs_buf
);
3145 /** A second or more has elapsed: tell any interested control
3146 * connections how much bandwidth streams have used. */
3148 control_event_stream_bandwidth_used(void)
3150 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED
)) {
3151 smartlist_t
*conns
= get_connection_array();
3152 edge_connection_t
*edge_conn
;
3154 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
3156 if (conn
->type
!= CONN_TYPE_AP
)
3158 edge_conn
= TO_EDGE_CONN(conn
);
3159 if (!edge_conn
->n_read
&& !edge_conn
->n_written
)
3162 send_control_event(EVENT_STREAM_BANDWIDTH_USED
, ALL_NAMES
,
3163 "650 STREAM_BW %lu %lu %lu\r\n",
3164 (unsigned long)edge_conn
->global_identifier
,
3165 (unsigned long)edge_conn
->n_read
,
3166 (unsigned long)edge_conn
->n_written
);
3168 edge_conn
->n_written
= edge_conn
->n_read
= 0;
3175 /** A second or more has elapsed: tell any interested control
3176 * connections how much bandwidth we used. */
3178 control_event_bandwidth_used(uint32_t n_read
, uint32_t n_written
)
3180 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED
)) {
3181 send_control_event(EVENT_BANDWIDTH_USED
, ALL_NAMES
,
3182 "650 BW %lu %lu\r\n",
3183 (unsigned long)n_read
,
3184 (unsigned long)n_written
);
3190 /** Called when we are sending a log message to the controllers: suspend
3191 * sending further log messages to the controllers until we're done. Used by
3192 * CONN_LOG_PROTECT. */
3194 disable_control_logging(void)
3196 ++disable_log_messages
;
3199 /** We're done sending a log message to the controllers: re-enable controller
3200 * logging. Used by CONN_LOG_PROTECT. */
3202 enable_control_logging(void)
3204 if (--disable_log_messages
< 0)
3208 /** We got a log message: tell any interested control connections. */
3210 control_event_logmsg(int severity
, uint32_t domain
, const char *msg
)
3214 if (disable_log_messages
)
3217 if (domain
== LD_BUG
&& EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
) &&
3218 severity
<= LOG_NOTICE
) {
3219 char *esc
= esc_for_log(msg
);
3220 ++disable_log_messages
;
3221 control_event_general_status(severity
, "BUG REASON=\"%s\"", esc
);
3222 --disable_log_messages
;
3226 event
= log_severity_to_event(severity
);
3227 if (event
>= 0 && EVENT_IS_INTERESTING(event
)) {
3230 if (strchr(msg
, '\n')) {
3232 b
= tor_strdup(msg
);
3233 for (cp
= b
; *cp
; ++cp
)
3234 if (*cp
== '\r' || *cp
== '\n')
3238 case LOG_DEBUG
: s
= "DEBUG"; break;
3239 case LOG_INFO
: s
= "INFO"; break;
3240 case LOG_NOTICE
: s
= "NOTICE"; break;
3241 case LOG_WARN
: s
= "WARN"; break;
3242 case LOG_ERR
: s
= "ERR"; break;
3243 default: s
= "UnknownLogSeverity"; break;
3245 ++disable_log_messages
;
3246 send_control_event(event
, ALL_NAMES
, "650 %s %s\r\n", s
, b
?b
:msg
);
3247 --disable_log_messages
;
3252 /** Called whenever we receive new router descriptors: tell any
3253 * interested control connections. <b>routers</b> is a list of
3257 control_event_descriptors_changed(smartlist_t
*routers
)
3261 smartlist_t
*identities
= NULL
;
3262 char buf
[HEX_DIGEST_LEN
+1];
3264 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC
))
3266 if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC
)) {
3267 identities
= smartlist_create();
3268 SMARTLIST_FOREACH(routers
, routerinfo_t
*, r
,
3270 base16_encode(buf
,sizeof(buf
),r
->cache_info
.identity_digest
,DIGEST_LEN
);
3271 smartlist_add(identities
, tor_strdup(buf
));
3274 if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC
)) {
3275 char *ids
= smartlist_join_strings(identities
, " ", 0, &len
);
3276 size_t ids_len
= strlen(ids
)+32;
3277 msg
= tor_malloc(ids_len
);
3278 tor_snprintf(msg
, ids_len
, "650 NEWDESC %s\r\n", ids
);
3279 send_control_event_string(EVENT_NEW_DESC
, SHORT_NAMES
|ALL_FORMATS
, msg
);
3283 if (EVENT_IS_INTERESTING1L(EVENT_NEW_DESC
)) {
3284 smartlist_t
*names
= smartlist_create();
3287 SMARTLIST_FOREACH(routers
, routerinfo_t
*, ri
, {
3288 char *b
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
3289 router_get_verbose_nickname(b
, ri
);
3290 smartlist_add(names
, b
);
3292 ids
= smartlist_join_strings(names
, " ", 0, &names_len
);
3293 names_len
= strlen(ids
)+32;
3294 msg
= tor_malloc(names_len
);
3295 tor_snprintf(msg
, names_len
, "650 NEWDESC %s\r\n", ids
);
3296 send_control_event_string(EVENT_NEW_DESC
, LONG_NAMES
|ALL_FORMATS
, msg
);
3299 SMARTLIST_FOREACH(names
, char *, cp
, tor_free(cp
));
3300 smartlist_free(names
);
3303 SMARTLIST_FOREACH(identities
, char *, cp
, tor_free(cp
));
3304 smartlist_free(identities
);
3309 /** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
3310 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
3311 * <b>error</b> is non-NULL, it is an error code describing the failure
3312 * mode of the mapping.
3315 control_event_address_mapped(const char *from
, const char *to
, time_t expires
,
3318 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP
))
3321 if (expires
< 3 || expires
== TIME_MAX
)
3322 send_control_event_extended(EVENT_ADDRMAP
, ALL_NAMES
,
3323 "650 ADDRMAP %s %s NEVER@%s\r\n", from
, to
,
3326 char buf
[ISO_TIME_LEN
+1];
3327 char buf2
[ISO_TIME_LEN
+1];
3328 format_local_iso_time(buf
,expires
);
3329 format_iso_time(buf2
,expires
);
3330 send_control_event_extended(EVENT_ADDRMAP
, ALL_NAMES
,
3331 "650 ADDRMAP %s %s \"%s\""
3332 "@%s%sEXPIRES=\"%s\"\r\n",
3334 error
?error
:"", error
?" ":"",
3341 /** The authoritative dirserver has received a new descriptor that
3342 * has passed basic syntax checks and is properly self-signed.
3344 * Notify any interested party of the new descriptor and what has
3345 * been done with it, and also optionally give an explanation/reason. */
3347 control_event_or_authdir_new_descriptor(const char *action
,
3348 const char *desc
, size_t desclen
,
3351 char firstline
[1024];
3357 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS
))
3360 tor_snprintf(firstline
, sizeof(firstline
),
3361 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
3365 /* Escape the server descriptor properly */
3366 esclen
= write_escaped_data(desc
, desclen
, &esc
);
3368 totallen
= strlen(firstline
) + esclen
+ 1;
3369 buf
= tor_malloc(totallen
);
3370 strlcpy(buf
, firstline
, totallen
);
3371 strlcpy(buf
+strlen(firstline
), esc
, totallen
);
3372 send_control_event_string(EVENT_AUTHDIR_NEWDESCS
, ALL_NAMES
|ALL_FORMATS
,
3374 send_control_event_string(EVENT_AUTHDIR_NEWDESCS
, ALL_NAMES
|ALL_FORMATS
,
3382 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
3383 * an NS event to any controller that cares. */
3385 control_event_networkstatus_changed(smartlist_t
*statuses
)
3388 char *s
, *esc
= NULL
;
3389 if (!EVENT_IS_INTERESTING(EVENT_NS
) || !smartlist_len(statuses
))
3392 strs
= smartlist_create();
3393 smartlist_add(strs
, tor_strdup("650+NS\r\n"));
3394 SMARTLIST_FOREACH(statuses
, routerstatus_t
*, rs
,
3396 s
= networkstatus_getinfo_helper_single(rs
);
3398 smartlist_add(strs
, s
);
3401 s
= smartlist_join_strings(strs
, "", 0, NULL
);
3402 write_escaped_data(s
, strlen(s
), &esc
);
3403 SMARTLIST_FOREACH(strs
, char *, cp
, tor_free(cp
));
3404 smartlist_free(strs
);
3406 send_control_event_string(EVENT_NS
, ALL_NAMES
|ALL_FORMATS
, esc
);
3407 send_control_event_string(EVENT_NS
, ALL_NAMES
|ALL_FORMATS
,
3414 /** Called when a single local_routerstatus_t has changed: Sends an NS event
3415 * to any countroller that cares. */
3417 control_event_networkstatus_changed_single(routerstatus_t
*rs
)
3419 smartlist_t
*statuses
;
3422 if (!EVENT_IS_INTERESTING(EVENT_NS
))
3425 statuses
= smartlist_create();
3426 smartlist_add(statuses
, rs
);
3427 r
= control_event_networkstatus_changed(statuses
);
3428 smartlist_free(statuses
);
3432 /** Our own router descriptor has changed; tell any controllers that care.
3435 control_event_my_descriptor_changed(void)
3437 send_control_event(EVENT_DESCCHANGED
, ALL_NAMES
, "650 DESCCHANGED\r\n");
3441 /** Helper: sends a status event where <b>type</b> is one of
3442 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
3443 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
3444 * string corresponding to <b>args</b>. */
3446 control_event_status(int type
, int severity
, const char *format
, va_list args
)
3448 char format_buf
[160];
3449 const char *status
, *sev
;
3452 case EVENT_STATUS_GENERAL
:
3453 status
= "STATUS_GENERAL";
3455 case EVENT_STATUS_CLIENT
:
3456 status
= "STATUS_CLIENT";
3458 case EVENT_STATUS_SERVER
:
3459 status
= "STATUS_SEVER";
3462 log_warn(LD_BUG
, "Unrecognized status type %d", type
);
3476 log_warn(LD_BUG
, "Unrecognized status severity %d", severity
);
3479 if (tor_snprintf(format_buf
, sizeof(format_buf
), "650 %s %s %s\r\n",
3480 status
, sev
, format
)<0) {
3481 log_warn(LD_BUG
, "Format string too long.");
3485 send_control_event_impl(type
, ALL_NAMES
|ALL_FORMATS
, 0, format_buf
, args
);
3489 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
3490 * by formatting the arguments using the printf-style <b>format</b>. */
3492 control_event_general_status(int severity
, const char *format
, ...)
3496 if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
))
3499 va_start(ap
, format
);
3500 r
= control_event_status(EVENT_STATUS_GENERAL
, severity
, format
, ap
);
3505 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
3506 * by formatting the arguments using the printf-style <b>format</b>. */
3508 control_event_client_status(int severity
, const char *format
, ...)
3512 if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT
))
3515 va_start(ap
, format
);
3516 r
= control_event_status(EVENT_STATUS_CLIENT
, severity
, format
, ap
);
3521 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
3522 * by formatting the arguments using the printf-style <b>format</b>. */
3524 control_event_server_status(int severity
, const char *format
, ...)
3528 if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER
))
3531 va_start(ap
, format
);
3532 r
= control_event_status(EVENT_STATUS_SERVER
, severity
, format
, ap
);
3537 /** Called when the status of an entry guard with the given <b>nickname</b>
3538 * and identity <b>digest</b> has changed to <b>status</b>: tells any
3539 * controllers that care. */
3541 control_event_guard(const char *nickname
, const char *digest
,
3544 char hbuf
[HEX_DIGEST_LEN
+1];
3545 base16_encode(hbuf
, sizeof(hbuf
), digest
, DIGEST_LEN
);
3546 if (!EVENT_IS_INTERESTING(EVENT_GUARD
))
3549 if (EVENT_IS_INTERESTING1L(EVENT_GUARD
)) {
3550 char buf
[MAX_VERBOSE_NICKNAME_LEN
+1];
3551 routerinfo_t
*ri
= router_get_by_digest(digest
);
3553 router_get_verbose_nickname(buf
, ri
);
3555 tor_snprintf(buf
, sizeof(buf
), "$%s~%s", hbuf
, nickname
);
3557 send_control_event(EVENT_GUARD
, LONG_NAMES
,
3558 "650 GUARD ENTRY %s %s\r\n", buf
, status
);
3560 if (EVENT_IS_INTERESTING1S(EVENT_GUARD
)) {
3561 send_control_event(EVENT_GUARD
, SHORT_NAMES
,
3562 "650 GUARD ENTRY $%s %s\r\n", hbuf
, status
);
3567 /** Helper: Return a newly allocated string containing a path to the
3568 * file where we store our authentication cookie. */
3570 get_cookie_file(void)
3572 or_options_t
*options
= get_options();
3573 if (options
->CookieAuthFile
&& strlen(options
->CookieAuthFile
)) {
3574 return tor_strdup(options
->CookieAuthFile
);
3576 const char *datadir
= get_options()->DataDirectory
;
3577 size_t len
= strlen(datadir
)+64;
3578 char *fname
= tor_malloc(len
);
3579 tor_snprintf(fname
, len
, "%s"PATH_SEPARATOR
"control_auth_cookie", datadir
);
3584 /** Choose a random authentication cookie and write it to disk.
3585 * Anybody who can read the cookie from disk will be considered
3586 * authorized to use the control connection. Return -1 if we can't
3587 * write the file, or 0 on success. */
3589 init_cookie_authentication(int enabled
)
3593 authentication_cookie_is_set
= 0;
3597 /* We don't want to generate a new cookie every time we call
3598 * options_act(). One should be enough. */
3599 if (authentication_cookie_is_set
)
3600 return 0; /* all set */
3602 fname
= get_cookie_file();
3603 crypto_rand(authentication_cookie
, AUTHENTICATION_COOKIE_LEN
);
3604 authentication_cookie_is_set
= 1;
3605 if (write_bytes_to_file(fname
, authentication_cookie
,
3606 AUTHENTICATION_COOKIE_LEN
, 1)) {
3607 log_warn(LD_FS
,"Error writing authentication cookie to %s.",
3613 if (get_options()->CookieAuthFileGroupReadable
) {
3614 if (chmod(fname
, 0640)) {
3615 log_warn(LD_FS
,"Unable to make %s group-readable.", escaped(fname
));