1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 const char control_c_id
[] =
10 * \brief Implementation for Tor's control-socket interface.
11 * See doc/spec/control-spec.txt for full details on protocol.
14 #define CONTROL_PRIVATE
18 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
19 * finished authentication and is accepting commands. */
20 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
22 /* Recognized asynchronous event types. It's okay to expand this list
23 * because it is used both as a list of v0 event types, and as indices
24 * into the bitfield to determine which controllers want which events.
26 #define _EVENT_MIN 0x0001
27 #define EVENT_CIRCUIT_STATUS 0x0001
28 #define EVENT_STREAM_STATUS 0x0002
29 #define EVENT_OR_CONN_STATUS 0x0003
30 #define EVENT_BANDWIDTH_USED 0x0004
31 #define EVENT_LOG_OBSOLETE 0x0005 /* Can reclaim this. */
32 #define EVENT_NEW_DESC 0x0006
33 #define EVENT_DEBUG_MSG 0x0007
34 #define EVENT_INFO_MSG 0x0008
35 #define EVENT_NOTICE_MSG 0x0009
36 #define EVENT_WARN_MSG 0x000A
37 #define EVENT_ERR_MSG 0x000B
38 #define EVENT_ADDRMAP 0x000C
39 // #define EVENT_AUTHDIR_NEWDESCS 0x000D
40 #define EVENT_DESCCHANGED 0x000E
41 // #define EVENT_NS 0x000F
42 #define EVENT_STATUS_CLIENT 0x0010
43 #define EVENT_STATUS_SERVER 0x0011
44 #define EVENT_STATUS_GENERAL 0x0012
45 #define EVENT_GUARD 0x0013
46 #define EVENT_STREAM_BANDWIDTH_USED 0x0014
47 #define _EVENT_MAX 0x0014
48 /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
50 /** Bitfield: The bit 1<<e is set if <b>any</b> open control
51 * connection is interested in events of type <b>e</b>. We use this
52 * so that we can decide to skip generating event messages that nobody
53 * has interest in without having to walk over the global connection
56 typedef uint32_t event_mask_t
;
57 static event_mask_t global_event_mask1long
= 0;
58 static event_mask_t global_event_mask1short
= 0;
60 /** True iff we have disabled log messages from being sent to the controller */
61 static int disable_log_messages
= 0;
63 /** Macro: true if any control connection is interested in events of type
65 #define EVENT_IS_INTERESTING(e) \
66 ((global_event_mask1long|global_event_mask1short) & (1<<(e)))
67 #define EVENT_IS_INTERESTING1L(e) (global_event_mask1long & (1<<(e)))
68 #define EVENT_IS_INTERESTING1S(e) (global_event_mask1short & (1<<(e)))
70 /** If we're using cookie-type authentication, how long should our cookies be?
72 #define AUTHENTICATION_COOKIE_LEN 32
74 /** If true, we've set authentication_cookie to a secret code and
75 * stored it to disk. */
76 static int authentication_cookie_is_set
= 0;
77 static char authentication_cookie
[AUTHENTICATION_COOKIE_LEN
];
81 #define ALL_NAMES (SHORT_NAMES|LONG_NAMES)
82 #define EXTENDED_FORMAT 4
83 #define NONEXTENDED_FORMAT 8
84 #define ALL_FORMATS (EXTENDED_FORMAT|NONEXTENDED_FORMAT)
85 typedef int event_format_t
;
87 static void connection_printf_to_buf(control_connection_t
*conn
,
88 const char *format
, ...)
90 static void send_control_done(control_connection_t
*conn
);
91 static void send_control_event(uint16_t event
, event_format_t which
,
92 const char *format
, ...)
94 static void send_control_event_extended(uint16_t event
, event_format_t which
,
95 const char *format
, ...)
97 static int handle_control_setconf(control_connection_t
*conn
, uint32_t len
,
99 static int handle_control_resetconf(control_connection_t
*conn
, uint32_t len
,
101 static int handle_control_getconf(control_connection_t
*conn
, uint32_t len
,
103 static int handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
105 static int handle_control_authenticate(control_connection_t
*conn
,
108 static int handle_control_saveconf(control_connection_t
*conn
, uint32_t len
,
110 static int handle_control_signal(control_connection_t
*conn
, uint32_t len
,
112 static int handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
114 static char *list_getinfo_options(void);
115 static int handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
117 static int handle_control_extendcircuit(control_connection_t
*conn
,
120 static int handle_control_setcircuitpurpose(control_connection_t
*conn
,
121 uint32_t len
, const char *body
);
122 static int handle_control_attachstream(control_connection_t
*conn
,
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
);
369 extract_escaped_string(const char *start
, size_t in_len_max
,
370 char **out
, size_t *out_len
)
372 const char *cp
, *end
;
379 end
= start
+in_len_max
;
381 /* Calculate length. */
385 else if (*cp
== '\\') {
387 return NULL
; /* Can't escape EOS. */
390 } else if (*cp
== '\"') {
399 *out_len
= end
-start
+1;
400 *out
= tor_strndup(start
, *out_len
);
405 /** Given a pointer to a string starting at <b>start</b> containing
406 * <b>in_len_max</b> characters, decode a string beginning with one double
407 * quote, containing any number of non-quote characters or characters escaped
408 * with a backslash, and ending with a final double quote. Place the resulting
409 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
410 * store its length in <b>out_len</b>. On success, return a pointer to the
411 * character immediately following the escaped string. On failure, return
413 /* XXXX020 fold into extract_escaped_string */
415 get_escaped_string(const char *start
, size_t in_len_max
,
416 char **out
, size_t *out_len
)
418 const char *cp
, *end
;
426 end
= start
+in_len_max
;
428 /* Calculate length. */
432 else if (*cp
== '\\') {
434 return NULL
; /* Can't escape EOS. */
437 } else if (*cp
== '\"') {
445 outp
= *out
= tor_malloc(len
+1);
455 tor_assert((outp
- *out
) == (int)*out_len
);
460 /** Acts like sprintf, but writes its formatted string to the end of
461 * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
462 * but it will always end with a CRLF sequence.
464 * Currently the length of the message is limited to 1024 (including the
467 connection_printf_to_buf(control_connection_t
*conn
, const char *format
, ...)
469 #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
471 char buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
];
475 r
= tor_vsnprintf(buf
, sizeof(buf
), format
, ap
);
478 log_warn(LD_BUG
, "Unable to format string for controller.");
482 if (memcmp("\r\n\0", buf
+len
-2, 3)) {
483 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-1] = '\0';
484 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-2] = '\n';
485 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-3] = '\r';
487 connection_write_to_buf(buf
, len
, TO_CONN(conn
));
490 /** Send a "DONE" message down the control connection <b>conn</b>. */
492 send_control_done(control_connection_t
*conn
)
494 connection_write_str_to_buf("250 OK\r\n", conn
);
497 /* Send an event to all v1 controllers that are listening for code
498 * <b>event</b>. The event's body is given by <b>msg</b>.
500 * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
501 * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
502 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
503 * to contollers that <em>have</em> enabled VERBOSE_NAMES.
505 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
506 * respect to the EXTENDED_EVENTS feature. */
508 send_control_event_string(uint16_t event
, event_format_t which
,
511 smartlist_t
*conns
= get_connection_array();
512 tor_assert(event
>= _EVENT_MIN
&& event
<= _EVENT_MAX
);
514 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
516 if (conn
->type
== CONN_TYPE_CONTROL
&&
517 !conn
->marked_for_close
&&
518 conn
->state
== CONTROL_CONN_STATE_OPEN
) {
519 control_connection_t
*control_conn
= TO_CONTROL_CONN(conn
);
520 if (control_conn
->use_long_names
) {
521 if (!(which
& LONG_NAMES
))
524 if (!(which
& SHORT_NAMES
))
527 if (control_conn
->use_extended_events
) {
528 if (!(which
& EXTENDED_FORMAT
))
531 if (!(which
& NONEXTENDED_FORMAT
))
534 if (control_conn
->event_mask
& (1<<event
)) {
536 connection_write_to_buf(msg
, strlen(msg
), TO_CONN(control_conn
));
537 if (event
== EVENT_ERR_MSG
)
539 else if (event
== EVENT_STATUS_GENERAL
)
540 is_err
= !strcmpstart(msg
, "STATUS_GENERAL ERR ");
541 else if (event
== EVENT_STATUS_CLIENT
)
542 is_err
= !strcmpstart(msg
, "STATUS_CLIENT ERR ");
543 else if (event
== EVENT_STATUS_SERVER
)
544 is_err
= !strcmpstart(msg
, "STATUS_SERVER ERR ");
546 connection_handle_write(TO_CONN(control_conn
), 1);
552 /** Helper for send_control1_event and send_control1_event_extended:
553 * Send an event to all v1 controllers that are listening for code
554 * <b>event</b>. The event's body is created by the printf-style format in
555 * <b>format</b>, and other arguments as provided.
557 * If <b>extended</b> is true, and the format contains a single '@' character,
558 * it will be replaced with a space and all text after that character will be
559 * sent only to controllers that have enabled extended events.
561 * Currently the length of the message is limited to 1024 (including the
564 send_control_event_impl(uint16_t event
, event_format_t which
, int extended
,
565 const char *format
, va_list ap
)
567 /* This is just a little longer than the longest allowed log message */
568 #define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
570 char buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
];
574 r
= tor_vsnprintf(buf
, sizeof(buf
), format
, ap
);
576 log_warn(LD_BUG
, "Unable to format event for controller.");
581 if (memcmp("\r\n\0", buf
+len
-2, 3)) {
582 /* if it is not properly terminated, do it now */
583 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-1] = '\0';
584 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-2] = '\n';
585 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-3] = '\r';
588 if (extended
&& (cp
= strchr(buf
, '@'))) {
589 which
&= ~ALL_FORMATS
;
591 send_control_event_string(event
, which
|EXTENDED_FORMAT
, buf
);
592 memcpy(cp
, "\r\n\0", 3);
593 send_control_event_string(event
, which
|NONEXTENDED_FORMAT
, buf
);
595 send_control_event_string(event
, which
|ALL_FORMATS
, buf
);
599 /* Send an event to all v1 controllers that are listening for code
600 * <b>event</b>. The event's body is created by the printf-style format in
601 * <b>format</b>, and other arguments as provided.
603 * Currently the length of the message is limited to 1024 (including the
606 send_control_event(uint16_t event
, event_format_t which
,
607 const char *format
, ...)
610 va_start(ap
, format
);
611 send_control_event_impl(event
, which
, 0, format
, ap
);
615 /* Send an event to all v1 controllers that are listening for code
616 * <b>event</b>. The event's body is created by the printf-style format in
617 * <b>format</b>, and other arguments as provided.
619 * If the format contains a single '@' character, it will be replaced with a
620 * space and all text after that character will be sent only to controllers
621 * that have enabled extended events.
623 * Currently the length of the message is limited to 1024 (including the
626 send_control_event_extended(uint16_t event
, event_format_t which
,
627 const char *format
, ...)
630 va_start(ap
, format
);
631 send_control_event_impl(event
, which
, 1, format
, ap
);
635 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
636 static origin_circuit_t
*
637 get_circ(const char *id
)
641 n_id
= tor_parse_ulong(id
, 10, 0, ULONG_MAX
, &ok
, NULL
);
644 return circuit_get_by_global_id(n_id
);
647 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
648 static edge_connection_t
*
649 get_stream(const char *id
)
653 edge_connection_t
*conn
;
654 n_id
= tor_parse_ulong(id
, 10, 0, ULONG_MAX
, &ok
, NULL
);
657 conn
= connection_get_by_global_id(n_id
);
658 if (!conn
|| conn
->_base
.type
!= CONN_TYPE_AP
)
663 /** Helper for setconf and resetconf. Acts like setconf, except
664 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
668 control_setconf_helper(control_connection_t
*conn
, uint32_t len
, char *body
,
672 config_line_t
*lines
=NULL
;
674 char *errstring
= NULL
;
675 const int clear_first
= 1;
678 smartlist_t
*entries
= smartlist_create();
680 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
681 * separated by space. break it into a list of configuration entries. */
686 while (!TOR_ISSPACE(*eq
) && *eq
!= '=')
688 key
= tor_strndup(body
, eq
-body
);
695 char *val_start
= body
;
696 while (!TOR_ISSPACE(*body
))
698 val
= tor_strndup(val_start
, body
-val_start
);
699 val_len
= strlen(val
);
701 body
= (char*)extract_escaped_string(body
, (len
- (body
-start
)),
704 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn
);
705 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
706 smartlist_free(entries
);
711 ent_len
= strlen(key
)+val_len
+3;
712 entry
= tor_malloc(ent_len
+1);
713 tor_snprintf(entry
, ent_len
, "%s %s", key
, val
);
719 smartlist_add(entries
, entry
);
720 while (TOR_ISSPACE(*body
))
724 smartlist_add(entries
, tor_strdup(""));
725 config
= smartlist_join_strings(entries
, "\n", 0, NULL
);
726 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
727 smartlist_free(entries
);
729 if (config_get_lines(config
, &lines
) < 0) {
730 log_warn(LD_CONTROL
,"Controller gave us config lines we can't parse.");
731 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
738 if ((r
=options_trial_assign(lines
, use_defaults
,
739 clear_first
, &errstring
)) < 0) {
742 "Controller gave us config lines that didn't validate: %s",
746 msg
= "552 Unrecognized option";
749 msg
= "513 Unacceptable option value";
752 msg
= "553 Transition not allowed";
756 msg
= "553 Unable to set option";
759 connection_printf_to_buf(conn
, "%s: %s\r\n", msg
, errstring
);
760 config_free_lines(lines
);
764 config_free_lines(lines
);
765 send_control_done(conn
);
769 /** Called when we receive a SETCONF message: parse the body and try
770 * to update our configuration. Reply with a DONE or ERROR message.
771 * Modifies the contents of body.*/
773 handle_control_setconf(control_connection_t
*conn
, uint32_t len
, char *body
)
775 return control_setconf_helper(conn
, len
, body
, 0);
778 /** Called when we receive a RESETCONF message: parse the body and try
779 * to update our configuration. Reply with a DONE or ERROR message.
780 * Modifies the contents of body. */
782 handle_control_resetconf(control_connection_t
*conn
, uint32_t len
, char *body
)
784 return control_setconf_helper(conn
, len
, body
, 1);
787 /** Called when we receive a GETCONF message. Parse the request, and
788 * reply with a CONFVALUE or an ERROR message */
790 handle_control_getconf(control_connection_t
*conn
, uint32_t body_len
,
793 smartlist_t
*questions
= NULL
;
794 smartlist_t
*answers
= NULL
;
795 smartlist_t
*unrecognized
= NULL
;
798 or_options_t
*options
= get_options();
801 questions
= smartlist_create();
802 (void) body_len
; /* body is nul-terminated; so we can ignore len. */
803 smartlist_split_string(questions
, body
, " ",
804 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
805 answers
= smartlist_create();
806 unrecognized
= smartlist_create();
807 SMARTLIST_FOREACH(questions
, char *, q
,
809 if (!option_is_recognized(q
)) {
810 smartlist_add(unrecognized
, q
);
812 config_line_t
*answer
= option_get_assignment(options
,q
);
814 const char *name
= option_get_canonical_name(q
);
815 size_t alen
= strlen(name
)+8;
816 char *astr
= tor_malloc(alen
);
817 tor_snprintf(astr
, alen
, "250-%s\r\n", name
);
818 smartlist_add(answers
, astr
);
823 size_t alen
= strlen(answer
->key
)+strlen(answer
->value
)+8;
824 char *astr
= tor_malloc(alen
);
825 tor_snprintf(astr
, alen
, "250-%s=%s\r\n",
826 answer
->key
, answer
->value
);
827 smartlist_add(answers
, astr
);
830 tor_free(answer
->key
);
831 tor_free(answer
->value
);
838 if ((len
= smartlist_len(unrecognized
))) {
839 for (i
=0; i
< len
-1; ++i
)
840 connection_printf_to_buf(conn
,
841 "552-Unrecognized configuration key \"%s\"\r\n",
842 (char*)smartlist_get(unrecognized
, i
));
843 connection_printf_to_buf(conn
,
844 "552 Unrecognized configuration key \"%s\"\r\n",
845 (char*)smartlist_get(unrecognized
, len
-1));
846 } else if ((len
= smartlist_len(answers
))) {
847 char *tmp
= smartlist_get(answers
, len
-1);
848 tor_assert(strlen(tmp
)>4);
850 msg
= smartlist_join_strings(answers
, "", 0, &msg_len
);
851 connection_write_to_buf(msg
, msg_len
, TO_CONN(conn
));
853 connection_write_str_to_buf("250 OK\r\n", conn
);
857 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
858 smartlist_free(answers
);
861 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
862 smartlist_free(questions
);
864 smartlist_free(unrecognized
);
870 /** Called when we get a SETEVENTS message: update conn->event_mask,
871 * and reply with DONE or ERROR. */
873 handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
877 uint32_t event_mask
= 0;
878 unsigned int extended
= 0;
879 smartlist_t
*events
= smartlist_create();
883 smartlist_split_string(events
, body
, " ",
884 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
885 SMARTLIST_FOREACH(events
, const char *, ev
,
887 if (!strcasecmp(ev
, "EXTENDED")) {
890 } else if (!strcasecmp(ev
, "CIRC"))
891 event_code
= EVENT_CIRCUIT_STATUS
;
892 else if (!strcasecmp(ev
, "STREAM"))
893 event_code
= EVENT_STREAM_STATUS
;
894 else if (!strcasecmp(ev
, "ORCONN"))
895 event_code
= EVENT_OR_CONN_STATUS
;
896 else if (!strcasecmp(ev
, "BW"))
897 event_code
= EVENT_BANDWIDTH_USED
;
898 else if (!strcasecmp(ev
, "DEBUG"))
899 event_code
= EVENT_DEBUG_MSG
;
900 else if (!strcasecmp(ev
, "INFO"))
901 event_code
= EVENT_INFO_MSG
;
902 else if (!strcasecmp(ev
, "NOTICE"))
903 event_code
= EVENT_NOTICE_MSG
;
904 else if (!strcasecmp(ev
, "WARN"))
905 event_code
= EVENT_WARN_MSG
;
906 else if (!strcasecmp(ev
, "ERR"))
907 event_code
= EVENT_ERR_MSG
;
908 else if (!strcasecmp(ev
, "NEWDESC"))
909 event_code
= EVENT_NEW_DESC
;
910 else if (!strcasecmp(ev
, "ADDRMAP"))
911 event_code
= EVENT_ADDRMAP
;
912 else if (!strcasecmp(ev
, "AUTHDIR_NEWDESCS"))
913 event_code
= EVENT_AUTHDIR_NEWDESCS
;
914 else if (!strcasecmp(ev
, "DESCCHANGED"))
915 event_code
= EVENT_DESCCHANGED
;
916 else if (!strcasecmp(ev
, "NS"))
917 event_code
= EVENT_NS
;
918 else if (!strcasecmp(ev
, "STATUS_GENERAL"))
919 event_code
= EVENT_STATUS_GENERAL
;
920 else if (!strcasecmp(ev
, "STATUS_CLIENT"))
921 event_code
= EVENT_STATUS_CLIENT
;
922 else if (!strcasecmp(ev
, "STATUS_SERVER"))
923 event_code
= EVENT_STATUS_SERVER
;
924 else if (!strcasecmp(ev
, "GUARD"))
925 event_code
= EVENT_GUARD
;
926 else if (!strcasecmp(ev
, "GUARDS")) {
927 /* XXXX021 This check is here to tolerate the controllers that
928 * depended on the buggy spec in 0.1.2.5-alpha through 0.1.2.10-rc.
929 * Once those versions are obsolete, stop supporting this. */
930 log_warn(LD_CONTROL
, "Controller used obsolete 'GUARDS' event name; "
931 "use GUARD instead.");
932 event_code
= EVENT_GUARD
;
933 } else if (!strcasecmp(ev
, "STREAM_BW"))
934 event_code
= EVENT_STREAM_BANDWIDTH_USED
;
936 connection_printf_to_buf(conn
, "552 Unrecognized event \"%s\"\r\n",
938 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
939 smartlist_free(events
);
942 event_mask
|= (1 << event_code
);
944 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
945 smartlist_free(events
);
947 conn
->event_mask
= event_mask
;
949 conn
->use_extended_events
= 1;
951 control_update_global_event_mask();
952 send_control_done(conn
);
956 /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
957 * Return a smartlist of acceptable passwords (unterminated strings of
958 * length S2K_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on failure.
961 decode_hashed_passwords(config_line_t
*passwords
)
965 smartlist_t
*sl
= smartlist_create();
967 tor_assert(passwords
);
969 for (cl
= passwords
; cl
; cl
= cl
->next
) {
970 const char *hashed
= cl
->value
;
972 if (!strcmpstart(hashed
, "16:")) {
973 if (base16_decode(decoded
, sizeof(decoded
), hashed
+3, strlen(hashed
+3))<0
974 || strlen(hashed
+3) != (S2K_SPECIFIER_LEN
+DIGEST_LEN
)*2) {
978 if (base64_decode(decoded
, sizeof(decoded
), hashed
, strlen(hashed
))
979 != S2K_SPECIFIER_LEN
+DIGEST_LEN
) {
983 smartlist_add(sl
, tor_memdup(decoded
, S2K_SPECIFIER_LEN
+DIGEST_LEN
));
989 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
994 /** Called when we get an AUTHENTICATE message. Check whether the
995 * authentication is valid, and if so, update the connection's state to
996 * OPEN. Reply with DONE or ERROR.
999 handle_control_authenticate(control_connection_t
*conn
, uint32_t len
,
1002 int used_quoted_string
= 0;
1003 or_options_t
*options
= get_options();
1004 const char *errstr
= NULL
;
1006 size_t password_len
;
1009 int bad_cookie
=0, bad_password
=0;
1010 smartlist_t
*sl
= NULL
;
1012 if (TOR_ISXDIGIT(body
[0])) {
1014 while (TOR_ISXDIGIT(*cp
))
1019 password
= tor_malloc(password_len
+ 1);
1020 if (base16_decode(password
, password_len
+1, body
, i
)<0) {
1021 connection_write_str_to_buf(
1022 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1023 "password? If so, the standard requires that you put it in "
1024 "double quotes.\r\n", conn
);
1025 connection_mark_for_close(TO_CONN(conn
));
1029 } else if (TOR_ISSPACE(body
[0])) {
1030 password
= tor_strdup("");
1033 if (!get_escaped_string(body
, len
, &password
, &password_len
)) {
1034 connection_write_str_to_buf("551 Invalid quoted string. You need "
1035 "to put the password in double quotes.\r\n", conn
);
1036 connection_mark_for_close(TO_CONN(conn
));
1039 used_quoted_string
= 1;
1042 if (!options
->CookieAuthentication
&& !options
->HashedControlPassword
) {
1043 /* if Tor doesn't demand any stronger authentication, then
1044 * the controller can get in with anything. */
1048 if (options
->CookieAuthentication
) {
1049 int also_password
= options
->HashedControlPassword
!= NULL
;
1050 if (password_len
!= AUTHENTICATION_COOKIE_LEN
) {
1051 if (!also_password
) {
1052 log_warn(LD_CONTROL
, "Got authentication cookie with wrong length "
1053 "(%d)", (int)password_len
);
1054 errstr
= "Wrong length on authentication cookie.";
1058 } else if (memcmp(authentication_cookie
, password
, password_len
)) {
1059 if (!also_password
) {
1060 log_warn(LD_CONTROL
, "Got mismatched authentication cookie");
1061 errstr
= "Authentication cookie did not match expected value.";
1070 if (options
->HashedControlPassword
) {
1071 char received
[DIGEST_LEN
];
1072 int also_cookie
= options
->CookieAuthentication
;
1073 sl
= decode_hashed_passwords(options
->HashedControlPassword
);
1076 log_warn(LD_CONTROL
,
1077 "Couldn't decode HashedControlPassword: invalid base16");
1078 errstr
="Couldn't decode HashedControlPassword value in configuration.";
1082 SMARTLIST_FOREACH(sl
, char *, expected
,
1084 secret_to_key(received
,DIGEST_LEN
,password
,password_len
,expected
);
1085 if (!memcmp(expected
+S2K_SPECIFIER_LEN
, received
, DIGEST_LEN
))
1088 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1091 if (used_quoted_string
)
1092 errstr
= "Password did not match HashedControlPassword value from "
1095 errstr
= "Password did not match HashedControlPassword value from "
1096 "configuration. Maybe you tried a plain text password? "
1097 "If so, the standard requires that you put it in double quotes.";
1104 /** We only get here if both kinds of authentication failed. */
1105 tor_assert(bad_password
&& bad_cookie
);
1106 log_warn(LD_CONTROL
, "Bad password or authentication cookie on controller.");
1107 errstr
= "Password did not match HashedControlPassword *or* authentication "
1113 errstr
= "Unknown reason.";
1114 connection_printf_to_buf(conn
, "515 Authentication failed: %s\r\n",
1116 connection_mark_for_close(TO_CONN(conn
));
1119 log_info(LD_CONTROL
, "Authenticated control connection (%d)", conn
->_base
.s
);
1120 send_control_done(conn
);
1121 conn
->_base
.state
= CONTROL_CONN_STATE_OPEN
;
1123 if (sl
) { /* clean up */
1124 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1130 /** Called when we get a SAVECONF command. Try to flush the current options to
1131 * disk, and report success or failure. */
1133 handle_control_saveconf(control_connection_t
*conn
, uint32_t len
,
1138 if (options_save_current()<0) {
1139 connection_write_str_to_buf(
1140 "551 Unable to write configuration to disk.\r\n", conn
);
1142 send_control_done(conn
);
1147 /** Called when we get a SIGNAL command. React to the provided signal, and
1148 * report success or failure. (If the signal results in a shutdown, success
1149 * may not be reported.) */
1151 handle_control_signal(control_connection_t
*conn
, uint32_t len
,
1160 while (body
[n
] && ! TOR_ISSPACE(body
[n
]))
1162 s
= tor_strndup(body
, n
);
1163 if (!strcasecmp(s
, "RELOAD") || !strcasecmp(s
, "HUP"))
1165 else if (!strcasecmp(s
, "SHUTDOWN") || !strcasecmp(s
, "INT"))
1167 else if (!strcasecmp(s
, "DUMP") || !strcasecmp(s
, "USR1"))
1169 else if (!strcasecmp(s
, "DEBUG") || !strcasecmp(s
, "USR2"))
1171 else if (!strcasecmp(s
, "HALT") || !strcasecmp(s
, "TERM"))
1173 else if (!strcasecmp(s
, "NEWNYM"))
1175 else if (!strcasecmp(s
, "CLEARDNSCACHE"))
1176 sig
= SIGCLEARDNSCACHE
;
1178 connection_printf_to_buf(conn
, "552 Unrecognized signal code \"%s\"\r\n",
1186 send_control_done(conn
);
1187 /* Flush the "done" first if the signal might make us shut down. */
1188 if (sig
== SIGTERM
|| sig
== SIGINT
)
1189 connection_handle_write(TO_CONN(conn
), 1);
1190 control_signal_act(sig
);
1194 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1195 * and report success or failrue. */
1197 handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
1205 (void) len
; /* body is nul-terminated, so it's safe to ignore the length. */
1207 lines
= smartlist_create();
1208 elts
= smartlist_create();
1209 reply
= smartlist_create();
1210 smartlist_split_string(lines
, body
, " ",
1211 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1212 SMARTLIST_FOREACH(lines
, char *, line
,
1215 smartlist_split_string(elts
, line
, "=", 0, 2);
1216 if (smartlist_len(elts
) == 2) {
1217 const char *from
= smartlist_get(elts
,0);
1218 const char *to
= smartlist_get(elts
,1);
1219 size_t anslen
= strlen(line
)+512;
1220 char *ans
= tor_malloc(anslen
);
1221 if (address_is_invalid_destination(to
, 1)) {
1222 tor_snprintf(ans
, anslen
,
1223 "512-syntax error: invalid address '%s'", to
);
1224 smartlist_add(reply
, ans
);
1225 log_warn(LD_CONTROL
,
1226 "Skipping invalid argument '%s' in MapAddress msg", to
);
1227 } else if (!strcmp(from
, ".") || !strcmp(from
, "0.0.0.0")) {
1228 const char *address
= addressmap_register_virtual_address(
1229 !strcmp(from
,".") ? RESOLVED_TYPE_HOSTNAME
: RESOLVED_TYPE_IPV4
,
1232 tor_snprintf(ans
, anslen
,
1233 "451-resource exhausted: skipping '%s'", line
);
1234 smartlist_add(reply
, ans
);
1235 log_warn(LD_CONTROL
,
1236 "Unable to allocate address for '%s' in MapAddress msg",
1239 tor_snprintf(ans
, anslen
, "250-%s=%s", address
, to
);
1240 smartlist_add(reply
, ans
);
1243 addressmap_register(from
, tor_strdup(to
), 1);
1244 tor_snprintf(ans
, anslen
, "250-%s", line
);
1245 smartlist_add(reply
, ans
);
1248 size_t anslen
= strlen(line
)+256;
1249 char *ans
= tor_malloc(anslen
);
1250 tor_snprintf(ans
, anslen
, "512-syntax error: mapping '%s' is "
1251 "not of expected form 'foo=bar'.", line
);
1252 smartlist_add(reply
, ans
);
1253 log_info(LD_CONTROL
, "Skipping MapAddress '%s': wrong "
1254 "number of items.", safe_str(line
));
1256 SMARTLIST_FOREACH(elts
, char *, cp
, tor_free(cp
));
1257 smartlist_clear(elts
);
1259 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
1260 smartlist_free(lines
);
1261 smartlist_free(elts
);
1263 if (smartlist_len(reply
)) {
1264 ((char*)smartlist_get(reply
,smartlist_len(reply
)-1))[3] = ' ';
1265 r
= smartlist_join_strings(reply
, "\r\n", 1, &sz
);
1266 connection_write_to_buf(r
, sz
, TO_CONN(conn
));
1269 const char *response
=
1270 "512 syntax error: not enough arguments to mapaddress.\r\n";
1271 connection_write_to_buf(response
, strlen(response
), TO_CONN(conn
));
1274 SMARTLIST_FOREACH(reply
, char *, cp
, tor_free(cp
));
1275 smartlist_free(reply
);
1279 /** Implementation helper for GETINFO: knows the answers for various
1280 * trivial-to-implement questions. */
1282 getinfo_helper_misc(control_connection_t
*conn
, const char *question
,
1286 if (!strcmp(question
, "version")) {
1287 *answer
= tor_strdup(get_version());
1288 } else if (!strcmp(question
, "config-file")) {
1289 *answer
= tor_strdup(get_torrc_fname());
1290 } else if (!strcmp(question
, "info/names")) {
1291 *answer
= list_getinfo_options();
1292 } else if (!strcmp(question
, "events/names")) {
1293 *answer
= tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
1294 "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
1295 "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
1297 } else if (!strcmp(question
, "features/names")) {
1298 *answer
= tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1299 } else if (!strcmp(question
, "address")) {
1301 if (router_pick_published_address(get_options(), &addr
) < 0)
1303 *answer
= tor_dup_addr(addr
);
1304 } else if (!strcmp(question
, "dir-usage")) {
1305 *answer
= directory_dump_request_log();
1306 } else if (!strcmp(question
, "fingerprint")) {
1307 routerinfo_t
*me
= router_get_my_routerinfo();
1310 *answer
= tor_malloc(HEX_DIGEST_LEN
+1);
1311 base16_encode(*answer
, HEX_DIGEST_LEN
+1, me
->cache_info
.identity_digest
,
1317 /** Awful hack: return a newly allocated string based on a routerinfo and
1318 * (possibly) an extrainfo, sticking the read-history and write-history from
1319 * <b>ei</b> into the resulting string. The thing you get back won't
1320 * necessarily have a valid signature.
1322 * New code should never use this; it's for backward compatibiliy.
1324 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1325 * not be NUL-terminated. */
1327 munge_extrainfo_into_routerinfo(const char *ri_body
, signed_descriptor_t
*ri
,
1328 signed_descriptor_t
*ei
)
1330 char *out
= NULL
, *outp
;
1332 const char *router_sig
;
1333 const char *ei_body
= signed_descriptor_get_body(ei
);
1334 size_t ri_len
= ri
->signed_descriptor_len
;
1335 size_t ei_len
= ei
->signed_descriptor_len
;
1339 outp
= out
= tor_malloc(ri_len
+ei_len
+1);
1340 if (!(router_sig
= tor_memstr(ri_body
, ri_len
, "\nrouter-signature")))
1343 memcpy(out
, ri_body
, router_sig
-ri_body
);
1344 outp
+= router_sig
-ri_body
;
1346 for (i
=0; i
< 2; ++i
) {
1347 const char *kwd
= i
?"\nwrite-history ":"\nread-history ";
1348 const char *cp
, *eol
;
1349 if (!(cp
= tor_memstr(ei_body
, ei_len
, kwd
)))
1352 eol
= memchr(cp
, '\n', ei_len
- (cp
-ei_body
));
1353 memcpy(outp
, cp
, eol
-cp
+1);
1356 memcpy(outp
, router_sig
, ri_len
- (router_sig
-ri_body
));
1358 tor_assert(outp
-out
< (int)(ri_len
+ei_len
+1));
1363 return tor_strndup(ri_body
, ri
->signed_descriptor_len
);
1366 /** Implementation helper for GETINFO: knows the answers for questions about
1367 * directory information. */
1369 getinfo_helper_dir(control_connection_t
*control_conn
,
1370 const char *question
, char **answer
)
1372 if (!strcmpstart(question
, "desc/id/")) {
1373 routerinfo_t
*ri
= router_get_by_hexdigest(question
+strlen("desc/id/"));
1375 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1377 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
1379 } else if (!strcmpstart(question
, "desc/name/")) {
1380 routerinfo_t
*ri
= router_get_by_nickname(question
+strlen("desc/name/"),1);
1382 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1384 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
1386 } else if (!strcmp(question
, "desc/all-recent")) {
1387 routerlist_t
*routerlist
= router_get_routerlist();
1388 smartlist_t
*sl
= smartlist_create();
1389 if (routerlist
&& routerlist
->routers
) {
1390 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
1392 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1395 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
1398 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
1399 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
1401 } else if (!strcmp(question
, "desc/all-recent-extrainfo-hack")) {
1402 /* XXXX Remove this once Torstat asks for extrainfos. */
1403 routerlist_t
*routerlist
= router_get_routerlist();
1404 smartlist_t
*sl
= smartlist_create();
1405 if (routerlist
&& routerlist
->routers
) {
1406 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
1408 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1409 signed_descriptor_t
*ei
= extrainfo_get_by_descriptor_digest(
1410 ri
->cache_info
.extra_info_digest
);
1412 smartlist_add(sl
, munge_extrainfo_into_routerinfo(body
,
1413 &ri
->cache_info
, ei
));
1416 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
1420 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
1421 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
1423 } else if (!strcmpstart(question
, "desc-annotations/id/")) {
1424 routerinfo_t
*ri
= router_get_by_hexdigest(question
+
1425 strlen("desc-annotations/id/"));
1427 const char *annotations
=
1428 signed_descriptor_get_annotations(&ri
->cache_info
);
1430 *answer
= tor_strndup(annotations
,
1431 ri
->cache_info
.annotations_len
);
1433 } else if (!strcmpstart(question
, "dir/server/")) {
1434 size_t answer_len
= 0, url_len
= strlen(question
)+2;
1435 char *url
= tor_malloc(url_len
);
1436 smartlist_t
*descs
= smartlist_create();
1440 tor_snprintf(url
, url_len
, "/tor/%s", question
+4);
1441 res
= dirserv_get_routerdescs(descs
, url
, &msg
);
1443 log_warn(LD_CONTROL
, "getinfo '%s': %s", question
, msg
);
1444 smartlist_free(descs
);
1447 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
1448 answer_len
+= sd
->signed_descriptor_len
);
1449 cp
= *answer
= tor_malloc(answer_len
+1);
1450 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
1452 memcpy(cp
, signed_descriptor_get_body(sd
),
1453 sd
->signed_descriptor_len
);
1454 cp
+= sd
->signed_descriptor_len
;
1458 smartlist_free(descs
);
1459 } else if (!strcmpstart(question
, "dir/status/")) {
1460 if (directory_permits_controller_requests(get_options())) {
1463 smartlist_t
*status_list
= smartlist_create();
1464 dirserv_get_networkstatus_v2(status_list
,
1465 question
+strlen("dir/status/"));
1466 SMARTLIST_FOREACH(status_list
, cached_dir_t
*, d
, len
+= d
->dir_len
);
1467 cp
= *answer
= tor_malloc(len
+1);
1468 SMARTLIST_FOREACH(status_list
, cached_dir_t
*, d
, {
1469 memcpy(cp
, d
->dir
, d
->dir_len
);
1473 smartlist_free(status_list
);
1475 smartlist_t
*fp_list
= smartlist_create();
1476 smartlist_t
*status_list
= smartlist_create();
1477 dirserv_get_networkstatus_v2_fingerprints(
1478 fp_list
, question
+strlen("dir/status/"));
1479 SMARTLIST_FOREACH(fp_list
, const char *, fp
, {
1481 char *fname
= networkstatus_get_cache_filename(fp
);
1482 s
= read_file_to_str(fname
, 0, NULL
);
1484 smartlist_add(status_list
, s
);
1487 SMARTLIST_FOREACH(fp_list
, char *, fp
, tor_free(fp
));
1488 smartlist_free(fp_list
);
1489 *answer
= smartlist_join_strings(status_list
, "", 0, NULL
);
1490 SMARTLIST_FOREACH(status_list
, char *, s
, tor_free(s
));
1491 smartlist_free(status_list
);
1493 } else if (!strcmp(question
, "network-status")) {
1494 routerlist_t
*routerlist
= router_get_routerlist();
1495 int verbose
= control_conn
->use_long_names
;
1496 if (!routerlist
|| !routerlist
->routers
||
1497 list_server_status_v1(routerlist
->routers
, answer
,
1498 verbose
? 2 : 1) < 0) {
1501 } else if (!strcmpstart(question
, "extra-info/digest/")) {
1502 question
+= strlen("extra-info/digest/");
1503 if (strlen(question
) == HEX_DIGEST_LEN
) {
1505 signed_descriptor_t
*sd
= NULL
;
1506 if (base16_decode(d
, sizeof(d
), question
, strlen(question
))==0)
1507 sd
= extrainfo_get_by_descriptor_digest(d
);
1509 const char *body
= signed_descriptor_get_body(sd
);
1511 *answer
= tor_strndup(body
, sd
->signed_descriptor_len
);
1519 /** Implementation helper for GETINFO: knows how to generate summaries of the
1520 * current states of things we send events about. */
1522 getinfo_helper_events(control_connection_t
*control_conn
,
1523 const char *question
, char **answer
)
1525 if (!strcmp(question
, "circuit-status")) {
1527 smartlist_t
*status
= smartlist_create();
1528 for (circ
= _circuit_get_global_list(); circ
; circ
= circ
->next
) {
1532 if (! CIRCUIT_IS_ORIGIN(circ
) || circ
->marked_for_close
)
1534 if (control_conn
->use_long_names
)
1535 path
= circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ
));
1537 path
= circuit_list_path(TO_ORIGIN_CIRCUIT(circ
),0);
1538 if (circ
->state
== CIRCUIT_STATE_OPEN
)
1540 else if (strlen(path
))
1545 slen
= strlen(path
)+strlen(state
)+20;
1546 s
= tor_malloc(slen
+1);
1547 tor_snprintf(s
, slen
, "%lu %s%s%s",
1548 (unsigned long)TO_ORIGIN_CIRCUIT(circ
)->global_identifier
,
1549 state
, *path
? " " : "", path
);
1550 smartlist_add(status
, s
);
1553 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1554 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1555 smartlist_free(status
);
1556 } else if (!strcmp(question
, "stream-status")) {
1557 smartlist_t
*conns
= get_connection_array();
1558 smartlist_t
*status
= smartlist_create();
1560 SMARTLIST_FOREACH(conns
, connection_t
*, base_conn
,
1563 edge_connection_t
*conn
;
1567 origin_circuit_t
*origin_circ
= NULL
;
1568 if (base_conn
->type
!= CONN_TYPE_AP
||
1569 base_conn
->marked_for_close
||
1570 base_conn
->state
== AP_CONN_STATE_SOCKS_WAIT
||
1571 base_conn
->state
== AP_CONN_STATE_NATD_WAIT
)
1573 conn
= TO_EDGE_CONN(base_conn
);
1574 switch (conn
->_base
.state
)
1576 case AP_CONN_STATE_CONTROLLER_WAIT
:
1577 case AP_CONN_STATE_CIRCUIT_WAIT
:
1578 if (conn
->socks_request
&&
1579 SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
))
1580 state
= "NEWRESOLVE";
1584 case AP_CONN_STATE_RENDDESC_WAIT
:
1585 case AP_CONN_STATE_CONNECT_WAIT
:
1586 state
= "SENTCONNECT"; break;
1587 case AP_CONN_STATE_RESOLVE_WAIT
:
1588 state
= "SENTRESOLVE"; break;
1589 case AP_CONN_STATE_OPEN
:
1590 state
= "SUCCEEDED"; break;
1592 log_warn(LD_BUG
, "Asked for stream in unknown state %d",
1596 circ
= circuit_get_by_edge_conn(conn
);
1597 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
1598 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
1599 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
1600 slen
= strlen(buf
)+strlen(state
)+32;
1601 s
= tor_malloc(slen
+1);
1602 tor_snprintf(s
, slen
, "%lu %s %lu %s",
1603 (unsigned long) conn
->global_identifier
,state
,
1605 (unsigned long)origin_circ
->global_identifier
: 0ul,
1607 smartlist_add(status
, s
);
1609 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1610 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1611 smartlist_free(status
);
1612 } else if (!strcmp(question
, "orconn-status")) {
1613 smartlist_t
*conns
= get_connection_array();
1614 smartlist_t
*status
= smartlist_create();
1615 SMARTLIST_FOREACH(conns
, connection_t
*, base_conn
,
1621 or_connection_t
*conn
;
1622 if (base_conn
->type
!= CONN_TYPE_OR
|| base_conn
->marked_for_close
)
1624 conn
= TO_OR_CONN(base_conn
);
1625 if (conn
->_base
.state
== OR_CONN_STATE_OPEN
)
1626 state
= "CONNECTED";
1627 else if (conn
->nickname
)
1631 orconn_target_get_name(control_conn
->use_long_names
, name
, sizeof(name
),
1633 slen
= strlen(name
)+strlen(state
)+2;
1634 s
= tor_malloc(slen
+1);
1635 tor_snprintf(s
, slen
, "%s %s", name
, state
);
1636 smartlist_add(status
, s
);
1638 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1639 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1640 smartlist_free(status
);
1641 } else if (!strcmpstart(question
, "addr-mappings/") ||
1642 !strcmpstart(question
, "address-mappings/")) {
1643 /* XXXX021 Warn about deprecated addr-mappings variant. */
1644 time_t min_e
, max_e
;
1645 smartlist_t
*mappings
;
1646 int want_expiry
= !strcmpstart(question
, "address-mappings/");
1647 question
+= strlen(want_expiry
? "address-mappings/"
1648 : "addr-mappings/");
1649 if (!strcmp(question
, "all")) {
1650 min_e
= 0; max_e
= TIME_MAX
;
1651 } else if (!strcmp(question
, "cache")) {
1652 min_e
= 2; max_e
= TIME_MAX
;
1653 } else if (!strcmp(question
, "config")) {
1654 min_e
= 0; max_e
= 0;
1655 } else if (!strcmp(question
, "control")) {
1656 min_e
= 1; max_e
= 1;
1660 mappings
= smartlist_create();
1661 addressmap_get_mappings(mappings
, min_e
, max_e
, want_expiry
);
1662 *answer
= smartlist_join_strings(mappings
, "\r\n", 0, NULL
);
1663 SMARTLIST_FOREACH(mappings
, char *, cp
, tor_free(cp
));
1664 smartlist_free(mappings
);
1665 } else if (!strcmpstart(question
, "status/")) {
1666 /* Note that status/ is not a catch-all for events; there's only supposed
1667 * to be a status GETINFO if there's a corresponding STATUS event. */
1668 if (!strcmp(question
, "status/circuit-established")) {
1669 *answer
= tor_strdup(has_completed_circuit
? "1" : "0");
1670 } else if (!strcmp(question
, "status/enough-dir-info")) {
1671 *answer
= tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
1672 } else if (!strcmp(question
, "status/good-server-descriptor")) {
1673 *answer
= tor_strdup(directories_have_accepted_server_descriptor()
1675 } else if (!strcmp(question
, "status/reachability-succeeded/or")) {
1676 *answer
= tor_strdup(check_whether_orport_reachable() ? "1" : "0");
1677 } else if (!strcmp(question
, "status/reachability-succeeded/dir")) {
1678 *answer
= tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
1679 } else if (!strcmp(question
, "status/reachability-succeeded")) {
1680 *answer
= tor_malloc(16);
1681 tor_snprintf(*answer
, 16, "OR=%d DIR=%d",
1682 check_whether_orport_reachable() ? 1 : 0,
1683 check_whether_dirport_reachable() ? 1 : 0);
1684 } else if (!strcmpstart(question
, "status/version/")) {
1685 int is_server
= server_mode(get_options());
1686 networkstatus_t
*c
= networkstatus_get_latest_consensus();
1687 version_status_t status
;
1688 const char *recommended
;
1690 recommended
= is_server
? c
->server_versions
: c
->client_versions
;
1691 status
= tor_version_is_obsolete(VERSION
, recommended
);
1694 status
= VS_UNKNOWN
;
1697 if (!strcmp(question
, "status/version/recommended")) {
1698 *answer
= tor_strdup(recommended
);
1701 if (!strcmp(question
, "status/version/current")) {
1704 case VS_RECOMMENDED
: *answer
= tor_strdup("recommended"); break;
1705 case VS_OLD
: *answer
= tor_strdup("obsolete"); break;
1706 case VS_NEW
: *answer
= tor_strdup("new"); break;
1707 case VS_NEW_IN_SERIES
: *answer
= tor_strdup("new in series"); break;
1708 case VS_UNRECOMMENDED
: *answer
= tor_strdup("unrecommended"); break;
1709 case VS_EMPTY
: *answer
= tor_strdup("none recommended"); break;
1710 case VS_UNKNOWN
: *answer
= tor_strdup("unknown"); break;
1711 default: tor_fragile_assert();
1713 } else if (!strcmp(question
, "status/version/num-versioning") ||
1714 !strcmp(question
, "status/version/num-concurring")) {
1716 tor_snprintf(s
, sizeof(s
), "%d", get_n_authorities(V3_AUTHORITY
));
1717 *answer
= tor_strdup(s
);
1718 log_warn(LD_GENERAL
, "%s is deprecated; it no longer gives useful "
1719 "information", question
);
1728 /** Callback function for GETINFO: on a given control connection, try to
1729 * answer the question <b>q</b> and store the newly-allocated answer in
1730 * *<b>a</b>. If there's no answer, or an error occurs, just don't set
1731 * <b>a</b>. Return 0.
1733 typedef int (*getinfo_helper_t
)(control_connection_t
*,
1734 const char *q
, char **a
);
1736 /** A single item for the GETINFO question-to-answer-function table. */
1737 typedef struct getinfo_item_t
{
1738 const char *varname
; /**< The value (or prefix) of the question. */
1739 getinfo_helper_t fn
; /**< The function that knows the answer: NULL if
1740 * this entry is documentation-only. */
1741 const char *desc
; /**< Description of the variable. */
1742 int is_prefix
; /** Must varname match exactly, or must it be a prefix? */
1745 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
1746 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
1747 #define DOC(name, desc) { name, NULL, desc, 0 }
1749 /** Table mapping questions accepted by GETINFO to the functions that know how
1750 * to answer them. */
1751 static const getinfo_item_t getinfo_items
[] = {
1752 ITEM("version", misc
, "The current version of Tor."),
1753 ITEM("config-file", misc
, "Current location of the \"torrc\" file."),
1754 ITEM("accounting/bytes", accounting
,
1755 "Number of bytes read/written so far in the accounting interval."),
1756 ITEM("accounting/bytes-left", accounting
,
1757 "Number of bytes left to write/read so far in the accounting interval."),
1758 ITEM("accounting/enabled", accounting
, "Is accounting currently enabled?"),
1759 ITEM("accounting/hibernating", accounting
, "Are we hibernating or awake?"),
1760 ITEM("accounting/interval-start", accounting
,
1761 "Time when the accounting period starts."),
1762 ITEM("accounting/interval-end", accounting
,
1763 "Time when the accounting period ends."),
1764 ITEM("accounting/interval-wake", accounting
,
1765 "Time to wake up in this accounting period."),
1766 ITEM("helper-nodes", entry_guards
, NULL
), /* deprecated */
1767 ITEM("entry-guards", entry_guards
,
1768 "Which nodes are we using as entry guards?"),
1769 ITEM("fingerprint", misc
, NULL
),
1770 PREFIX("config/", config
, "Current configuration values."),
1772 "List of configuration options, types, and documentation."),
1773 ITEM("info/names", misc
,
1774 "List of GETINFO options, types, and documentation."),
1775 ITEM("events/names", misc
,
1776 "Events that the controller can ask for with SETEVENTS."),
1777 ITEM("features/names", misc
, "What arguments can USEFEATURE take?"),
1778 PREFIX("desc/id/", dir
, "Router descriptors by ID."),
1779 PREFIX("desc/name/", dir
, "Router descriptors by nickname."),
1780 ITEM("desc/all-recent", dir
,
1781 "All non-expired, non-superseded router descriptors."),
1782 ITEM("desc/all-recent-extrainfo-hack", dir
, NULL
), /* Hack. */
1783 PREFIX("extra-info/digest/", dir
, "Extra-info documents by digest."),
1784 ITEM("ns/all", networkstatus
,
1785 "Brief summary of router status (v2 directory format)"),
1786 PREFIX("ns/id/", networkstatus
,
1787 "Brief summary of router status by ID (v2 directory format)."),
1788 PREFIX("ns/name/", networkstatus
,
1789 "Brief summary of router status by nickname (v2 directory format)."),
1790 PREFIX("ns/purpose/", networkstatus
,
1791 "Brief summary of router status by purpose (v2 directory format)."),
1793 PREFIX("unregistered-servers-", dirserv_unregistered
, NULL
),
1794 ITEM("network-status", dir
,
1795 "Brief summary of router status (v1 directory format)"),
1796 ITEM("circuit-status", events
, "List of current circuits originating here."),
1797 ITEM("stream-status", events
,"List of current streams."),
1798 ITEM("orconn-status", events
, "A list of current OR connections."),
1799 PREFIX("address-mappings/", events
, NULL
),
1800 DOC("address-mappings/all", "Current address mappings."),
1801 DOC("address-mappings/cache", "Current cached DNS replies."),
1802 DOC("address-mappings/config",
1803 "Current address mappings from configuration."),
1804 DOC("address-mappings/control", "Current address mappings from controller."),
1805 PREFIX("addr-mappings/", events
, NULL
),
1806 DOC("addr-mappings/all", "Current address mappings without expiry times."),
1807 DOC("addr-mappings/cache",
1808 "Current cached DNS replies without expiry times."),
1809 DOC("addr-mappings/config",
1810 "Current address mappings from configuration without expiry times."),
1811 DOC("addr-mappings/control",
1812 "Current address mappings from controller without expiry times."),
1813 PREFIX("status/", events
, NULL
),
1814 DOC("status/circuit-established",
1815 "Whether we think client functionality is working."),
1816 DOC("status/enough-dir-info",
1817 "Whether we have enough up-to-date directory information to build "
1819 DOC("status/version/recommended", "List of currently recommended versions."),
1820 DOC("status/version/current", "Status of the current version."),
1821 DOC("status/version/num-versioning", "Number of versioning authorities."),
1822 DOC("status/version/num-concurring",
1823 "Number of versioning authorities agreeing on the status of the "
1825 ITEM("address", misc
, "IP address of this Tor host, if we can guess it."),
1826 ITEM("dir-usage", misc
, "Breakdown of bytes transferred over DirPort."),
1827 PREFIX("desc-annotations/id/", dir
, "Router annotations by hexdigest."),
1828 PREFIX("dir/server/", dir
,"Router descriptors as retrieved from a DirPort."),
1829 PREFIX("dir/status/", dir
,"Networkstatus docs as retrieved from a DirPort."),
1830 PREFIX("exit-policy/default", policies
,
1831 "The default value appended to the configured exit policy."),
1832 PREFIX("ip-to-country/", geoip
, "Perform a GEOIP lookup"),
1833 { NULL
, NULL
, NULL
, 0 }
1836 /** Allocate and return a list of recognized GETINFO options. */
1838 list_getinfo_options(void)
1842 smartlist_t
*lines
= smartlist_create();
1844 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
1845 if (!getinfo_items
[i
].desc
)
1848 tor_snprintf(buf
, sizeof(buf
), "%s%s -- %s\n",
1849 getinfo_items
[i
].varname
,
1850 getinfo_items
[i
].is_prefix
? "*" : "",
1851 getinfo_items
[i
].desc
);
1852 smartlist_add(lines
, tor_strdup(buf
));
1854 smartlist_sort_strings(lines
);
1856 ans
= smartlist_join_strings(lines
, "", 0, NULL
);
1857 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
1858 smartlist_free(lines
);
1863 /** Lookup the 'getinfo' entry <b>question</b>, and return
1864 * the answer in <b>*answer</b> (or NULL if key not recognized).
1865 * Return 0 if success or unrecognized, or -1 if recognized but
1866 * internal error. */
1868 handle_getinfo_helper(control_connection_t
*control_conn
,
1869 const char *question
, char **answer
)
1872 *answer
= NULL
; /* unrecognized key by default */
1874 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
1876 if (getinfo_items
[i
].is_prefix
)
1877 match
= !strcmpstart(question
, getinfo_items
[i
].varname
);
1879 match
= !strcmp(question
, getinfo_items
[i
].varname
);
1881 tor_assert(getinfo_items
[i
].fn
);
1882 return getinfo_items
[i
].fn(control_conn
, question
, answer
);
1886 return 0; /* unrecognized */
1889 /** Called when we receive a GETINFO command. Try to fetch all requested
1890 * information, and reply with information or error message. */
1892 handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
1895 smartlist_t
*questions
= NULL
;
1896 smartlist_t
*answers
= NULL
;
1897 smartlist_t
*unrecognized
= NULL
;
1898 char *msg
= NULL
, *ans
= NULL
;
1900 (void) len
; /* body is nul-terminated, so it's safe to ignore the length. */
1902 questions
= smartlist_create();
1903 smartlist_split_string(questions
, body
, " ",
1904 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1905 answers
= smartlist_create();
1906 unrecognized
= smartlist_create();
1907 SMARTLIST_FOREACH(questions
, const char *, q
,
1909 if (handle_getinfo_helper(conn
, q
, &ans
) < 0) {
1910 connection_write_str_to_buf("551 Internal error\r\n", conn
);
1914 smartlist_add(unrecognized
, (char*)q
);
1916 smartlist_add(answers
, tor_strdup(q
));
1917 smartlist_add(answers
, ans
);
1920 if (smartlist_len(unrecognized
)) {
1921 for (i
=0; i
< smartlist_len(unrecognized
)-1; ++i
)
1922 connection_printf_to_buf(conn
,
1923 "552-Unrecognized key \"%s\"\r\n",
1924 (char*)smartlist_get(unrecognized
, i
));
1925 connection_printf_to_buf(conn
,
1926 "552 Unrecognized key \"%s\"\r\n",
1927 (char*)smartlist_get(unrecognized
, i
));
1931 for (i
= 0; i
< smartlist_len(answers
); i
+= 2) {
1932 char *k
= smartlist_get(answers
, i
);
1933 char *v
= smartlist_get(answers
, i
+1);
1934 if (!strchr(v
, '\n') && !strchr(v
, '\r')) {
1935 connection_printf_to_buf(conn
, "250-%s=", k
);
1936 connection_write_str_to_buf(v
, conn
);
1937 connection_write_str_to_buf("\r\n", conn
);
1941 esc_len
= write_escaped_data(v
, strlen(v
), &esc
);
1942 connection_printf_to_buf(conn
, "250+%s=\r\n", k
);
1943 connection_write_to_buf(esc
, esc_len
, TO_CONN(conn
));
1947 connection_write_str_to_buf("250 OK\r\n", conn
);
1951 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
1952 smartlist_free(answers
);
1955 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
1956 smartlist_free(questions
);
1958 smartlist_free(unrecognized
);
1964 /** Given a string, convert it to a circuit purpose. */
1966 circuit_purpose_from_string(const char *string
)
1968 if (!strcmpstart(string
, "purpose="))
1969 string
+= strlen("purpose=");
1971 if (!strcmp(string
, "general"))
1972 return CIRCUIT_PURPOSE_C_GENERAL
;
1973 else if (!strcmp(string
, "controller"))
1974 return CIRCUIT_PURPOSE_CONTROLLER
;
1976 return CIRCUIT_PURPOSE_UNKNOWN
;
1979 /** Return a newly allocated smartlist containing the arguments to the command
1980 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
1981 * or if <b>max_args</b> is nonnegative and there are more than
1982 * <b>max_args</b> arguments, send a 512 error to the controller, using
1983 * <b>command</b> as the command name in the error message. */
1984 static smartlist_t
*
1985 getargs_helper(const char *command
, control_connection_t
*conn
,
1986 const char *body
, int min_args
, int max_args
)
1988 smartlist_t
*args
= smartlist_create();
1989 smartlist_split_string(args
, body
, " ",
1990 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1991 if (smartlist_len(args
) < min_args
) {
1992 connection_printf_to_buf(conn
, "512 Missing argument to %s\r\n",command
);
1994 } else if (max_args
>= 0 && smartlist_len(args
) > max_args
) {
1995 connection_printf_to_buf(conn
, "512 Too many arguments to %s\r\n",command
);
2000 SMARTLIST_FOREACH(args
, char *, s
, tor_free(s
));
2001 smartlist_free(args
);
2005 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
2006 * circuit, and report success or failure. */
2008 handle_control_extendcircuit(control_connection_t
*conn
, uint32_t len
,
2011 smartlist_t
*router_nicknames
=NULL
, *routers
=NULL
;
2012 origin_circuit_t
*circ
= NULL
;
2014 uint8_t intended_purpose
= CIRCUIT_PURPOSE_C_GENERAL
;
2018 router_nicknames
= smartlist_create();
2020 args
= getargs_helper("EXTENDCIRCUIT", conn
, body
, 2, -1);
2024 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,0));
2025 if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
,0)))) {
2026 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2027 (char*)smartlist_get(args
, 0));
2029 smartlist_split_string(router_nicknames
, smartlist_get(args
,1), ",", 0, 0);
2031 if (zero_circ
&& smartlist_len(args
)>2) {
2032 char *purp
= smartlist_get(args
,2);
2033 intended_purpose
= circuit_purpose_from_string(purp
);
2034 if (intended_purpose
== CIRCUIT_PURPOSE_UNKNOWN
) {
2035 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
2036 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2037 smartlist_free(args
);
2041 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2042 smartlist_free(args
);
2043 if (!zero_circ
&& !circ
) {
2047 routers
= smartlist_create();
2048 SMARTLIST_FOREACH(router_nicknames
, const char *, n
,
2050 routerinfo_t
*r
= router_get_by_nickname(n
, 1);
2052 connection_printf_to_buf(conn
, "552 No such router \"%s\"\r\n", n
);
2055 smartlist_add(routers
, r
);
2057 if (!smartlist_len(routers
)) {
2058 connection_write_str_to_buf("512 No router names provided\r\n", conn
);
2063 /* start a new circuit */
2064 circ
= origin_circuit_init(intended_purpose
, 0);
2067 /* now circ refers to something that is ready to be extended */
2068 SMARTLIST_FOREACH(routers
, routerinfo_t
*, r
,
2070 extend_info_t
*info
= extend_info_from_router(r
);
2071 circuit_append_new_exit(circ
, info
);
2072 extend_info_free(info
);
2075 /* now that we've populated the cpath, start extending */
2078 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
2079 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
2080 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
2084 if (circ
->_base
.state
== CIRCUIT_STATE_OPEN
) {
2086 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
2087 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
2088 log_info(LD_CONTROL
,
2089 "send_next_onion_skin failed; circuit marked for closing.");
2090 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
2091 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn
);
2097 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
2098 (unsigned long)circ
->global_identifier
);
2099 if (zero_circ
) /* send a 'launched' event, for completeness */
2100 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
2102 SMARTLIST_FOREACH(router_nicknames
, char *, n
, tor_free(n
));
2103 smartlist_free(router_nicknames
);
2105 smartlist_free(routers
);
2109 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
2110 * circuit and it's a valid purpose, change it. */
2112 handle_control_setcircuitpurpose(control_connection_t
*conn
,
2113 uint32_t len
, const char *body
)
2115 origin_circuit_t
*circ
= NULL
;
2116 uint8_t new_purpose
;
2118 (void) len
; /* body is nul-terminated, so it's safe to ignore the length. */
2120 args
= getargs_helper("SETCIRCUITPURPOSE", conn
, body
, 2, -1);
2124 if (!(circ
= get_circ(smartlist_get(args
,0)))) {
2125 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2126 (char*)smartlist_get(args
, 0));
2131 char *purp
= smartlist_get(args
,1);
2132 new_purpose
= circuit_purpose_from_string(purp
);
2133 if (new_purpose
== CIRCUIT_PURPOSE_UNKNOWN
) {
2134 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
2139 circ
->_base
.purpose
= new_purpose
;
2140 connection_write_str_to_buf("250 OK\r\n", conn
);
2144 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2145 smartlist_free(args
);
2150 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
2151 * stream, and report success or failure. */
2153 handle_control_attachstream(control_connection_t
*conn
, uint32_t len
,
2156 edge_connection_t
*ap_conn
= NULL
;
2157 origin_circuit_t
*circ
= NULL
;
2160 crypt_path_t
*cpath
=NULL
;
2161 int hop
=0, hop_line_ok
=1;
2164 args
= getargs_helper("ATTACHSTREAM", conn
, body
, 2, -1);
2168 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,1));
2170 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))) {
2171 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2172 (char*)smartlist_get(args
, 0));
2173 } else if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
, 1)))) {
2174 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2175 (char*)smartlist_get(args
, 1));
2176 } else if (circ
&& smartlist_len(args
) > 2) {
2177 char *hopstring
= smartlist_get(args
, 2);
2178 if (!strcasecmpstart(hopstring
, "HOP=")) {
2179 hopstring
+= strlen("HOP=");
2180 hop
= tor_parse_ulong(hopstring
, 10, 0, ULONG_MAX
,
2181 &hop_line_ok
, NULL
);
2182 if (!hop_line_ok
) { /* broken hop line */
2183 connection_printf_to_buf(conn
, "552 Bad value hop=%s\r\n", hopstring
);
2187 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2188 smartlist_free(args
);
2189 if (!ap_conn
|| (!zero_circ
&& !circ
) || !hop_line_ok
)
2192 if (ap_conn
->_base
.state
!= AP_CONN_STATE_CONTROLLER_WAIT
&&
2193 ap_conn
->_base
.state
!= AP_CONN_STATE_CONNECT_WAIT
&&
2194 ap_conn
->_base
.state
!= AP_CONN_STATE_RESOLVE_WAIT
) {
2195 connection_write_str_to_buf(
2196 "555 Connection is not managed by controller.\r\n",
2201 /* Do we need to detach it first? */
2202 if (ap_conn
->_base
.state
!= AP_CONN_STATE_CONTROLLER_WAIT
) {
2203 circuit_t
*tmpcirc
= circuit_get_by_edge_conn(ap_conn
);
2204 connection_edge_end(ap_conn
, END_STREAM_REASON_TIMEOUT
);
2205 /* Un-mark it as ending, since we're going to reuse it. */
2206 ap_conn
->_base
.edge_has_sent_end
= 0;
2207 ap_conn
->end_reason
= 0;
2209 circuit_detach_stream(tmpcirc
,ap_conn
);
2210 ap_conn
->_base
.state
= AP_CONN_STATE_CONTROLLER_WAIT
;
2213 if (circ
&& (circ
->_base
.state
!= CIRCUIT_STATE_OPEN
)) {
2214 connection_write_str_to_buf(
2215 "551 Can't attach stream to non-open origin circuit\r\n",
2219 if (circ
&& (circuit_get_cpath_len(circ
)<2 || hop
==1)) {
2220 connection_write_str_to_buf(
2221 "551 Can't attach stream to one-hop circuit.\r\n", conn
);
2224 if (circ
&& hop
>0) {
2225 /* find this hop in the circuit, and set cpath */
2226 cpath
= circuit_get_cpath_hop(circ
, hop
);
2228 connection_printf_to_buf(conn
,
2229 "551 Circuit doesn't have %d hops.\r\n", hop
);
2233 if (connection_ap_handshake_rewrite_and_attach(ap_conn
, circ
, cpath
) < 0) {
2234 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn
);
2237 send_control_done(conn
);
2241 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
2242 * descriptor, and report success or failure. */
2244 handle_control_postdescriptor(control_connection_t
*conn
, uint32_t len
,
2248 const char *msg
=NULL
;
2249 uint8_t purpose
= ROUTER_PURPOSE_GENERAL
;
2250 int cache
= 0; /* eventually, we may switch this to 1 */
2252 char *cp
= memchr(body
, '\n', len
);
2253 smartlist_t
*args
= smartlist_create();
2257 smartlist_split_string(args
, body
, " ",
2258 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2259 SMARTLIST_FOREACH(args
, char *, option
,
2261 if (!strcasecmpstart(option
, "purpose=")) {
2262 option
+= strlen("purpose=");
2263 purpose
= router_purpose_from_string(option
);
2264 if (purpose
== ROUTER_PURPOSE_UNKNOWN
) {
2265 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n",
2269 } else if (!strcasecmpstart(option
, "cache=")) {
2270 option
+= strlen("cache=");
2271 if (!strcmp(option
, "no"))
2273 else if (!strcmp(option
, "yes"))
2276 connection_printf_to_buf(conn
, "552 Unknown cache request \"%s\"\r\n",
2280 } else { /* unrecognized argument? */
2281 connection_printf_to_buf(conn
,
2282 "512 Unexpected argument \"%s\" to postdescriptor\r\n", option
);
2287 read_escaped_data(cp
, len
-(cp
-body
), &desc
);
2289 switch (router_load_single_router(desc
, purpose
, cache
, &msg
)) {
2291 if (!msg
) msg
= "Could not parse descriptor";
2292 connection_printf_to_buf(conn
, "554 %s\r\n", msg
);
2295 if (!msg
) msg
= "Descriptor not added";
2296 connection_printf_to_buf(conn
, "251 %s\r\n",msg
);
2299 send_control_done(conn
);
2305 SMARTLIST_FOREACH(args
, char *, arg
, tor_free(arg
));
2306 smartlist_free(args
);
2310 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
2311 * address of the named AP stream, and report success or failure. */
2313 handle_control_redirectstream(control_connection_t
*conn
, uint32_t len
,
2316 edge_connection_t
*ap_conn
= NULL
;
2317 char *new_addr
= NULL
;
2318 uint16_t new_port
= 0;
2322 args
= getargs_helper("REDIRECTSTREAM", conn
, body
, 2, -1);
2326 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))
2327 || !ap_conn
->socks_request
) {
2328 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2329 (char*)smartlist_get(args
, 0));
2332 if (smartlist_len(args
) > 2) { /* they included a port too */
2333 new_port
= (uint16_t) tor_parse_ulong(smartlist_get(args
, 2),
2334 10, 1, 65535, &ok
, NULL
);
2337 connection_printf_to_buf(conn
, "512 Cannot parse port \"%s\"\r\n",
2338 (char*)smartlist_get(args
, 2));
2340 new_addr
= tor_strdup(smartlist_get(args
, 1));
2344 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2345 smartlist_free(args
);
2349 strlcpy(ap_conn
->socks_request
->address
, new_addr
,
2350 sizeof(ap_conn
->socks_request
->address
));
2352 ap_conn
->socks_request
->port
= new_port
;
2354 send_control_done(conn
);
2358 /** Called when we get a CLOSESTREAM command; try to close the named stream
2359 * and report success or failure. */
2361 handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
2364 edge_connection_t
*ap_conn
=NULL
;
2370 args
= getargs_helper("CLOSESTREAM", conn
, body
, 2, -1);
2374 else if (!(ap_conn
= get_stream(smartlist_get(args
, 0))))
2375 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2376 (char*)smartlist_get(args
, 0));
2378 reason
= (uint8_t) tor_parse_ulong(smartlist_get(args
,1), 10, 0, 255,
2381 connection_printf_to_buf(conn
, "552 Unrecognized reason \"%s\"\r\n",
2382 (char*)smartlist_get(args
, 1));
2386 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2387 smartlist_free(args
);
2391 connection_mark_unattached_ap(ap_conn
, reason
);
2392 send_control_done(conn
);
2396 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
2397 * and report success or failure. */
2399 handle_control_closecircuit(control_connection_t
*conn
, uint32_t len
,
2402 origin_circuit_t
*circ
= NULL
;
2407 args
= getargs_helper("CLOSECIRCUIT", conn
, body
, 1, -1);
2411 if (!(circ
=get_circ(smartlist_get(args
, 0))))
2412 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2413 (char*)smartlist_get(args
, 0));
2416 for (i
=1; i
< smartlist_len(args
); ++i
) {
2417 if (!strcasecmp(smartlist_get(args
, i
), "IfUnused"))
2420 log_info(LD_CONTROL
, "Skipping unknown option %s",
2421 (char*)smartlist_get(args
,i
));
2424 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2425 smartlist_free(args
);
2429 if (!safe
|| !circ
->p_streams
) {
2430 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_REQUESTED
);
2433 send_control_done(conn
);
2437 /** Called when we get a RESOLVE command: start trying to resolve
2438 * the listed addresses. */
2440 handle_control_resolve(control_connection_t
*conn
, uint32_t len
,
2443 smartlist_t
*args
, *failed
;
2445 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
2447 if (!(conn
->event_mask
& (1L<<EVENT_ADDRMAP
))) {
2448 log_warn(LD_CONTROL
, "Controller asked us to resolve an address, but "
2449 "isn't listening for ADDRMAP events. It probably won't see "
2452 args
= smartlist_create();
2453 smartlist_split_string(args
, body
, " ",
2454 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2455 if (smartlist_len(args
) &&
2456 !strcasecmp(smartlist_get(args
, 0), "mode=reverse")) {
2457 char *cp
= smartlist_get(args
, 0);
2458 smartlist_del_keeporder(args
, 0);
2462 failed
= smartlist_create();
2463 SMARTLIST_FOREACH(args
, const char *, arg
, {
2464 if (dnsserv_launch_request(arg
, is_reverse
)<0)
2465 smartlist_add(failed
, (char*)arg
);
2468 send_control_done(conn
);
2469 SMARTLIST_FOREACH(failed
, const char *, arg
, {
2470 control_event_address_mapped(arg
, arg
, time(NULL
),
2471 "Unable to launch resolve request");
2474 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2475 smartlist_free(args
);
2476 smartlist_free(failed
);
2480 /** Called when we get a PROTOCOLINFO command: send back a reply. */
2482 handle_control_protocolinfo(control_connection_t
*conn
, uint32_t len
,
2485 const char *bad_arg
= NULL
;
2489 conn
->have_sent_protocolinfo
= 1;
2490 args
= smartlist_create();
2491 smartlist_split_string(args
, body
, " ",
2492 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2493 SMARTLIST_FOREACH(args
, const char *, arg
, {
2495 tor_parse_long(arg
, 10, 0, LONG_MAX
, &ok
, NULL
);
2502 connection_printf_to_buf(conn
, "513 No such version %s\r\n",
2504 /* Don't tolerate bad arguments when not authenticated. */
2505 if (!STATE_IS_OPEN(TO_CONN(conn
)->state
))
2506 connection_mark_for_close(TO_CONN(conn
));
2509 or_options_t
*options
= get_options();
2510 int cookies
= options
->CookieAuthentication
;
2511 char *cfile
= get_cookie_file();
2512 char *esc_cfile
= esc_for_log(cfile
);
2515 int passwd
= (options
->HashedControlPassword
!= NULL
);
2516 smartlist_t
*mlist
= smartlist_create();
2518 smartlist_add(mlist
, (char*)"COOKIE");
2520 smartlist_add(mlist
, (char*)"HASHEDPASSWORD");
2521 if (!cookies
&& !passwd
)
2522 smartlist_add(mlist
, (char*)"NULL");
2523 methods
= smartlist_join_strings(mlist
, ",", 0, NULL
);
2524 smartlist_free(mlist
);
2527 connection_printf_to_buf(conn
,
2528 "250-PROTOCOLINFO 1\r\n"
2529 "250-AUTH METHODS=%s%s%s\r\n"
2530 "250-VERSION Tor=%s\r\n"
2533 cookies
?" COOKIEFILE=":"",
2534 cookies
?esc_cfile
:"",
2538 tor_free(esc_cfile
);
2541 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2542 smartlist_free(args
);
2546 /** Called when we get a USEFEATURE command: parse the feature list, and
2547 * set up the control_connection's options properly. */
2549 handle_control_usefeature(control_connection_t
*conn
,
2554 int verbose_names
= 0, extended_events
= 0;
2556 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
2557 args
= smartlist_create();
2558 smartlist_split_string(args
, body
, " ",
2559 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2560 SMARTLIST_FOREACH(args
, const char *, arg
, {
2561 if (!strcasecmp(arg
, "VERBOSE_NAMES"))
2563 else if (!strcasecmp(arg
, "EXTENDED_EVENTS")) /* <- documented */
2564 extended_events
= 1;
2565 else if (!strcasecmp(arg
, "EXTENDED_FORMAT")) {
2566 /* remove this in 0.1.2.4; EXTENDED_FORMAT only ever worked for a
2567 * little while during 0.1.2.2-alpha-dev. */
2568 log_warn(LD_GENERAL
,
2569 "EXTENDED_FORMAT is deprecated; use EXTENDED_EVENTS "
2571 extended_events
= 1;
2573 connection_printf_to_buf(conn
, "552 Unrecognized feature \"%s\"\r\n",
2581 if (verbose_names
) {
2582 conn
->use_long_names
= 1;
2583 control_update_global_event_mask();
2585 if (extended_events
)
2586 conn
->use_extended_events
= 1;
2587 send_control_done(conn
);
2590 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2591 smartlist_free(args
);
2595 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
2597 connection_control_finished_flushing(control_connection_t
*conn
)
2601 connection_stop_writing(TO_CONN(conn
));
2605 /** Called when <b>conn</b> has gotten its socket closed. */
2607 connection_control_reached_eof(control_connection_t
*conn
)
2611 log_info(LD_CONTROL
,"Control connection reached EOF. Closing.");
2612 connection_mark_for_close(TO_CONN(conn
));
2616 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
2617 * stage of the protocol. */
2619 is_valid_initial_command(control_connection_t
*conn
, const char *cmd
)
2621 if (conn
->_base
.state
== CONTROL_CONN_STATE_OPEN
)
2623 if (!strcasecmp(cmd
, "PROTOCOLINFO"))
2624 return !conn
->have_sent_protocolinfo
;
2625 if (!strcasecmp(cmd
, "AUTHENTICATE") ||
2626 !strcasecmp(cmd
, "QUIT"))
2631 /** Do not accept any control command of more than 1MB in length. Anything
2632 * that needs to be anywhere near this long probably means that one of our
2633 * interfaces is broken. */
2634 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
2636 /** Called when data has arrived on a v1 control connection: Try to fetch
2637 * commands from conn->inbuf, and execute them.
2640 connection_control_process_inbuf(control_connection_t
*conn
)
2647 tor_assert(conn
->_base
.state
== CONTROL_CONN_STATE_OPEN
||
2648 conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH
);
2650 if (!conn
->incoming_cmd
) {
2651 conn
->incoming_cmd
= tor_malloc(1024);
2652 conn
->incoming_cmd_len
= 1024;
2653 conn
->incoming_cmd_cur_len
= 0;
2656 if (conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
2657 peek_buf_has_control0_command(conn
->_base
.inbuf
)) {
2658 /* Detect v0 commands and send a "no more v0" message. */
2661 set_uint16(buf
+2, htons(0x0000)); /* type == error */
2662 set_uint16(buf
+4, htons(0x0001)); /* code == internal error */
2663 strlcpy(buf
+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
2664 "and later; upgrade your controller.",
2666 body_len
= 2+strlen(buf
+6)+2; /* code, msg, nul. */
2667 set_uint16(buf
+0, htons(body_len
));
2668 connection_write_to_buf(buf
, 4+body_len
, TO_CONN(conn
));
2669 connection_mark_for_close(TO_CONN(conn
));
2670 conn
->_base
.hold_open_until_flushed
= 1;
2678 /* First, fetch a line. */
2680 data_len
= conn
->incoming_cmd_len
- conn
->incoming_cmd_cur_len
;
2681 r
= fetch_from_buf_line(conn
->_base
.inbuf
,
2682 conn
->incoming_cmd
+conn
->incoming_cmd_cur_len
,
2685 /* Line not all here yet. Wait. */
2688 if (data_len
+ conn
->incoming_cmd_cur_len
> MAX_COMMAND_LINE_LENGTH
) {
2689 connection_write_str_to_buf("500 Line too long.\r\n", conn
);
2690 connection_stop_reading(TO_CONN(conn
));
2691 connection_mark_for_close(TO_CONN(conn
));
2692 conn
->_base
.hold_open_until_flushed
= 1;
2694 while (conn
->incoming_cmd_len
< data_len
+conn
->incoming_cmd_cur_len
)
2695 conn
->incoming_cmd_len
*= 2;
2696 conn
->incoming_cmd
= tor_realloc(conn
->incoming_cmd
,
2697 conn
->incoming_cmd_len
);
2701 tor_assert(data_len
);
2703 last_idx
= conn
->incoming_cmd_cur_len
;
2704 conn
->incoming_cmd_cur_len
+= data_len
;
2706 /* We have appended a line to incoming_cmd. Is the command done? */
2707 if (last_idx
== 0 && *conn
->incoming_cmd
!= '+')
2708 /* One line command, didn't start with '+'. */
2710 /* XXXX this code duplication is kind of dumb. */
2711 if (last_idx
+3 == conn
->incoming_cmd_cur_len
&&
2712 !memcmp(conn
->incoming_cmd
+ last_idx
, ".\r\n", 3)) {
2713 /* Just appended ".\r\n"; we're done. Remove it. */
2714 conn
->incoming_cmd_cur_len
-= 3;
2716 } else if (last_idx
+2 == conn
->incoming_cmd_cur_len
&&
2717 !memcmp(conn
->incoming_cmd
+ last_idx
, ".\n", 2)) {
2718 /* Just appended ".\n"; we're done. Remove it. */
2719 conn
->incoming_cmd_cur_len
-= 2;
2722 /* Otherwise, read another line. */
2724 data_len
= conn
->incoming_cmd_cur_len
;
2725 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
2729 while ((size_t)cmd_len
< data_len
2730 && !TOR_ISSPACE(conn
->incoming_cmd
[cmd_len
]))
2733 data_len
-= cmd_len
;
2734 conn
->incoming_cmd
[cmd_len
]='\0';
2735 args
= conn
->incoming_cmd
+cmd_len
+1;
2736 while (*args
== ' ' || *args
== '\t') {
2741 /* Quit is always valid. */
2742 if (!strcasecmp(conn
->incoming_cmd
, "QUIT")) {
2743 connection_write_str_to_buf("250 closing connection\r\n", conn
);
2744 connection_mark_for_close(TO_CONN(conn
));
2748 if (conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH
&&
2749 !is_valid_initial_command(conn
, conn
->incoming_cmd
)) {
2750 connection_write_str_to_buf("514 Authentication required.\r\n", conn
);
2751 connection_mark_for_close(TO_CONN(conn
));
2755 if (!strcasecmp(conn
->incoming_cmd
, "SETCONF")) {
2756 if (handle_control_setconf(conn
, data_len
, args
))
2758 } else if (!strcasecmp(conn
->incoming_cmd
, "RESETCONF")) {
2759 if (handle_control_resetconf(conn
, data_len
, args
))
2761 } else if (!strcasecmp(conn
->incoming_cmd
, "GETCONF")) {
2762 if (handle_control_getconf(conn
, data_len
, args
))
2764 } else if (!strcasecmp(conn
->incoming_cmd
, "SETEVENTS")) {
2765 if (handle_control_setevents(conn
, data_len
, args
))
2767 } else if (!strcasecmp(conn
->incoming_cmd
, "AUTHENTICATE")) {
2768 if (handle_control_authenticate(conn
, data_len
, args
))
2770 } else if (!strcasecmp(conn
->incoming_cmd
, "SAVECONF")) {
2771 if (handle_control_saveconf(conn
, data_len
, args
))
2773 } else if (!strcasecmp(conn
->incoming_cmd
, "SIGNAL")) {
2774 if (handle_control_signal(conn
, data_len
, args
))
2776 } else if (!strcasecmp(conn
->incoming_cmd
, "MAPADDRESS")) {
2777 if (handle_control_mapaddress(conn
, data_len
, args
))
2779 } else if (!strcasecmp(conn
->incoming_cmd
, "GETINFO")) {
2780 if (handle_control_getinfo(conn
, data_len
, args
))
2782 } else if (!strcasecmp(conn
->incoming_cmd
, "EXTENDCIRCUIT")) {
2783 if (handle_control_extendcircuit(conn
, data_len
, args
))
2785 } else if (!strcasecmp(conn
->incoming_cmd
, "SETCIRCUITPURPOSE")) {
2786 if (handle_control_setcircuitpurpose(conn
, data_len
, args
))
2788 } else if (!strcasecmp(conn
->incoming_cmd
, "SETROUTERPURPOSE")) {
2789 connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn
);
2790 } else if (!strcasecmp(conn
->incoming_cmd
, "ATTACHSTREAM")) {
2791 if (handle_control_attachstream(conn
, data_len
, args
))
2793 } else if (!strcasecmp(conn
->incoming_cmd
, "+POSTDESCRIPTOR")) {
2794 if (handle_control_postdescriptor(conn
, data_len
, args
))
2796 } else if (!strcasecmp(conn
->incoming_cmd
, "REDIRECTSTREAM")) {
2797 if (handle_control_redirectstream(conn
, data_len
, args
))
2799 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSESTREAM")) {
2800 if (handle_control_closestream(conn
, data_len
, args
))
2802 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSECIRCUIT")) {
2803 if (handle_control_closecircuit(conn
, data_len
, args
))
2805 } else if (!strcasecmp(conn
->incoming_cmd
, "USEFEATURE")) {
2806 if (handle_control_usefeature(conn
, data_len
, args
))
2808 } else if (!strcasecmp(conn
->incoming_cmd
, "RESOLVE")) {
2809 if (handle_control_resolve(conn
, data_len
, args
))
2811 } else if (!strcasecmp(conn
->incoming_cmd
, "PROTOCOLINFO")) {
2812 if (handle_control_protocolinfo(conn
, data_len
, args
))
2815 connection_printf_to_buf(conn
, "510 Unrecognized command \"%s\"\r\n",
2816 conn
->incoming_cmd
);
2819 conn
->incoming_cmd_cur_len
= 0;
2823 /** Convert a numeric reason for destroying a circuit into a string for a
2826 circuit_end_reason_to_string(int reason
)
2828 if (reason
>= 0 && reason
& END_CIRC_REASON_FLAG_REMOTE
)
2829 reason
&= ~END_CIRC_REASON_FLAG_REMOTE
;
2831 case END_CIRC_AT_ORIGIN
:
2832 /* This shouldn't get passed here; it's a catch-all reason. */
2834 case END_CIRC_REASON_NONE
:
2835 /* This shouldn't get passed here; it's a catch-all reason. */
2837 case END_CIRC_REASON_TORPROTOCOL
:
2838 return "TORPROTOCOL";
2839 case END_CIRC_REASON_INTERNAL
:
2841 case END_CIRC_REASON_REQUESTED
:
2843 case END_CIRC_REASON_HIBERNATING
:
2844 return "HIBERNATING";
2845 case END_CIRC_REASON_RESOURCELIMIT
:
2846 return "RESOURCELIMIT";
2847 case END_CIRC_REASON_CONNECTFAILED
:
2848 return "CONNECTFAILED";
2849 case END_CIRC_REASON_OR_IDENTITY
:
2850 return "OR_IDENTITY";
2851 case END_CIRC_REASON_OR_CONN_CLOSED
:
2852 return "OR_CONN_CLOSED";
2853 case END_CIRC_REASON_FINISHED
:
2855 case END_CIRC_REASON_TIMEOUT
:
2857 case END_CIRC_REASON_DESTROYED
:
2859 case END_CIRC_REASON_NOPATH
:
2861 case END_CIRC_REASON_NOSUCHSERVICE
:
2862 return "NOSUCHSERVICE";
2864 log_warn(LD_BUG
, "Unrecognized reason code %d", (int)reason
);
2869 /** Something has happened to circuit <b>circ</b>: tell any interested
2870 * control connections. */
2872 control_event_circuit_status(origin_circuit_t
*circ
, circuit_status_event_t tp
,
2876 char reason_buf
[64];
2877 int providing_reason
=0;
2879 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS
))
2883 if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS
))
2884 path
= circuit_list_path(circ
,0);
2888 case CIRC_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
2889 case CIRC_EVENT_BUILT
: status
= "BUILT"; break;
2890 case CIRC_EVENT_EXTENDED
: status
= "EXTENDED"; break;
2891 case CIRC_EVENT_FAILED
: status
= "FAILED"; break;
2892 case CIRC_EVENT_CLOSED
: status
= "CLOSED"; break;
2894 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
2898 if (tp
== CIRC_EVENT_FAILED
|| tp
== CIRC_EVENT_CLOSED
) {
2899 const char *reason_str
= circuit_end_reason_to_string(reason_code
);
2900 char *reason
= NULL
;
2903 reason
= tor_malloc(16);
2904 tor_snprintf(reason
, 16, "UNKNOWN_%d", reason_code
);
2905 reason_str
= reason
;
2907 if (reason_code
> 0 && reason_code
& END_CIRC_REASON_FLAG_REMOTE
) {
2908 tor_snprintf(reason_buf
, sizeof(reason_buf
),
2909 "REASON=DESTROYED REMOTE_REASON=%s", reason_str
);
2911 tor_snprintf(reason_buf
, sizeof(reason_buf
),
2912 "REASON=%s", reason_str
);
2917 if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS
)) {
2918 const char *sp
= strlen(path
) ? " " : "";
2919 if (providing_reason
)
2920 send_control_event_extended(EVENT_CIRCUIT_STATUS
, SHORT_NAMES
,
2921 "650 CIRC %lu %s%s%s@%s\r\n",
2922 (unsigned long)circ
->global_identifier
,
2923 status
, sp
, path
, reason_buf
);
2925 send_control_event_extended(EVENT_CIRCUIT_STATUS
, SHORT_NAMES
,
2926 "650 CIRC %lu %s%s%s\r\n",
2927 (unsigned long)circ
->global_identifier
,
2930 if (EVENT_IS_INTERESTING1L(EVENT_CIRCUIT_STATUS
)) {
2931 char *vpath
= circuit_list_path_for_controller(circ
);
2932 const char *sp
= strlen(vpath
) ? " " : "";
2933 if (providing_reason
)
2934 send_control_event_extended(EVENT_CIRCUIT_STATUS
, LONG_NAMES
,
2935 "650 CIRC %lu %s%s%s@%s\r\n",
2936 (unsigned long)circ
->global_identifier
,
2937 status
, sp
, vpath
, reason_buf
);
2939 send_control_event_extended(EVENT_CIRCUIT_STATUS
, LONG_NAMES
,
2940 "650 CIRC %lu %s%s%s\r\n",
2941 (unsigned long)circ
->global_identifier
,
2951 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
2952 * <b>buf</b>, determine the address:port combination requested on
2953 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
2956 write_stream_target_to_buf(edge_connection_t
*conn
, char *buf
, size_t len
)
2959 if (conn
->chosen_exit_name
)
2960 if (tor_snprintf(buf2
, sizeof(buf2
), ".%s.exit", conn
->chosen_exit_name
)<0)
2962 if (tor_snprintf(buf
, len
, "%s%s%s:%d",
2963 conn
->socks_request
->address
,
2964 conn
->chosen_exit_name
? buf2
: "",
2965 !conn
->chosen_exit_name
&&
2966 connection_edge_is_rendezvous_stream(conn
) ? ".onion" : "",
2967 conn
->socks_request
->port
)<0)
2972 /** Convert the reason for ending a stream <b>reason</b> into the format used
2973 * in STREAM events. Return NULL if the reason is unrecognized. */
2975 stream_end_reason_to_string(int reason
)
2977 reason
&= END_STREAM_REASON_MASK
;
2979 case END_STREAM_REASON_MISC
: return "MISC";
2980 case END_STREAM_REASON_RESOLVEFAILED
: return "RESOLVEFAILED";
2981 case END_STREAM_REASON_CONNECTREFUSED
: return "CONNECTREFUSED";
2982 case END_STREAM_REASON_EXITPOLICY
: return "EXITPOLICY";
2983 case END_STREAM_REASON_DESTROY
: return "DESTROY";
2984 case END_STREAM_REASON_DONE
: return "DONE";
2985 case END_STREAM_REASON_TIMEOUT
: return "TIMEOUT";
2986 case END_STREAM_REASON_HIBERNATING
: return "HIBERNATING";
2987 case END_STREAM_REASON_INTERNAL
: return "INTERNAL";
2988 case END_STREAM_REASON_RESOURCELIMIT
: return "RESOURCELIMIT";
2989 case END_STREAM_REASON_CONNRESET
: return "CONNRESET";
2990 case END_STREAM_REASON_TORPROTOCOL
: return "TORPROTOCOL";
2991 case END_STREAM_REASON_NOTDIRECTORY
: return "NOTDIRECTORY";
2993 case END_STREAM_REASON_CANT_ATTACH
: return "CANT_ATTACH";
2994 case END_STREAM_REASON_NET_UNREACHABLE
: return "NET_UNREACHABLE";
2995 case END_STREAM_REASON_SOCKSPROTOCOL
: return "SOCKS_PROTOCOL";
2997 default: return NULL
;
3001 /** Something has happened to the stream associated with AP connection
3002 * <b>conn</b>: tell any interested control connections. */
3004 control_event_stream_status(edge_connection_t
*conn
, stream_status_event_t tp
,
3007 char reason_buf
[64];
3008 char addrport_buf
[64];
3011 origin_circuit_t
*origin_circ
= NULL
;
3013 tor_assert(conn
->socks_request
);
3015 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS
))
3018 if (tp
== STREAM_EVENT_CLOSED
&&
3019 (reason_code
& END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
))
3022 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
3024 reason_buf
[0] = '\0';
3027 case STREAM_EVENT_SENT_CONNECT
: status
= "SENTCONNECT"; break;
3028 case STREAM_EVENT_SENT_RESOLVE
: status
= "SENTRESOLVE"; break;
3029 case STREAM_EVENT_SUCCEEDED
: status
= "SUCCEEDED"; break;
3030 case STREAM_EVENT_FAILED
: status
= "FAILED"; break;
3031 case STREAM_EVENT_CLOSED
: status
= "CLOSED"; break;
3032 case STREAM_EVENT_NEW
: status
= "NEW"; break;
3033 case STREAM_EVENT_NEW_RESOLVE
: status
= "NEWRESOLVE"; break;
3034 case STREAM_EVENT_FAILED_RETRIABLE
: status
= "DETACHED"; break;
3035 case STREAM_EVENT_REMAP
: status
= "REMAP"; break;
3037 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3040 if (reason_code
&& (tp
== STREAM_EVENT_FAILED
||
3041 tp
== STREAM_EVENT_CLOSED
||
3042 tp
== STREAM_EVENT_FAILED_RETRIABLE
)) {
3043 const char *reason_str
= stream_end_reason_to_string(reason_code
);
3047 tor_snprintf(r
, 16, "UNKNOWN_%d", reason_code
);
3050 if (reason_code
& END_STREAM_REASON_FLAG_REMOTE
)
3051 tor_snprintf(reason_buf
, sizeof(reason_buf
),
3052 "REASON=END REMOTE_REASON=%s", reason_str
);
3054 tor_snprintf(reason_buf
, sizeof(reason_buf
),
3055 "REASON=%s", reason_str
);
3057 } else if (reason_code
&& tp
== STREAM_EVENT_REMAP
) {
3058 switch (reason_code
) {
3059 case REMAP_STREAM_SOURCE_CACHE
:
3060 strlcpy(reason_buf
, "SOURCE=CACHE", sizeof(reason_buf
));
3062 case REMAP_STREAM_SOURCE_EXIT
:
3063 strlcpy(reason_buf
, "SOURCE=EXIT", sizeof(reason_buf
));
3066 tor_snprintf(reason_buf
, sizeof(reason_buf
), "REASON=UNKNOWN_%d",
3072 if (tp
== STREAM_EVENT_NEW
) {
3073 tor_snprintf(addrport_buf
,sizeof(addrport_buf
), "%sSOURCE_ADDR=%s:%d",
3074 strlen(reason_buf
) ? " " : "",
3075 TO_CONN(conn
)->address
, TO_CONN(conn
)->port
);
3077 addrport_buf
[0] = '\0';
3080 circ
= circuit_get_by_edge_conn(conn
);
3081 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
3082 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
3083 send_control_event_extended(EVENT_STREAM_STATUS
, ALL_NAMES
,
3084 "650 STREAM %lu %s %lu %s@%s%s\r\n",
3085 (unsigned long)conn
->global_identifier
, status
,
3087 (unsigned long)origin_circ
->global_identifier
: 0ul,
3088 buf
, reason_buf
, addrport_buf
);
3090 /* XXX need to specify its intended exit, etc? */
3095 /** Figure out the best name for the target router of an OR connection
3096 * <b>conn</b>, and write it into the <b>len</b>-character buffer
3097 * <b>name</b>. Use verbose names if <b>long_names</b> is set. */
3099 orconn_target_get_name(int long_names
,
3100 char *name
, size_t len
, or_connection_t
*conn
)
3104 strlcpy(name
, conn
->nickname
, len
);
3106 tor_snprintf(name
, len
, "%s:%d",
3107 conn
->_base
.address
, conn
->_base
.port
);
3109 routerinfo_t
*ri
= router_get_by_digest(conn
->identity_digest
);
3111 tor_assert(len
> MAX_VERBOSE_NICKNAME_LEN
);
3112 router_get_verbose_nickname(name
, ri
);
3113 } else if (! tor_digest_is_zero(conn
->identity_digest
)) {
3115 base16_encode(name
+1, len
-1, conn
->identity_digest
,
3118 tor_snprintf(name
, len
, "%s:%d",
3119 conn
->_base
.address
, conn
->_base
.port
);
3124 /** Convert a TOR_TLS_* error code into an END_OR_CONN_* reason. */
3126 control_tls_error_to_reason(int e
)
3129 case TOR_TLS_ERROR_IO
:
3130 return END_OR_CONN_REASON_TLS_IO_ERROR
;
3131 case TOR_TLS_ERROR_CONNREFUSED
:
3132 return END_OR_CONN_REASON_TCP_REFUSED
;
3133 case TOR_TLS_ERROR_CONNRESET
:
3134 return END_OR_CONN_REASON_TLS_CONNRESET
;
3135 case TOR_TLS_ERROR_NO_ROUTE
:
3136 return END_OR_CONN_REASON_TLS_NO_ROUTE
;
3137 case TOR_TLS_ERROR_TIMEOUT
:
3138 return END_OR_CONN_REASON_TLS_TIMEOUT
;
3139 case TOR_TLS_WANTREAD
:
3140 case TOR_TLS_WANTWRITE
:
3143 return END_OR_CONN_REASON_DONE
;
3145 return END_OR_CONN_REASON_TLS_MISC
;
3149 /** Convert the reason for ending an OR connection <b>r</b> into the format
3150 * used in ORCONN events. Return NULL if the reason is unrecognized. */
3152 or_conn_end_reason_to_string(int r
)
3155 case END_OR_CONN_REASON_DONE
:
3156 return "REASON=DONE";
3157 case END_OR_CONN_REASON_TCP_REFUSED
:
3158 return "REASON=CONNECTREFUSED";
3159 case END_OR_CONN_REASON_OR_IDENTITY
:
3160 return "REASON=IDENTITY";
3161 case END_OR_CONN_REASON_TLS_CONNRESET
:
3162 return "REASON=CONNECTRESET";
3163 case END_OR_CONN_REASON_TLS_TIMEOUT
:
3164 return "REASON=TIMEOUT";
3165 case END_OR_CONN_REASON_TLS_NO_ROUTE
:
3166 return "REASON=NOROUTE";
3167 case END_OR_CONN_REASON_TLS_IO_ERROR
:
3168 return "REASON=IOERROR";
3169 case END_OR_CONN_REASON_TLS_MISC
:
3170 return "REASON=MISC";
3174 log_warn(LD_BUG
, "Unrecognized or_conn reason code %d", r
);
3175 return "REASON=BOGUS";
3179 /** Called when the status of an OR connection <b>conn</b> changes: tell any
3180 * interested control connections. <b>tp</b> is the new status for the
3181 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
3182 * may be the reason why.
3185 control_event_or_conn_status(or_connection_t
*conn
, or_conn_status_event_t tp
,
3191 char ncircs_buf
[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
3193 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS
))
3198 case OR_CONN_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
3199 case OR_CONN_EVENT_CONNECTED
: status
= "CONNECTED"; break;
3200 case OR_CONN_EVENT_FAILED
: status
= "FAILED"; break;
3201 case OR_CONN_EVENT_CLOSED
: status
= "CLOSED"; break;
3202 case OR_CONN_EVENT_NEW
: status
= "NEW"; break;
3204 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3207 ncircs
= circuit_count_pending_on_or_conn(conn
);
3208 ncircs
+= conn
->n_circuits
;
3209 if (ncircs
&& (tp
== OR_CONN_EVENT_FAILED
|| tp
== OR_CONN_EVENT_CLOSED
)) {
3210 tor_snprintf(ncircs_buf
, sizeof(ncircs_buf
), "%sNCIRCS=%d",
3211 reason
? " " : "", ncircs
);
3214 if (EVENT_IS_INTERESTING1S(EVENT_OR_CONN_STATUS
)) {
3215 orconn_target_get_name(0, name
, sizeof(name
), conn
);
3216 send_control_event_extended(EVENT_OR_CONN_STATUS
, SHORT_NAMES
,
3217 "650 ORCONN %s %s@%s%s\r\n",
3219 or_conn_end_reason_to_string(reason
), ncircs_buf
);
3221 if (EVENT_IS_INTERESTING1L(EVENT_OR_CONN_STATUS
)) {
3222 orconn_target_get_name(1, name
, sizeof(name
), conn
);
3223 send_control_event_extended(EVENT_OR_CONN_STATUS
, LONG_NAMES
,
3224 "650 ORCONN %s %s@%s%s\r\n",
3226 or_conn_end_reason_to_string(reason
), ncircs_buf
);
3232 /** A second or more has elapsed: tell any interested control
3233 * connections how much bandwidth streams have used. */
3235 control_event_stream_bandwidth_used(void)
3237 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED
)) {
3238 smartlist_t
*conns
= get_connection_array();
3239 edge_connection_t
*edge_conn
;
3241 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
3243 if (conn
->type
!= CONN_TYPE_AP
)
3245 edge_conn
= TO_EDGE_CONN(conn
);
3246 if (!edge_conn
->n_read
&& !edge_conn
->n_written
)
3249 send_control_event(EVENT_STREAM_BANDWIDTH_USED
, ALL_NAMES
,
3250 "650 STREAM_BW %lu %lu %lu\r\n",
3251 (unsigned long)edge_conn
->global_identifier
,
3252 (unsigned long)edge_conn
->n_read
,
3253 (unsigned long)edge_conn
->n_written
);
3255 edge_conn
->n_written
= edge_conn
->n_read
= 0;
3262 /** A second or more has elapsed: tell any interested control
3263 * connections how much bandwidth we used. */
3265 control_event_bandwidth_used(uint32_t n_read
, uint32_t n_written
)
3267 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED
)) {
3268 send_control_event(EVENT_BANDWIDTH_USED
, ALL_NAMES
,
3269 "650 BW %lu %lu\r\n",
3270 (unsigned long)n_read
,
3271 (unsigned long)n_written
);
3277 /** Called when we are sending a log message to the controllers: suspend
3278 * sending further log messages to the controllers until we're done. Used by
3279 * CONN_LOG_PROTECT. */
3281 disable_control_logging(void)
3283 ++disable_log_messages
;
3286 /** We're done sending a log message to the controllers: re-enable controller
3287 * logging. Used by CONN_LOG_PROTECT. */
3289 enable_control_logging(void)
3291 if (--disable_log_messages
< 0)
3295 /** We got a log message: tell any interested control connections. */
3297 control_event_logmsg(int severity
, uint32_t domain
, const char *msg
)
3301 if (disable_log_messages
)
3304 if (domain
== LD_BUG
&& EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
) &&
3305 severity
<= LOG_NOTICE
) {
3306 char *esc
= esc_for_log(msg
);
3307 ++disable_log_messages
;
3308 control_event_general_status(severity
, "BUG REASON=\"%s\"", esc
);
3309 --disable_log_messages
;
3313 event
= log_severity_to_event(severity
);
3314 if (event
>= 0 && EVENT_IS_INTERESTING(event
)) {
3317 if (strchr(msg
, '\n')) {
3319 b
= tor_strdup(msg
);
3320 for (cp
= b
; *cp
; ++cp
)
3321 if (*cp
== '\r' || *cp
== '\n')
3325 case LOG_DEBUG
: s
= "DEBUG"; break;
3326 case LOG_INFO
: s
= "INFO"; break;
3327 case LOG_NOTICE
: s
= "NOTICE"; break;
3328 case LOG_WARN
: s
= "WARN"; break;
3329 case LOG_ERR
: s
= "ERR"; break;
3330 default: s
= "UnknownLogSeverity"; break;
3332 ++disable_log_messages
;
3333 send_control_event(event
, ALL_NAMES
, "650 %s %s\r\n", s
, b
?b
:msg
);
3334 --disable_log_messages
;
3339 /** Called whenever we receive new router descriptors: tell any
3340 * interested control connections. <b>routers</b> is a list of
3344 control_event_descriptors_changed(smartlist_t
*routers
)
3348 smartlist_t
*identities
= NULL
;
3349 char buf
[HEX_DIGEST_LEN
+1];
3351 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC
))
3353 if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC
)) {
3354 identities
= smartlist_create();
3355 SMARTLIST_FOREACH(routers
, routerinfo_t
*, r
,
3357 base16_encode(buf
,sizeof(buf
),r
->cache_info
.identity_digest
,DIGEST_LEN
);
3358 smartlist_add(identities
, tor_strdup(buf
));
3361 if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC
)) {
3362 char *ids
= smartlist_join_strings(identities
, " ", 0, &len
);
3363 size_t ids_len
= strlen(ids
)+32;
3364 msg
= tor_malloc(ids_len
);
3365 tor_snprintf(msg
, ids_len
, "650 NEWDESC %s\r\n", ids
);
3366 send_control_event_string(EVENT_NEW_DESC
, SHORT_NAMES
|ALL_FORMATS
, msg
);
3370 if (EVENT_IS_INTERESTING1L(EVENT_NEW_DESC
)) {
3371 smartlist_t
*names
= smartlist_create();
3374 SMARTLIST_FOREACH(routers
, routerinfo_t
*, ri
, {
3375 char *b
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
3376 router_get_verbose_nickname(b
, ri
);
3377 smartlist_add(names
, b
);
3379 ids
= smartlist_join_strings(names
, " ", 0, &names_len
);
3380 names_len
= strlen(ids
)+32;
3381 msg
= tor_malloc(names_len
);
3382 tor_snprintf(msg
, names_len
, "650 NEWDESC %s\r\n", ids
);
3383 send_control_event_string(EVENT_NEW_DESC
, LONG_NAMES
|ALL_FORMATS
, msg
);
3386 SMARTLIST_FOREACH(names
, char *, cp
, tor_free(cp
));
3387 smartlist_free(names
);
3390 SMARTLIST_FOREACH(identities
, char *, cp
, tor_free(cp
));
3391 smartlist_free(identities
);
3396 /** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
3397 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
3398 * <b>error</b> is non-NULL, it is an error code describing the failure
3399 * mode of the mapping.
3402 control_event_address_mapped(const char *from
, const char *to
, time_t expires
,
3405 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP
))
3408 if (expires
< 3 || expires
== TIME_MAX
)
3409 send_control_event_extended(EVENT_ADDRMAP
, ALL_NAMES
,
3410 "650 ADDRMAP %s %s NEVER@%s\r\n", from
, to
,
3413 char buf
[ISO_TIME_LEN
+1];
3414 char buf2
[ISO_TIME_LEN
+1];
3415 format_local_iso_time(buf
,expires
);
3416 format_iso_time(buf2
,expires
);
3417 send_control_event_extended(EVENT_ADDRMAP
, ALL_NAMES
,
3418 "650 ADDRMAP %s %s \"%s\""
3419 "@%s%sEXPIRES=\"%s\"\r\n",
3421 error
?error
:"", error
?" ":"",
3428 /** The authoritative dirserver has received a new descriptor that
3429 * has passed basic syntax checks and is properly self-signed.
3431 * Notify any interested party of the new descriptor and what has
3432 * been done with it, and also optionally give an explanation/reason. */
3434 control_event_or_authdir_new_descriptor(const char *action
,
3435 const char *desc
, size_t desclen
,
3438 char firstline
[1024];
3444 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS
))
3447 tor_snprintf(firstline
, sizeof(firstline
),
3448 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
3452 /* Escape the server descriptor properly */
3453 esclen
= write_escaped_data(desc
, desclen
, &esc
);
3455 totallen
= strlen(firstline
) + esclen
+ 1;
3456 buf
= tor_malloc(totallen
);
3457 strlcpy(buf
, firstline
, totallen
);
3458 strlcpy(buf
+strlen(firstline
), esc
, totallen
);
3459 send_control_event_string(EVENT_AUTHDIR_NEWDESCS
, ALL_NAMES
|ALL_FORMATS
,
3461 send_control_event_string(EVENT_AUTHDIR_NEWDESCS
, ALL_NAMES
|ALL_FORMATS
,
3469 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
3470 * an NS event to any controller that cares. */
3472 control_event_networkstatus_changed(smartlist_t
*statuses
)
3475 char *s
, *esc
= NULL
;
3476 if (!EVENT_IS_INTERESTING(EVENT_NS
) || !smartlist_len(statuses
))
3479 strs
= smartlist_create();
3480 smartlist_add(strs
, tor_strdup("650+NS\r\n"));
3481 SMARTLIST_FOREACH(statuses
, routerstatus_t
*, rs
,
3483 s
= networkstatus_getinfo_helper_single(rs
);
3485 smartlist_add(strs
, s
);
3488 s
= smartlist_join_strings(strs
, "", 0, NULL
);
3489 write_escaped_data(s
, strlen(s
), &esc
);
3490 SMARTLIST_FOREACH(strs
, char *, cp
, tor_free(cp
));
3491 smartlist_free(strs
);
3493 send_control_event_string(EVENT_NS
, ALL_NAMES
|ALL_FORMATS
, esc
);
3494 send_control_event_string(EVENT_NS
, ALL_NAMES
|ALL_FORMATS
,
3501 /** Called when a single local_routerstatus_t has changed: Sends an NS event
3502 * to any countroller that cares. */
3504 control_event_networkstatus_changed_single(routerstatus_t
*rs
)
3506 smartlist_t
*statuses
;
3509 if (!EVENT_IS_INTERESTING(EVENT_NS
))
3512 statuses
= smartlist_create();
3513 smartlist_add(statuses
, rs
);
3514 r
= control_event_networkstatus_changed(statuses
);
3515 smartlist_free(statuses
);
3519 /** Our own router descriptor has changed; tell any controllers that care.
3522 control_event_my_descriptor_changed(void)
3524 send_control_event(EVENT_DESCCHANGED
, ALL_NAMES
, "650 DESCCHANGED\r\n");
3528 /** Helper: sends a status event where <b>type</b> is one of
3529 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
3530 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
3531 * string corresponding to <b>args</b>. */
3533 control_event_status(int type
, int severity
, const char *format
, va_list args
)
3535 char format_buf
[160];
3536 const char *status
, *sev
;
3539 case EVENT_STATUS_GENERAL
:
3540 status
= "STATUS_GENERAL";
3542 case EVENT_STATUS_CLIENT
:
3543 status
= "STATUS_CLIENT";
3545 case EVENT_STATUS_SERVER
:
3546 status
= "STATUS_SEVER";
3549 log_warn(LD_BUG
, "Unrecognized status type %d", type
);
3563 log_warn(LD_BUG
, "Unrecognized status severity %d", severity
);
3566 if (tor_snprintf(format_buf
, sizeof(format_buf
), "650 %s %s %s\r\n",
3567 status
, sev
, format
)<0) {
3568 log_warn(LD_BUG
, "Format string too long.");
3572 send_control_event_impl(type
, ALL_NAMES
|ALL_FORMATS
, 0, format_buf
, args
);
3576 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
3577 * by formatting the arguments using the printf-style <b>format</b>. */
3579 control_event_general_status(int severity
, const char *format
, ...)
3583 if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
))
3586 va_start(ap
, format
);
3587 r
= control_event_status(EVENT_STATUS_GENERAL
, severity
, format
, ap
);
3592 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
3593 * by formatting the arguments using the printf-style <b>format</b>. */
3595 control_event_client_status(int severity
, const char *format
, ...)
3599 if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT
))
3602 va_start(ap
, format
);
3603 r
= control_event_status(EVENT_STATUS_CLIENT
, severity
, format
, ap
);
3608 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
3609 * by formatting the arguments using the printf-style <b>format</b>. */
3611 control_event_server_status(int severity
, const char *format
, ...)
3615 if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER
))
3618 va_start(ap
, format
);
3619 r
= control_event_status(EVENT_STATUS_SERVER
, severity
, format
, ap
);
3624 /** Called when the status of an entry guard with the given <b>nickname</b>
3625 * and identity <b>digest</b> has changed to <b>status</b>: tells any
3626 * controllers that care. */
3628 control_event_guard(const char *nickname
, const char *digest
,
3631 char hbuf
[HEX_DIGEST_LEN
+1];
3632 base16_encode(hbuf
, sizeof(hbuf
), digest
, DIGEST_LEN
);
3633 if (!EVENT_IS_INTERESTING(EVENT_GUARD
))
3636 if (EVENT_IS_INTERESTING1L(EVENT_GUARD
)) {
3637 char buf
[MAX_VERBOSE_NICKNAME_LEN
+1];
3638 routerinfo_t
*ri
= router_get_by_digest(digest
);
3640 router_get_verbose_nickname(buf
, ri
);
3642 tor_snprintf(buf
, sizeof(buf
), "$%s~%s", hbuf
, nickname
);
3644 send_control_event(EVENT_GUARD
, LONG_NAMES
,
3645 "650 GUARD ENTRY %s %s\r\n", buf
, status
);
3647 if (EVENT_IS_INTERESTING1S(EVENT_GUARD
)) {
3648 send_control_event(EVENT_GUARD
, SHORT_NAMES
,
3649 "650 GUARD ENTRY $%s %s\r\n", hbuf
, status
);
3654 /** Helper: Return a newly allocated string containing a path to the
3655 * file where we store our authentication cookie. */
3657 get_cookie_file(void)
3659 or_options_t
*options
= get_options();
3660 if (options
->CookieAuthFile
&& strlen(options
->CookieAuthFile
)) {
3661 return tor_strdup(options
->CookieAuthFile
);
3663 return get_datadir_fname("control_auth_cookie");
3667 /** Choose a random authentication cookie and write it to disk.
3668 * Anybody who can read the cookie from disk will be considered
3669 * authorized to use the control connection. Return -1 if we can't
3670 * write the file, or 0 on success. */
3672 init_cookie_authentication(int enabled
)
3676 authentication_cookie_is_set
= 0;
3680 /* We don't want to generate a new cookie every time we call
3681 * options_act(). One should be enough. */
3682 if (authentication_cookie_is_set
)
3683 return 0; /* all set */
3685 fname
= get_cookie_file();
3686 crypto_rand(authentication_cookie
, AUTHENTICATION_COOKIE_LEN
);
3687 authentication_cookie_is_set
= 1;
3688 if (write_bytes_to_file(fname
, authentication_cookie
,
3689 AUTHENTICATION_COOKIE_LEN
, 1)) {
3690 log_warn(LD_FS
,"Error writing authentication cookie to %s.",
3696 if (get_options()->CookieAuthFileGroupReadable
) {
3697 if (chmod(fname
, 0640)) {
3698 log_warn(LD_FS
,"Unable to make %s group-readable.", escaped(fname
));