1 /* Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
2 /* See LICENSE for licensing information */
4 const char control_c_id
[] = "$Id$";
8 * \brief Implementation for Tor's control-socket interface.
13 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN_V0 || \
14 (s) == CONTROL_CONN_STATE_OPEN_V1)
15 #define STATE_IS_V0(s) ((s) == CONTROL_CONN_STATE_NEEDAUTH_V0 || \
16 (s) == CONTROL_CONN_STATE_OPEN_V0)
19 * See control-spec.txt and control-spec-v0.txt for full details on protocol(s).
22 /* Recognized message type codes. */
23 #define CONTROL0_CMD_ERROR 0x0000
24 #define CONTROL0_CMD_DONE 0x0001
25 #define CONTROL0_CMD_SETCONF 0x0002
26 #define CONTROL0_CMD_GETCONF 0x0003
27 #define CONTROL0_CMD_CONFVALUE 0x0004
28 #define CONTROL0_CMD_SETEVENTS 0x0005
29 #define CONTROL0_CMD_EVENT 0x0006
30 #define CONTROL0_CMD_AUTHENTICATE 0x0007
31 #define CONTROL0_CMD_SAVECONF 0x0008
32 #define CONTROL0_CMD_SIGNAL 0x0009
33 #define CONTROL0_CMD_MAPADDRESS 0x000A
34 #define CONTROL0_CMD_GETINFO 0x000B
35 #define CONTROL0_CMD_INFOVALUE 0x000C
36 #define CONTROL0_CMD_EXTENDCIRCUIT 0x000D
37 #define CONTROL0_CMD_ATTACHSTREAM 0x000E
38 #define CONTROL0_CMD_POSTDESCRIPTOR 0x000F
39 #define CONTROL0_CMD_FRAGMENTHEADER 0x0010
40 #define CONTROL0_CMD_FRAGMENT 0x0011
41 #define CONTROL0_CMD_REDIRECTSTREAM 0x0012
42 #define CONTROL0_CMD_CLOSESTREAM 0x0013
43 #define CONTROL0_CMD_CLOSECIRCUIT 0x0014
44 #define _CONTROL0_CMD_MAX_RECOGNIZED 0x0014
46 /* Recognized error codes. */
47 #define ERR_UNSPECIFIED 0x0000
48 #define ERR_INTERNAL 0x0001
49 #define ERR_UNRECOGNIZED_TYPE 0x0002
50 #define ERR_SYNTAX 0x0003
51 #define ERR_UNRECOGNIZED_CONFIG_KEY 0x0004
52 #define ERR_INVALID_CONFIG_VALUE 0x0005
53 #define ERR_UNRECOGNIZED_EVENT_CODE 0x0006
54 #define ERR_UNAUTHORIZED 0x0007
55 #define ERR_REJECTED_AUTHENTICATION 0x0008
56 #define ERR_RESOURCE_EXHAUSETED 0x0009
57 #define ERR_NO_STREAM 0x000A
58 #define ERR_NO_CIRC 0x000B
59 #define ERR_NO_ROUTER 0x000C
61 /* Recognized asynchronous event types. */
62 #define _EVENT_MIN 0x0001
63 #define EVENT_CIRCUIT_STATUS 0x0001
64 #define EVENT_STREAM_STATUS 0x0002
65 #define EVENT_OR_CONN_STATUS 0x0003
66 #define EVENT_BANDWIDTH_USED 0x0004
67 #define EVENT_LOG_OBSOLETE 0x0005
68 #define EVENT_NEW_DESC 0x0006
69 #define EVENT_DEBUG_MSG 0x0007
70 #define EVENT_INFO_MSG 0x0008
71 #define EVENT_NOTICE_MSG 0x0009
72 #define EVENT_WARN_MSG 0x000A
73 #define EVENT_ERR_MSG 0x000B
74 #define LAST_V0_EVENT 0x000B
75 #define EVENT_ADDRMAP 0x000C
76 #define _EVENT_MAX 0x000C
78 /** Array mapping from message type codes to human-readable message
79 * type names. Used for compatibility with version 0 of the control
81 static const char * CONTROL0_COMMANDS
[_CONTROL0_CMD_MAX_RECOGNIZED
+1] = {
102 /** Bitfield: The bit 1<<e is set if <b>any</b> open control
103 * connection is interested in events of type <b>e</b>. We use this
104 * so that we can decide to skip generating event messages that nobody
105 * has interest in without having to walk over the global connection
108 static uint32_t global_event_mask0
= 0;
109 static uint32_t global_event_mask1
= 0;
111 /** True iff we have disabled log messages from being sent to the controller */
112 static int disable_log_messages
= 0;
114 /** Macro: true if any control connection is interested in events of type
116 #define EVENT_IS_INTERESTING0(e) (global_event_mask0 & (1<<(e)))
117 #define EVENT_IS_INTERESTING1(e) (global_event_mask1 & (1<<(e)))
118 #define EVENT_IS_INTERESTING(e) \
119 ((global_event_mask0|global_event_mask1) & (1<<(e)))
121 /** If we're using cookie-type authentication, how long should our cookies be?
123 #define AUTHENTICATION_COOKIE_LEN 32
125 /** If true, we've set authentication_cookie to a secret code and
126 * stored it to disk. */
127 static int authentication_cookie_is_set
= 0;
128 static char authentication_cookie
[AUTHENTICATION_COOKIE_LEN
];
130 static void connection_printf_to_buf(connection_t
*conn
, const char *format
, ...)
132 /*static*/ size_t write_escaped_data(const char *data
, size_t len
,
133 int translate_newlines
, char **out
);
134 /*static*/ size_t read_escaped_data(const char *data
, size_t len
,
135 int translate_newlines
, char **out
);
136 static void send_control0_message(connection_t
*conn
, uint16_t type
,
137 uint32_t len
, const char *body
);
138 static void send_control_done(connection_t
*conn
);
139 static void send_control_done2(connection_t
*conn
, const char *msg
, size_t len
);
140 static void send_control0_error(connection_t
*conn
, uint16_t error
,
141 const char *message
);
142 static void send_control0_event(uint16_t event
, uint32_t len
, const char *body
);
143 static void send_control1_event(uint16_t event
, const char *format
, ...)
145 static int handle_control_setconf(connection_t
*conn
, uint32_t len
,
147 static int handle_control_resetconf(connection_t
*conn
, uint32_t len
,
149 static int handle_control_getconf(connection_t
*conn
, uint32_t len
,
151 static int handle_control_setevents(connection_t
*conn
, uint32_t len
,
153 static int handle_control_authenticate(connection_t
*conn
, uint32_t len
,
155 static int handle_control_saveconf(connection_t
*conn
, uint32_t len
,
157 static int handle_control_signal(connection_t
*conn
, uint32_t len
,
159 static int handle_control_mapaddress(connection_t
*conn
, uint32_t len
,
161 static int handle_control_getinfo(connection_t
*conn
, uint32_t len
,
163 static int handle_control_extendcircuit(connection_t
*conn
, uint32_t len
,
165 static int handle_control_attachstream(connection_t
*conn
, uint32_t len
,
167 static int handle_control_postdescriptor(connection_t
*conn
, uint32_t len
,
169 static int handle_control_redirectstream(connection_t
*conn
, uint32_t len
,
171 static int handle_control_closestream(connection_t
*conn
, uint32_t len
,
173 static int handle_control_closecircuit(connection_t
*conn
, uint32_t len
,
175 static int write_stream_target_to_buf(connection_t
*conn
, char *buf
, size_t len
);
177 /** Given a possibly invalid message type code <b>cmd</b>, return a
178 * human-readable string equivalent. */
179 static INLINE
const char *
180 control_cmd_to_string(uint16_t cmd
)
182 return (cmd
<=_CONTROL0_CMD_MAX_RECOGNIZED
) ? CONTROL0_COMMANDS
[cmd
] : "Unknown";
185 /** Given a control event code for a message event, return the corresponding
188 event_to_log_severity(int event
)
191 case EVENT_DEBUG_MSG
: return LOG_DEBUG
;
192 case EVENT_INFO_MSG
: return LOG_INFO
;
193 case EVENT_NOTICE_MSG
: return LOG_NOTICE
;
194 case EVENT_WARN_MSG
: return LOG_WARN
;
195 case EVENT_ERR_MSG
: return LOG_ERR
;
200 /** Given a log severity, return the corresponding control event code. */
202 log_severity_to_event(int severity
)
205 case LOG_DEBUG
: return EVENT_DEBUG_MSG
;
206 case LOG_INFO
: return EVENT_INFO_MSG
;
207 case LOG_NOTICE
: return EVENT_NOTICE_MSG
;
208 case LOG_WARN
: return EVENT_WARN_MSG
;
209 case LOG_ERR
: return EVENT_ERR_MSG
;
214 /** Set <b>global_event_maskX</b> (where X is 0 or 1) to the bitwise OR
215 * of each live control connection's event_mask field. */
217 control_update_global_event_mask(void)
219 connection_t
**conns
;
221 global_event_mask0
= 0;
222 global_event_mask1
= 0;
223 get_connection_array(&conns
, &n_conns
);
224 for (i
= 0; i
< n_conns
; ++i
) {
225 if (conns
[i
]->type
== CONN_TYPE_CONTROL
&&
226 STATE_IS_OPEN(conns
[i
]->state
)) {
227 if (STATE_IS_V0(conns
[i
]->state
))
228 global_event_mask0
|= conns
[i
]->event_mask
;
230 global_event_mask1
|= conns
[i
]->event_mask
;
234 control_adjust_event_log_severity();
237 /** Adjust the log severities that result in control_event_logmsg being called
238 * to match the severity of log messages that any controllers are interested
241 control_adjust_event_log_severity(void)
244 int min_log_event
=EVENT_ERR_MSG
, max_log_event
=EVENT_DEBUG_MSG
;
246 for (i
= EVENT_DEBUG_MSG
; i
<= EVENT_ERR_MSG
; ++i
) {
247 if (EVENT_IS_INTERESTING(i
)) {
252 for (i
= EVENT_ERR_MSG
; i
>= EVENT_DEBUG_MSG
; --i
) {
253 if (EVENT_IS_INTERESTING(i
)) {
258 if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE
)) {
259 if (min_log_event
> EVENT_NOTICE_MSG
)
260 min_log_event
= EVENT_NOTICE_MSG
;
261 if (max_log_event
< EVENT_ERR_MSG
)
262 max_log_event
= EVENT_ERR_MSG
;
264 change_callback_log_severity(event_to_log_severity(min_log_event
),
265 event_to_log_severity(max_log_event
),
266 control_event_logmsg
);
269 /** Append a NUL-terminated string <b>s</b> to the end of
270 * <b>conn</b>-\>outbuf
273 connection_write_str_to_buf(const char *s
, connection_t
*conn
)
275 size_t len
= strlen(s
);
276 connection_write_to_buf(s
, len
, conn
);
279 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
280 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
281 * the contents of <b>data</b> into *<b>out</b>, adding a period
282 * before any period that that appears at the start of a line, and
283 * adding a period-CRLF line at the end. If <b>translate_newlines</b>
284 * is true, replace all LF characters sequences with CRLF. Return the
285 * number of bytes in *<b>out</b>.
288 write_escaped_data(const char *data
, size_t len
, int translate_newlines
,
291 size_t sz_out
= len
+8;
296 for (i
=0; i
<(int)len
; ++i
) {
298 sz_out
+= 2; /* Maybe add a CR; maybe add a dot. */
300 *out
= outp
= tor_malloc(sz_out
+1);
305 if (translate_newlines
)
308 } else if (*data
== '.') {
318 if (outp
< *out
+2 || memcmp(outp
-2, "\r\n", 2)) {
325 *outp
= '\0'; /* NUL-terminate just in case. */
326 tor_assert((outp
- *out
) <= (int)sz_out
);
330 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
331 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
332 * the contents of <b>data</b> into *<b>out</b>, removing any period
333 * that appears at the start of a line. If <b>translate_newlines</b>
334 * is true, replace all CRLF sequences with LF. Return the number of
335 * bytes in *<b>out</b>. */
337 read_escaped_data(const char *data
, size_t len
, int translate_newlines
,
344 *out
= outp
= tor_malloc(len
+1);
351 if (translate_newlines
)
352 next
= tor_memmem(data
, end
-data
, "\r\n", 2);
354 next
= tor_memmem(data
, end
-data
, "\r\n.", 3);
356 memcpy(outp
, data
, next
-data
);
360 memcpy(outp
, data
, end
-data
);
365 if (translate_newlines
) {
377 /** Given a pointer to a string starting at <b>start</b> containing
378 * <b>in_len_max</b> characters, decode a string beginning with a single
379 * quote, containing any number of non-quote characters or characters escaped
380 * with a backslash, and ending with a final quote. Place the resulting
381 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
382 * store its length in <b>out_len</b>. On success, return a pointer to the
383 * character immediately following the escaped string. On failure, return
386 get_escaped_string(const char *start
, size_t in_len_max
,
387 char **out
, size_t *out_len
)
389 const char *cp
, *end
;
397 end
= start
+in_len_max
;
399 /* Calculate length. */
403 else if (*cp
== '\\') {
405 return NULL
; /* Can't escape EOS. */
408 } else if (*cp
== '\"') {
416 outp
= *out
= tor_malloc(len
+1);
426 tor_assert((outp
- *out
) == (int)*out_len
);
431 /** Acts like sprintf, but writes its formatted string to the end of
432 * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
433 * but it will always end with a CRLF sequence.
436 connection_printf_to_buf(connection_t
*conn
, const char *format
, ...)
443 r
= tor_vsnprintf(buf
, sizeof(buf
), format
, ap
);
446 if (memcmp("\r\n\0", buf
+len
-2, 3)) {
451 connection_write_to_buf(buf
, len
, conn
);
454 /** Send a message of type <b>type</b> containing <b>len</b> bytes
455 * from <b>body</b> along the control connection <b>conn</b> */
457 send_control0_message(connection_t
*conn
, uint16_t type
, uint32_t len
,
462 tor_assert(STATE_IS_V0(conn
->state
));
463 tor_assert(len
|| !body
);
464 tor_assert(type
<= _CONTROL0_CMD_MAX_RECOGNIZED
);
466 set_uint16(buf
, htons(len
));
467 set_uint16(buf
+2, htons(type
));
468 connection_write_to_buf(buf
, 4, conn
);
470 connection_write_to_buf(body
, len
, conn
);
472 set_uint16(buf
, htons(65535));
473 set_uint16(buf
+2, htons(CONTROL0_CMD_FRAGMENTHEADER
));
474 set_uint16(buf
+4, htons(type
));
475 set_uint32(buf
+6, htonl(len
));
476 connection_write_to_buf(buf
, 10, conn
);
477 connection_write_to_buf(body
, 65535-6, conn
);
481 size_t chunklen
= (len
<65535)?len
:65535;
482 set_uint16(buf
, htons((uint16_t)chunklen
));
483 set_uint16(buf
+2, htons(CONTROL0_CMD_FRAGMENT
));
484 connection_write_to_buf(buf
, 4, conn
);
485 connection_write_to_buf(body
, chunklen
, conn
);
492 /** Send a "DONE" message down the control connection <b>conn</b> */
494 send_control_done(connection_t
*conn
)
496 if (STATE_IS_V0(conn
->state
)) {
497 send_control0_message(conn
, CONTROL0_CMD_DONE
, 0, NULL
);
499 connection_write_str_to_buf("250 OK\r\n", conn
);
503 /** Send a "DONE" message down the v0 control message <b>conn</b>, with body
504 * as provided in the <b>len</b> bytes at <b>msg</b>.
507 send_control_done2(connection_t
*conn
, const char *msg
, size_t len
)
511 send_control0_message(conn
, CONTROL0_CMD_DONE
, len
, msg
);
514 /** Send an error message with error code <b>error</b> and body
515 * <b>message</b> down the connection <b>conn</b> */
517 send_control0_error(connection_t
*conn
, uint16_t error
, const char *message
)
521 set_uint16(buf
, htons(error
));
522 len
= strlen(message
);
523 tor_assert(len
< (256-2));
524 memcpy(buf
+2, message
, len
);
525 send_control0_message(conn
, CONTROL0_CMD_ERROR
, (uint16_t)(len
+2), buf
);
528 /** Send an 'event' message of event type <b>event</b>, containing
529 * <b>len</b> bytes in <b>body</b> to every control connection that
530 * is interested in it. */
532 send_control0_event(uint16_t event
, uint32_t len
, const char *body
)
534 connection_t
**conns
;
539 tor_assert(event
>= _EVENT_MIN
&& event
<= LAST_V0_EVENT
);
542 buf
= tor_malloc_zero(buflen
);
543 set_uint16(buf
, htons(event
));
544 memcpy(buf
+2, body
, len
);
546 get_connection_array(&conns
, &n_conns
);
547 for (i
= 0; i
< n_conns
; ++i
) {
548 if (conns
[i
]->type
== CONN_TYPE_CONTROL
&&
549 !conns
[i
]->marked_for_close
&&
550 conns
[i
]->state
== CONTROL_CONN_STATE_OPEN_V0
&&
551 conns
[i
]->event_mask
& (1<<event
)) {
552 send_control0_message(conns
[i
], CONTROL0_CMD_EVENT
, buflen
, buf
);
553 if (event
== EVENT_ERR_MSG
)
554 _connection_controller_force_write(conns
[i
]);
561 /* Send an event to all v1 controllers that are listening for code
562 * <b>event</b>. The event's body is created by the printf-style format in
563 * <b>format</b>, and other arguments as provided. */
565 send_control1_event(uint16_t event
, const char *format
, ...)
567 connection_t
**conns
;
569 char buf
[1024]; /* XXXX Length */
573 va_start(ap
, format
);
574 r
= tor_vsnprintf(buf
, sizeof(buf
), format
, ap
);
578 if (memcmp("\r\n\0", buf
+len
-2, 3)) {
584 tor_assert(event
>= _EVENT_MIN
&& event
<= _EVENT_MAX
);
586 get_connection_array(&conns
, &n_conns
);
587 for (i
= 0; i
< n_conns
; ++i
) {
588 if (conns
[i
]->type
== CONN_TYPE_CONTROL
&&
589 !conns
[i
]->marked_for_close
&&
590 conns
[i
]->state
== CONTROL_CONN_STATE_OPEN_V1
&&
591 conns
[i
]->event_mask
& (1<<event
)) {
592 connection_write_to_buf(buf
, len
, conns
[i
]);
593 if (event
== EVENT_ERR_MSG
)
594 _connection_controller_force_write(conns
[i
]);
599 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
601 get_circ(const char *id
)
605 n_id
= tor_parse_ulong(id
, 10, 0, ULONG_MAX
, &ok
, NULL
);
608 return circuit_get_by_global_id(n_id
);
611 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
612 static connection_t
*
613 get_stream(const char *id
)
618 n_id
= tor_parse_ulong(id
, 10, 0, ULONG_MAX
, &ok
, NULL
);
621 conn
= connection_get_by_global_id(n_id
);
622 if (!conn
|| conn
->type
!= CONN_TYPE_AP
)
627 /** Helper for setconf and resetconf. Acts like setconf, except
628 * it passes <b>use_defaults</b> on to options_trial_assign().
631 control_setconf_helper(connection_t
*conn
, uint32_t len
, char *body
,
632 int use_defaults
, int clear_first
)
635 config_line_t
*lines
=NULL
;
637 int v0
= STATE_IS_V0(conn
->state
);
640 char *config
= tor_malloc(len
+1);
644 while (!TOR_ISSPACE(*eq
) && *eq
!= '=')
646 memcpy(outp
, body
, eq
-body
);
652 while (!TOR_ISSPACE(*body
))
657 body
= (char*)get_escaped_string(body
, (len
- (body
-start
)),
660 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn
);
664 memcpy(outp
, val
, val_len
);
669 while (TOR_ISSPACE(*body
))
675 if (config_get_lines(config
, &lines
) < 0) {
676 log_fn(LOG_WARN
,"Controller gave us config lines we can't parse.");
677 connection_write_str_to_buf("551 Couldn't parse configuration\r\n", conn
);
683 if (config_get_lines(body
, &lines
) < 0) {
684 log_fn(LOG_WARN
,"Controller gave us config lines we can't parse.");
685 send_control0_error(conn
, ERR_SYNTAX
, "Couldn't parse configuration");
690 if ((r
=options_trial_assign(lines
, use_defaults
, clear_first
)) < 0) {
693 log_fn(LOG_WARN
,"Controller gave us config lines that didn't validate.");
696 v0_err
= ERR_UNRECOGNIZED_CONFIG_KEY
;
697 msg
= "Unrecognized option";
700 v0_err
= ERR_INVALID_CONFIG_VALUE
;
701 msg
= "Unrecognized option value";
704 v0_err
= ERR_INVALID_CONFIG_VALUE
;
705 msg
= "Transition not allowed";
709 v0_err
= ERR_INVALID_CONFIG_VALUE
;
710 msg
= "Unable to set option";
714 send_control0_error(conn
, v0_err
, msg
);
716 connection_printf_to_buf(conn
, "552 %s\r\n", msg
);
718 config_free_lines(lines
);
721 config_free_lines(lines
);
722 send_control_done(conn
);
726 /** Called when we receive a SETCONF message: parse the body and try
727 * to update our configuration. Reply with a DONE or ERROR message. */
729 handle_control_setconf(connection_t
*conn
, uint32_t len
, char *body
)
731 return control_setconf_helper(conn
, len
, body
, 0, 1);
734 /** Called when we receive a RESETCONF message: parse the body and try
735 * to update our configuration. Reply with a DONE or ERROR message. */
737 handle_control_resetconf(connection_t
*conn
, uint32_t len
, char *body
)
739 int v0
= STATE_IS_V0(conn
->state
);
741 return control_setconf_helper(conn
, len
, body
, 1, 1);
744 /** Called when we receive a GETCONF message. Parse the request, and
745 * reply with a CONFVALUE or an ERROR message */
747 handle_control_getconf(connection_t
*conn
, uint32_t body_len
, const char *body
)
749 smartlist_t
*questions
= NULL
;
750 smartlist_t
*answers
= NULL
;
751 smartlist_t
*unrecognized
= NULL
;
754 or_options_t
*options
= get_options();
755 int v0
= STATE_IS_V0(conn
->state
);
757 questions
= smartlist_create();
759 smartlist_split_string(questions
, body
, "\n",
760 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
762 smartlist_split_string(questions
, body
, " ",
763 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
765 answers
= smartlist_create();
766 unrecognized
= smartlist_create();
767 SMARTLIST_FOREACH(questions
, char *, q
,
769 if (!option_is_recognized(q
)) {
771 send_control0_error(conn
, ERR_UNRECOGNIZED_CONFIG_KEY
, q
);
774 smartlist_add(unrecognized
, q
);
777 config_line_t
*answer
= option_get_assignment(options
,q
);
778 if (!v0
&& !answer
) {
779 const char *name
= option_get_canonical_name(q
);
780 size_t alen
= strlen(name
)+8;
781 char *astr
= tor_malloc(alen
);
782 tor_snprintf(astr
, alen
, "250-%s\r\n", name
);
783 smartlist_add(answers
, astr
);
788 size_t alen
= strlen(answer
->key
)+strlen(answer
->value
)+8;
789 char *astr
= tor_malloc(alen
);
791 tor_snprintf(astr
, alen
, "%s %s\n", answer
->key
, answer
->value
);
793 tor_snprintf(astr
, alen
, "250-%s=%s\r\n", answer
->key
, answer
->value
);
794 smartlist_add(answers
, astr
);
797 tor_free(answer
->key
);
798 tor_free(answer
->value
);
806 msg
= smartlist_join_strings(answers
, "", 0, &msg_len
);
807 send_control0_message(conn
, CONTROL0_CMD_CONFVALUE
,
808 (uint16_t)msg_len
, msg_len
?msg
:NULL
);
811 if ((len
= smartlist_len(unrecognized
))) {
812 for (i
=0; i
< len
-1; ++i
)
813 connection_printf_to_buf(conn
,
814 "552-Unrecognized configuration key \"%s\"\r\n",
815 (char*)smartlist_get(unrecognized
, i
));
816 connection_printf_to_buf(conn
,
817 "552 Unrecognized configuration key \"%s\"\r\n",
818 (char*)smartlist_get(unrecognized
, len
-1));
819 } else if ((len
= smartlist_len(answers
))) {
820 char *tmp
= smartlist_get(answers
, len
-1);
821 tor_assert(strlen(tmp
)>4);
823 msg
= smartlist_join_strings(answers
, "", 0, &msg_len
);
824 connection_write_to_buf(msg
, msg_len
, conn
);
826 connection_write_str_to_buf("250 OK\r\n", conn
);
831 if (answers
) SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
832 if (questions
) SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
833 smartlist_free(answers
);
834 smartlist_free(questions
);
835 smartlist_free(unrecognized
);
841 /** Called when we get a SETEVENTS message: update conn->event_mask,
842 * and reply with DONE or ERROR. */
844 handle_control_setevents(connection_t
*conn
, uint32_t len
, const char *body
)
847 uint32_t event_mask
= 0;
849 if (STATE_IS_V0(conn
->state
)) {
851 send_control0_error(conn
, ERR_SYNTAX
,
852 "Odd number of bytes in setevents message");
856 for (; len
; len
-= 2, body
+= 2) {
857 event_code
= ntohs(get_uint16(body
));
858 if (event_code
< _EVENT_MIN
|| event_code
> LAST_V0_EVENT
) {
859 send_control0_error(conn
, ERR_UNRECOGNIZED_EVENT_CODE
,
860 "Unrecognized event code");
863 event_mask
|= (1 << event_code
);
866 smartlist_t
*events
= smartlist_create();
867 smartlist_split_string(events
, body
, " ",
868 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
869 SMARTLIST_FOREACH(events
, const char *, ev
,
871 if (!strcasecmp(ev
, "CIRC"))
872 event_code
= EVENT_CIRCUIT_STATUS
;
873 else if (!strcasecmp(ev
, "STREAM"))
874 event_code
= EVENT_STREAM_STATUS
;
875 else if (!strcasecmp(ev
, "ORCONN"))
876 event_code
= EVENT_OR_CONN_STATUS
;
877 else if (!strcasecmp(ev
, "BW"))
878 event_code
= EVENT_BANDWIDTH_USED
;
879 else if (!strcasecmp(ev
, "DEBUG"))
880 event_code
= EVENT_DEBUG_MSG
;
881 else if (!strcasecmp(ev
, "INFO"))
882 event_code
= EVENT_INFO_MSG
;
883 else if (!strcasecmp(ev
, "NOTICE"))
884 event_code
= EVENT_NOTICE_MSG
;
885 else if (!strcasecmp(ev
, "WARN"))
886 event_code
= EVENT_WARN_MSG
;
887 else if (!strcasecmp(ev
, "ERR"))
888 event_code
= EVENT_ERR_MSG
;
889 else if (!strcasecmp(ev
, "NEWDESC"))
890 event_code
= EVENT_NEW_DESC
;
891 else if (!strcasecmp(ev
, "ADDRMAP"))
892 event_code
= EVENT_ADDRMAP
;
894 connection_printf_to_buf(conn
, "552 Unrecognized event \"%s\"\r\n",
896 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
897 smartlist_free(events
);
900 event_mask
|= (1 << event_code
);
902 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
903 smartlist_free(events
);
905 conn
->event_mask
= event_mask
;
907 control_update_global_event_mask();
908 send_control_done(conn
);
912 /** Decode the hashed, base64'd password stored in <b>hashed</b>. If
913 * <b>buf</b> is provided, store the hashed password in the first
914 * S2K_SPECIFIER_LEN+DIGEST_LEN bytes of <b>buf</b>. Return 0 on
915 * success, -1 on failure.
918 decode_hashed_password(char *buf
, const char *hashed
)
921 if (!strcmpstart(hashed
, "16:")) {
922 if (base16_decode(decoded
, sizeof(decoded
), hashed
+3, strlen(hashed
+3))<0
923 || strlen(hashed
+3) != (S2K_SPECIFIER_LEN
+DIGEST_LEN
)*2) {
927 if (base64_decode(decoded
, sizeof(decoded
), hashed
, strlen(hashed
))
928 != S2K_SPECIFIER_LEN
+DIGEST_LEN
) {
933 memcpy(buf
, decoded
, S2K_SPECIFIER_LEN
+DIGEST_LEN
);
937 /** Called when we get an AUTHENTICATE message. Check whether the
938 * authentication is valid, and if so, update the connection's state to
939 * OPEN. Reply with DONE or ERROR.
942 handle_control_authenticate(connection_t
*conn
, uint32_t len
, const char *body
)
944 or_options_t
*options
= get_options();
947 if (STATE_IS_V0(conn
->state
)) {
948 password
= (char*)body
;
951 if (TOR_ISXDIGIT(body
[0])) {
953 while (TOR_ISXDIGIT(body
[i
]))
955 password
= tor_malloc(i
/2 + 1);
956 if (base16_decode(password
, i
/2+1, body
, i
)<0) {
957 connection_write_str_to_buf("551 Invalid hexadecimal encoding\r\n", conn
);
962 } else if (TOR_ISSPACE(body
[0])) {
963 password
= tor_strdup("");
966 if (!get_escaped_string(body
, len
, &password
, &password_len
)) {
967 connection_write_str_to_buf("551 Invalid quoted string\r\n", conn
);
972 if (options
->CookieAuthentication
) {
973 if (len
== AUTHENTICATION_COOKIE_LEN
&&
974 !memcmp(authentication_cookie
, password
, password_len
)) {
977 } else if (options
->HashedControlPassword
) {
978 char expected
[S2K_SPECIFIER_LEN
+DIGEST_LEN
];
979 char received
[DIGEST_LEN
];
980 if (decode_hashed_password(expected
, options
->HashedControlPassword
)<0) {
981 log_fn(LOG_WARN
,"Couldn't decode HashedControlPassword: invalid base64");
984 secret_to_key(received
,DIGEST_LEN
,password
,password_len
,expected
);
985 if (!memcmp(expected
+S2K_SPECIFIER_LEN
, received
, DIGEST_LEN
))
989 /* if Tor doesn't demand any stronger authentication, then
990 * the controller can get in with anything. */
995 if (STATE_IS_V0(conn
->state
))
996 send_control0_error(conn
,ERR_REJECTED_AUTHENTICATION
,"Authentication failed");
999 connection_write_str_to_buf("515 Authentication failed\r\n", conn
);
1003 log_fn(LOG_INFO
, "Authenticated control connection (%d)", conn
->s
);
1004 send_control_done(conn
);
1005 if (STATE_IS_V0(conn
->state
))
1006 conn
->state
= CONTROL_CONN_STATE_OPEN_V0
;
1008 conn
->state
= CONTROL_CONN_STATE_OPEN_V1
;
1014 /** Called when we get a SAVECONF command. Try to flush the current options to
1015 * disk, and report success or failure. */
1017 handle_control_saveconf(connection_t
*conn
, uint32_t len
,
1020 if (options_save_current()<0) {
1021 if (STATE_IS_V0(conn
->state
))
1022 send_control0_error(conn
, ERR_INTERNAL
,
1023 "Unable to write configuration to disk.");
1025 connection_write_str_to_buf("551 Unable to write configuration to disk.",
1028 send_control_done(conn
);
1033 /** Called when we get a SIGNAL command. React to the provided signal, and
1034 * report success or failure. (If the signal results in a shutdown, success
1035 * may not be reported.) */
1037 handle_control_signal(connection_t
*conn
, uint32_t len
,
1041 if (STATE_IS_V0(conn
->state
)) {
1043 send_control0_error(conn
, ERR_SYNTAX
,
1044 "Body of SIGNAL command too long or too short.");
1047 sig
= (uint8_t)body
[0];
1052 while (body
[n
] && ! TOR_ISSPACE(body
[n
]))
1054 s
= tor_strndup(body
, n
);
1055 if (!strcasecmp(s
, "RELOAD") || !strcasecmp(s
, "HUP"))
1057 else if (!strcasecmp(s
, "SHUTDOWN") || !strcasecmp(s
, "INT"))
1059 else if (!strcasecmp(s
, "DUMP") || !strcasecmp(s
, "USR1"))
1061 else if (!strcasecmp(s
, "DEBUG") || !strcasecmp(s
, "USR2"))
1063 else if (!strcasecmp(s
, "HALT") || !strcasecmp(s
, "TERM"))
1066 connection_printf_to_buf(conn
, "552 Unrecognized signal code \"%s\"\r\n",
1075 if (control_signal_act(sig
) < 0) {
1076 if (STATE_IS_V0(conn
->state
))
1077 send_control0_error(conn
, ERR_SYNTAX
, "Unrecognized signal number.");
1079 connection_write_str_to_buf("551 Internal error acting on signal\r\n",
1082 send_control_done(conn
);
1087 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1088 * and report success or failrue. */
1090 handle_control_mapaddress(connection_t
*conn
, uint32_t len
, const char *body
)
1097 int v0
= STATE_IS_V0(conn
->state
);
1098 lines
= smartlist_create();
1099 elts
= smartlist_create();
1100 reply
= smartlist_create();
1102 smartlist_split_string(lines
, body
, "\n",
1103 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1105 smartlist_split_string(lines
, body
, " ",
1106 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1107 /* XXXX Make errors conformant. */
1108 SMARTLIST_FOREACH(lines
, char *, line
,
1112 smartlist_split_string(elts
, line
, " ", 0, 2);
1114 smartlist_split_string(elts
, line
, "=", 0, 2);
1115 if (smartlist_len(elts
) == 2) {
1116 const char *from
= smartlist_get(elts
,0);
1117 const char *to
= smartlist_get(elts
,1);
1118 if (!is_plausible_address(from
)) {
1119 log_fn(LOG_WARN
,"Skipping invalid argument '%s' in MapAddress msg",from
);
1120 } else if (!is_plausible_address(to
)) {
1121 log_fn(LOG_WARN
,"Skipping invalid argument '%s' in MapAddress msg",to
);
1122 } else if (!strcmp(from
, ".") || !strcmp(from
, "0.0.0.0")) {
1123 const char *addr
= addressmap_register_virtual_address(
1124 !strcmp(from
,".") ? RESOLVED_TYPE_HOSTNAME
: RESOLVED_TYPE_IPV4
,
1128 "Unable to allocate address for '%s' in MapAddress msg",
1131 size_t anslen
= strlen(addr
)+strlen(to
)+8;
1132 char *ans
= tor_malloc(anslen
);
1134 tor_snprintf(ans
, anslen
, "%s %s", addr
, to
);
1136 tor_snprintf(ans
, anslen
, "250-%s=%s", addr
, to
);
1137 smartlist_add(reply
, ans
);
1140 addressmap_register(from
, tor_strdup(to
), 1);
1142 smartlist_add(reply
, tor_strdup(line
));
1144 size_t anslen
= strlen(line
)+8;
1145 char *ans
= tor_malloc(anslen
);
1146 tor_snprintf(ans
, anslen
, "250-%s", line
);
1147 smartlist_add(reply
, ans
);
1151 log_fn(LOG_WARN
, "Skipping MapAddress line with wrong number of items.");
1153 SMARTLIST_FOREACH(elts
, char *, cp
, tor_free(cp
));
1154 smartlist_clear(elts
);
1156 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
1157 smartlist_free(lines
);
1158 smartlist_free(elts
);
1161 r
= smartlist_join_strings(reply
, "\n", 1, &sz
);
1162 send_control_done2(conn
,r
,sz
);
1164 if (smartlist_len(reply
))
1165 ((char*)smartlist_get(reply
,smartlist_len(reply
)-1))[3] = ' ';
1166 r
= smartlist_join_strings(reply
, "\r\n", 1, &sz
);
1167 connection_write_to_buf(r
, sz
, conn
);
1170 SMARTLIST_FOREACH(reply
, char *, cp
, tor_free(cp
));
1171 smartlist_free(reply
);
1176 /** Return a newly allocated string listing all valid GETINFO fields as
1177 * required by GETINFO info/names. */
1179 list_getinfo_options(void)
1182 "accounting/bytes Number of bytes read/written so far in interval.\n"
1183 "accounting/bytes-left Number of bytes left to read/write in interval.\n"
1184 "accounting/enabled Is accounting currently enabled?\n"
1185 "accounting/hibernating Are we hibernating or awake?\n"
1186 "accounting/interval-end Time when interval ends.\n"
1187 "accounting/interval-start Time when interval starts.\n"
1188 "accounting/interval-wake Time to wake up in this interval.\n"
1189 "addr-mappings/all All current remapped addresses.\n"
1190 "addr-mappings/cache Addresses remapped by DNS cache.\n"
1191 "addr-mappings/configl Addresses remapped from configuration options.\n"
1192 "addr-mappings/control Addresses remapped by a controller.\n"
1193 "circuit-status Status of each current circuit.\n"
1194 "config/names List of configuration options, types, and documentation.\n"
1195 "desc/id/* Server descriptor by hex ID\n"
1196 "desc/name/* Server descriptor by nickname.\n"
1197 "helper-nodes Which nodes will we use as helpers?\n"
1198 "info/names List of GETINFO options, types, and documentation.\n"
1199 "network-status List of hex IDs, nicknames, server statuses.\n"
1200 "orconn-status Status of each current OR connection.\n"
1201 "stream-status Status of each current application stream.\n"
1202 "version The current version of Tor.\n");
1205 /** Lookup the 'getinfo' entry <b>question</b>, and return
1206 * the answer in <b>*answer</b> (or NULL if key not recognized).
1207 * Return 0 if success, or -1 if internal error. */
1209 handle_getinfo_helper(const char *question
, char **answer
)
1211 *answer
= NULL
; /* unrecognized key by default */
1212 if (!strcmp(question
, "version")) {
1213 *answer
= tor_strdup(VERSION
);
1214 } else if (!strcmp(question
, "config-file")) {
1215 *answer
= tor_strdup(get_torrc_fname());
1216 } else if (!strcmpstart(question
, "accounting/")) {
1217 return accounting_getinfo_helper(question
, answer
);
1218 } else if (!strcmpstart(question
, "helper-nodes")) {
1219 return helper_nodes_getinfo_helper(question
, answer
);
1220 } else if (!strcmpstart(question
, "config/")) {
1221 return config_getinfo_helper(question
, answer
);
1222 } else if (!strcmp(question
, "info/names")) {
1223 *answer
= list_getinfo_options();
1224 } else if (!strcmpstart(question
, "desc/id/")) {
1225 routerinfo_t
*ri
= router_get_by_hexdigest(question
+strlen("desc/id/"));
1226 if (ri
&& ri
->signed_descriptor
)
1227 *answer
= tor_strdup(ri
->signed_descriptor
);
1228 } else if (!strcmpstart(question
, "desc/name/")) {
1229 routerinfo_t
*ri
= router_get_by_nickname(question
+strlen("desc/name/"),1);
1230 if (ri
&& ri
->signed_descriptor
)
1231 *answer
= tor_strdup(ri
->signed_descriptor
);
1232 } else if (!strcmpstart(question
, "unregistered-servers-")) {
1233 *answer
= dirserver_getinfo_unregistered(question
+
1234 strlen("unregistered-servers-"));
1235 } else if (!strcmp(question
, "network-status")) {
1236 routerlist_t
*routerlist
;
1237 router_get_routerlist(&routerlist
);
1238 if (!routerlist
|| !routerlist
->routers
||
1239 list_server_status(routerlist
->routers
, answer
) < 0) {
1242 } else if (!strcmp(question
, "circuit-status")) {
1244 smartlist_t
*status
= smartlist_create();
1245 for (circ
= _circuit_get_global_list(); circ
; circ
= circ
->next
) {
1249 if (! CIRCUIT_IS_ORIGIN(circ
) || circ
->marked_for_close
)
1251 path
= circuit_list_path(circ
,0);
1252 if (circ
->state
== CIRCUIT_STATE_OPEN
)
1254 else if (strlen(path
))
1259 slen
= strlen(path
)+strlen(state
)+20;
1260 s
= tor_malloc(slen
+1);
1261 tor_snprintf(s
, slen
, "%lu %s %s", (unsigned long)circ
->global_identifier
,
1263 smartlist_add(status
, s
);
1266 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1267 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1268 smartlist_free(status
);
1269 } else if (!strcmp(question
, "stream-status")) {
1270 connection_t
**conns
;
1273 smartlist_t
*status
= smartlist_create();
1274 get_connection_array(&conns
, &n_conns
);
1275 for (i
=0; i
< n_conns
; ++i
) {
1280 if (conns
[i
]->type
!= CONN_TYPE_AP
||
1281 conns
[i
]->marked_for_close
||
1282 conns
[i
]->state
== AP_CONN_STATE_SOCKS_WAIT
)
1284 switch (conns
[i
]->state
)
1286 case AP_CONN_STATE_CONTROLLER_WAIT
:
1287 case AP_CONN_STATE_CIRCUIT_WAIT
:
1288 if (conns
[i
]->socks_request
&&
1289 conns
[i
]->socks_request
->command
== SOCKS_COMMAND_RESOLVE
)
1290 state
= "NEWRESOLVE";
1294 case AP_CONN_STATE_RENDDESC_WAIT
:
1295 case AP_CONN_STATE_CONNECT_WAIT
:
1296 state
= "SENTCONNECT"; break;
1297 case AP_CONN_STATE_RESOLVE_WAIT
:
1298 state
= "SENTRESOLVE"; break;
1299 case AP_CONN_STATE_OPEN
:
1300 state
= "SUCCEEDED"; break;
1302 log_fn(LOG_WARN
, "Asked for stream in unknown state %d",
1306 circ
= circuit_get_by_edge_conn(conns
[i
]);
1307 write_stream_target_to_buf(conns
[i
], buf
, sizeof(buf
));
1308 slen
= strlen(buf
)+strlen(state
)+32;
1309 s
= tor_malloc(slen
+1);
1310 tor_snprintf(s
, slen
, "%lu %s %lu %s",
1311 (unsigned long) conns
[i
]->global_identifier
,state
,
1312 circ
?(unsigned long)circ
->global_identifier
: 0ul,
1314 smartlist_add(status
, s
);
1316 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1317 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1318 smartlist_free(status
);
1319 } else if (!strcmp(question
, "orconn-status")) {
1320 connection_t
**conns
;
1322 smartlist_t
*status
= smartlist_create();
1323 get_connection_array(&conns
, &n_conns
);
1324 for (i
=0; i
< n_conns
; ++i
) {
1328 if (conns
[i
]->type
!= CONN_TYPE_OR
|| conns
[i
]->marked_for_close
)
1330 if (conns
[i
]->state
== OR_CONN_STATE_OPEN
)
1331 state
= "CONNECTED";
1334 slen
= strlen(conns
[i
]->nickname
)+strlen(state
)+2;
1335 s
= tor_malloc(slen
+1);
1336 tor_snprintf(s
, slen
, "%s %s",conns
[i
]->nickname
,state
);
1337 smartlist_add(status
, s
);
1339 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1340 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1341 smartlist_free(status
);
1342 } else if (!strcmpstart(question
, "addr-mappings/")) {
1343 time_t min_e
, max_e
;
1344 smartlist_t
*mappings
;
1345 if (!strcmp(question
, "addr-mappings/all")) {
1346 min_e
= 0; max_e
= TIME_MAX
;
1347 } else if (!strcmp(question
, "addr-mappings/cache")) {
1348 min_e
= 2; max_e
= TIME_MAX
;
1349 } else if (!strcmp(question
, "addr-mappings/config")) {
1350 min_e
= 0; max_e
= 0;
1351 } else if (!strcmp(question
, "addr-mappings/control")) {
1352 min_e
= 1; max_e
= 1;
1356 mappings
= smartlist_create();
1357 addressmap_get_mappings(mappings
, min_e
, max_e
);
1358 *answer
= smartlist_join_strings(mappings
, "\n", 0, NULL
);
1359 SMARTLIST_FOREACH(mappings
, char *, cp
, tor_free(cp
));
1360 smartlist_free(mappings
);
1365 /** Called when we receive a GETINFO command. Try to fetch all requested
1366 * information, and reply with information or error message. */
1368 handle_control_getinfo(connection_t
*conn
, uint32_t len
, const char *body
)
1370 smartlist_t
*questions
= NULL
;
1371 smartlist_t
*answers
= NULL
;
1372 smartlist_t
*unrecognized
= NULL
;
1373 char *msg
= NULL
, *ans
= NULL
;
1375 int v0
= STATE_IS_V0(conn
->state
);
1377 questions
= smartlist_create();
1379 smartlist_split_string(questions
, body
, "\n",
1380 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1382 smartlist_split_string(questions
, body
, " ",
1383 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1384 answers
= smartlist_create();
1385 unrecognized
= smartlist_create();
1386 SMARTLIST_FOREACH(questions
, const char *, q
,
1388 if (handle_getinfo_helper(q
, &ans
) < 0) {
1390 send_control0_error(conn
, ERR_INTERNAL
, body
);
1392 connection_write_str_to_buf("551 Internal error\r\n", conn
);
1397 send_control0_error(conn
, ERR_UNRECOGNIZED_CONFIG_KEY
, body
);
1400 smartlist_add(unrecognized
, (char*)q
);
1402 smartlist_add(answers
, tor_strdup(q
));
1403 smartlist_add(answers
, ans
);
1406 if (smartlist_len(unrecognized
)) {
1409 for (i
=0; i
< smartlist_len(unrecognized
)-1; ++i
)
1410 connection_printf_to_buf(conn
,
1411 "552-Unrecognized key \"%s\"\r\n",
1412 (char*)smartlist_get(unrecognized
, i
));
1413 connection_printf_to_buf(conn
,
1414 "552 Unrecognized key \"%s\"\r\n",
1415 (char*)smartlist_get(unrecognized
, i
));
1420 msg
= smartlist_join_strings2(answers
, "\0", 1, 1, &msg_len
);
1421 tor_assert(msg_len
> 0); /* it will at least be terminated */
1422 send_control0_message(conn
, CONTROL0_CMD_INFOVALUE
,
1424 } else if (smartlist_len(answers
)) {
1426 for (i
= 0; i
< smartlist_len(answers
); i
+= 2) {
1427 char *k
= smartlist_get(answers
, i
);
1428 char *v
= smartlist_get(answers
, i
+1);
1429 /*XXXX Not an adequate test! XXXX011 */
1430 if (!strchr(v
, '\n') && !strchr(v
, '\r')) {
1431 connection_printf_to_buf(conn
, "250-%s=", k
);
1432 connection_write_str_to_buf(v
, conn
);
1433 connection_write_str_to_buf("\r\n", conn
);
1437 len
= write_escaped_data(v
, strlen(v
), 1, &esc
);
1438 connection_printf_to_buf(conn
, "250+%s=\r\n", k
);
1439 connection_write_to_buf(esc
, len
, conn
);
1443 connection_write_str_to_buf("250 OK\r\n", conn
);
1447 if (answers
) SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
1448 if (questions
) SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
1449 smartlist_free(answers
);
1450 smartlist_free(questions
);
1451 smartlist_free(unrecognized
);
1457 /** Callled when we get an EXTENDCIRCUIT message. Try to extend the listed
1458 * circuit, and report succcess or failure. */
1460 handle_control_extendcircuit(connection_t
*conn
, uint32_t len
,
1463 smartlist_t
*router_nicknames
=NULL
, *routers
=NULL
;
1465 circuit_t
*circ
= NULL
;
1469 v0
= STATE_IS_V0(conn
->state
);
1470 router_nicknames
= smartlist_create();
1474 send_control0_error(conn
, ERR_SYNTAX
, "extendcircuit message too short");
1477 smartlist_split_string(router_nicknames
, body
+4, ",", 0, 0);
1478 circ_id
= ntohl(get_uint32(body
));
1480 /* start a new circuit */
1483 circ
= circuit_get_by_global_id(circ_id
);
1486 send_control0_error(conn
, ERR_NO_CIRC
,
1487 "No circuit found with given ID");
1493 args
= smartlist_create();
1494 smartlist_split_string(args
, body
, " ",
1495 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1496 if (smartlist_len(args
)<2)
1497 connection_printf_to_buf(conn
,"512 Missing argument to EXTENDCIRCUIT\r\n");
1499 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,0));
1500 if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
,0)))) {
1501 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
1502 (char*)smartlist_get(args
, 0));
1504 smartlist_split_string(router_nicknames
, smartlist_get(args
,1), ",", 0, 0);
1506 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
1507 smartlist_free(args
);
1508 if (!zero_circ
&& !circ
) {
1513 routers
= smartlist_create();
1514 SMARTLIST_FOREACH(router_nicknames
, const char *, n
,
1516 routerinfo_t
*r
= router_get_by_nickname(n
, 1);
1519 send_control0_error(conn
, ERR_NO_ROUTER
, n
);
1521 connection_printf_to_buf(conn
, "552 No such router \"%s\"\r\n", n
);
1524 smartlist_add(routers
, r
);
1526 if (!smartlist_len(routers
)) {
1528 send_control0_error(conn
, ERR_SYNTAX
, "No router names provided");
1530 connection_write_str_to_buf("512 No router names provided\r\n", conn
);
1535 /* start a new circuit */
1536 circ
= circuit_init(CIRCUIT_PURPOSE_C_GENERAL
, 0, 0, 0);
1539 /* now circ refers to something that is ready to be extended */
1540 SMARTLIST_FOREACH(routers
, routerinfo_t
*, r
,
1542 extend_info_t
*info
= extend_info_from_router(r
);
1543 circuit_append_new_exit(circ
, info
);
1544 extend_info_free(info
);
1547 /* now that we've populated the cpath, start extending */
1549 if (circuit_handle_first_hop(circ
) < 0) {
1550 circuit_mark_for_close(circ
);
1552 send_control0_error(conn
, ERR_INTERNAL
, "couldn't start circuit");
1554 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
1558 if (circ
->state
== CIRCUIT_STATE_OPEN
) {
1559 circ
->state
= CIRCUIT_STATE_BUILDING
;
1560 if (circuit_send_next_onion_skin(circ
) < 0) {
1561 log_fn(LOG_INFO
,"send_next_onion_skin failed; circuit marked for closing.");
1562 circuit_mark_for_close(circ
);
1564 send_control0_error(conn
, ERR_INTERNAL
, "couldn't send onion skin");
1566 connection_write_str_to_buf("551 Couldn't send onion skinr\n", conn
);
1573 set_uint32(reply
, htonl(circ
->global_identifier
));
1574 send_control_done2(conn
, reply
, sizeof(reply
));
1576 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
1577 (unsigned long)circ
->global_identifier
);
1580 SMARTLIST_FOREACH(router_nicknames
, char *, n
, tor_free(n
));
1581 smartlist_free(router_nicknames
);
1583 smartlist_free(routers
);
1587 /** Callled when we get an ATTACHSTREAM message. Try to attach the requested
1588 * stream, and report succcess or failure. */
1590 handle_control_attachstream(connection_t
*conn
, uint32_t len
,
1593 connection_t
*ap_conn
= NULL
;
1594 circuit_t
*circ
= NULL
;
1597 if (STATE_IS_V0(conn
->state
)) {
1601 send_control0_error(conn
, ERR_SYNTAX
, "attachstream message too short");
1605 conn_id
= ntohl(get_uint32(body
));
1606 circ_id
= ntohl(get_uint32(body
+4));
1607 zero_circ
= circ_id
== 0;
1609 if (!(ap_conn
= connection_get_by_global_id(conn_id
))) {
1610 send_control0_error(conn
, ERR_NO_STREAM
,
1611 "No connection found with given ID");
1614 if (circ_id
&& !(circ
= circuit_get_by_global_id(circ_id
))) {
1615 send_control0_error(conn
, ERR_NO_CIRC
, "No circuit found with given ID");
1620 args
= smartlist_create();
1621 smartlist_split_string(args
, body
, " ",
1622 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1623 if (smartlist_len(args
)<2)
1624 connection_printf_to_buf(conn
,"512 Missing argument to ATTACHSTREAM\r\n");
1626 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,1));
1628 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))) {
1629 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
1630 (char*)smartlist_get(args
, 0));
1631 } else if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
, 1)))) {
1632 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
1633 (char*)smartlist_get(args
, 1));
1635 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
1636 smartlist_free(args
);
1637 if (!ap_conn
|| (!zero_circ
&& !circ
))
1641 if (ap_conn
->state
!= AP_CONN_STATE_CONTROLLER_WAIT
) {
1642 if (STATE_IS_V0(conn
->state
)) {
1643 send_control0_error(conn
, ERR_NO_STREAM
,
1644 "Connection is not managed by controller.");
1646 connection_write_str_to_buf(
1647 "555 Connection is not managed by controller.\r\n",
1654 ap_conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1655 if (connection_ap_handshake_attach_circuit(ap_conn
)<0)
1656 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_CANT_ATTACH
);
1657 send_control_done(conn
);
1660 if (circ
->state
!= CIRCUIT_STATE_OPEN
) {
1661 if (STATE_IS_V0(conn
->state
))
1662 send_control0_error(conn
, ERR_INTERNAL
, "Refuse to attach stream to non-open circ.");
1664 connection_write_str_to_buf(
1665 "551 Can't attach stream to non-open circuit\r\n",
1669 if (connection_ap_handshake_attach_chosen_circuit(ap_conn
, circ
) != 1) {
1670 if (STATE_IS_V0(conn
->state
))
1671 send_control0_error(conn
, ERR_INTERNAL
, "Unable to attach stream.");
1673 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn
);
1676 send_control_done(conn
);
1681 /** Callled when we get a POSTDESCRIPTORT message. Try to learn the provided
1682 * descriptor, and report succcess or failure. */
1684 handle_control_postdescriptor(connection_t
*conn
, uint32_t len
,
1688 int v0
= STATE_IS_V0(conn
->state
);
1689 const char *msg
=NULL
;
1694 const char *cp
= memchr(body
, '\n', len
);
1696 read_escaped_data(cp
, len
-(cp
-body
), 1, &desc
);
1699 switch (router_load_single_router(desc
, &msg
)) {
1701 if (!msg
) msg
= "Could not parse descriptor";
1703 send_control0_error(conn
,ERR_SYNTAX
,msg
);
1705 connection_printf_to_buf(conn
, "554 %s\r\n", msg
);
1708 if (!msg
) msg
= "Descriptor not added";
1710 send_control_done2(conn
,msg
,0);
1712 connection_printf_to_buf(conn
, "251 %s\r\n",msg
);
1715 send_control_done(conn
);
1724 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
1725 * adderess of the named AP steream, and report success or failure. */
1727 handle_control_redirectstream(connection_t
*conn
, uint32_t len
,
1730 connection_t
*ap_conn
= NULL
;
1732 char *new_addr
= NULL
;
1733 if (STATE_IS_V0(conn
->state
)) {
1735 send_control0_error(conn
, ERR_SYNTAX
, "redirectstream message too short");
1738 conn_id
= ntohl(get_uint32(body
));
1740 if (!(ap_conn
= connection_get_by_global_id(conn_id
))
1741 || ap_conn
->state
!= CONN_TYPE_AP
1742 || !ap_conn
->socks_request
) {
1743 send_control0_error(conn
, ERR_NO_STREAM
,
1744 "No AP connection found with given ID");
1747 new_addr
= tor_strdup(body
+4);
1750 args
= smartlist_create();
1751 smartlist_split_string(args
, body
, " ",
1752 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1753 if (smartlist_len(args
)<2)
1754 connection_printf_to_buf(conn
,"512 Missing argument to REDIRECTSTREAM\r\n");
1755 else if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))
1756 || !ap_conn
->socks_request
) {
1757 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
1758 (char*)smartlist_get(args
, 0));
1760 new_addr
= tor_strdup(smartlist_get(args
, 1));
1763 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
1764 smartlist_free(args
);
1769 strlcpy(ap_conn
->socks_request
->address
, new_addr
,
1770 sizeof(ap_conn
->socks_request
->address
));
1772 send_control_done(conn
);
1776 /** Called when we get a CLOSESTREAM command; try to close the named stream
1777 * and report success or failure. */
1779 handle_control_closestream(connection_t
*conn
, uint32_t len
,
1782 connection_t
*ap_conn
=NULL
;
1785 if (STATE_IS_V0(conn
->state
)) {
1788 send_control0_error(conn
, ERR_SYNTAX
, "closestream message too short");
1792 conn_id
= ntohl(get_uint32(body
));
1793 reason
= *(uint8_t*)(body
+4);
1795 if (!(ap_conn
= connection_get_by_global_id(conn_id
))
1796 || ap_conn
->state
!= CONN_TYPE_AP
1797 || !ap_conn
->socks_request
) {
1798 send_control0_error(conn
, ERR_NO_STREAM
,
1799 "No AP connection found with given ID");
1805 args
= smartlist_create();
1806 smartlist_split_string(args
, body
, " ",
1807 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1808 if (smartlist_len(args
)<2)
1809 connection_printf_to_buf(conn
, "512 Missing argument to CLOSESTREAM\r\n");
1810 else if (!(ap_conn
= get_stream(smartlist_get(args
, 0))))
1811 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
1812 (char*)smartlist_get(args
, 0));
1814 reason
= (uint8_t) tor_parse_ulong(smartlist_get(args
,1), 10, 0, 255,
1817 connection_printf_to_buf(conn
, "552 Unrecognized reason \"%s\"\r\n",
1818 (char*)smartlist_get(args
, 1));
1822 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
1823 smartlist_free(args
);
1828 connection_mark_unattached_ap(ap_conn
, reason
);
1829 send_control_done(conn
);
1833 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
1834 * and report success or failure. */
1836 handle_control_closecircuit(connection_t
*conn
, uint32_t len
,
1839 circuit_t
*circ
= NULL
;
1842 if (STATE_IS_V0(conn
->state
)) {
1845 send_control0_error(conn
, ERR_SYNTAX
, "closecircuit message too short");
1848 circ_id
= ntohl(get_uint32(body
));
1849 safe
= (*(uint8_t*)(body
+4)) & 1;
1851 if (!(circ
= circuit_get_by_global_id(circ_id
))) {
1852 send_control0_error(conn
, ERR_NO_CIRC
,
1853 "No circuit found with given ID");
1858 args
= smartlist_create();
1859 smartlist_split_string(args
, body
, " ",
1860 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1861 if (smartlist_len(args
)<1)
1862 connection_printf_to_buf(conn
, "512 Missing argument to CLOSECIRCUIT\r\n");
1863 else if (!(circ
=get_circ(smartlist_get(args
, 0))))
1864 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
1865 (char*)smartlist_get(args
, 0));
1868 for (i
=1; i
< smartlist_len(args
); ++i
) {
1869 if (!strcasecmp(smartlist_get(args
, i
), "IfUnused"))
1872 log_fn(LOG_INFO
, "Skipping unknown option %s",
1873 (char*)smartlist_get(args
,i
));
1876 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
1877 smartlist_free(args
);
1882 if (!safe
|| !circ
->p_streams
) {
1883 circuit_mark_for_close(circ
);
1886 send_control_done(conn
);
1890 /** Called when we get a v0 FRAGMENTHEADER or FRAGMENT command; try to append
1891 * the data to conn->incoming_cmd, setting conn->incoming_(type|len|cur_len)
1892 * as appropriate. If the command is malformed, drop it and all pending
1893 * fragments and report failure.
1896 handle_control_fragments(connection_t
*conn
, uint16_t command_type
,
1897 uint32_t body_len
, char *body
)
1899 if (command_type
== CONTROL0_CMD_FRAGMENTHEADER
) {
1900 if (conn
->incoming_cmd
) {
1901 log_fn(LOG_WARN
, "Dropping incomplete fragmented command");
1902 tor_free(conn
->incoming_cmd
);
1905 send_control0_error(conn
, ERR_SYNTAX
, "FRAGMENTHEADER too short.");
1908 conn
->incoming_cmd_type
= ntohs(get_uint16(body
));
1909 conn
->incoming_cmd_len
= ntohl(get_uint32(body
+2));
1910 conn
->incoming_cmd_cur_len
= 0;
1911 conn
->incoming_cmd
= tor_malloc(conn
->incoming_cmd_len
);
1914 } else if (command_type
== CONTROL0_CMD_FRAGMENT
) {
1915 if (!conn
->incoming_cmd
) {
1916 send_control0_error(conn
, ERR_SYNTAX
, "Out-of-place FRAGMENT");
1923 if (conn
->incoming_cmd_cur_len
+ body_len
> conn
->incoming_cmd_len
) {
1924 tor_free(conn
->incoming_cmd
);
1925 send_control0_error(conn
, ERR_SYNTAX
,
1926 "Fragmented data exceeds declared length");
1929 memcpy(conn
->incoming_cmd
+ conn
->incoming_cmd_cur_len
,
1931 conn
->incoming_cmd_cur_len
+= body_len
;
1935 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
1937 connection_control_finished_flushing(connection_t
*conn
)
1940 tor_assert(conn
->type
== CONN_TYPE_CONTROL
);
1942 connection_stop_writing(conn
);
1946 /** Called when <b>conn</b> has gotten its socket closed. */
1948 connection_control_reached_eof(connection_t
*conn
)
1951 tor_assert(conn
->type
== CONN_TYPE_CONTROL
);
1953 log_fn(LOG_INFO
,"Control connection reached EOF. Closing.");
1954 connection_mark_for_close(conn
);
1958 /** Called when data has arrived on a v1 control connection: Try to fetch
1959 * commands from conn->inbuf, and execute them.
1962 connection_control_process_inbuf_v1(connection_t
*conn
)
1969 tor_assert(conn
->type
== CONN_TYPE_CONTROL
);
1970 tor_assert(conn
->state
== CONTROL_CONN_STATE_OPEN_V1
||
1971 conn
->state
== CONTROL_CONN_STATE_NEEDAUTH_V1
);
1973 if (!conn
->incoming_cmd
) {
1974 conn
->incoming_cmd
= tor_malloc(1024);
1975 conn
->incoming_cmd_len
= 1024;
1976 conn
->incoming_cmd_cur_len
= 0;
1983 /* First, fetch a line. */
1985 data_len
= conn
->incoming_cmd_len
- conn
->incoming_cmd_cur_len
;
1986 r
= fetch_from_buf_line(conn
->inbuf
,
1987 conn
->incoming_cmd
+conn
->incoming_cmd_cur_len
,
1990 /* Line not all here yet. Wait. */
1993 while (conn
->incoming_cmd_len
< data_len
+conn
->incoming_cmd_cur_len
)
1994 conn
->incoming_cmd_len
*= 2;
1995 conn
->incoming_cmd
= tor_realloc(conn
->incoming_cmd
,
1996 conn
->incoming_cmd_len
);
2000 tor_assert(data_len
);
2002 last_idx
= conn
->incoming_cmd_cur_len
;
2003 conn
->incoming_cmd_cur_len
+= data_len
;
2005 /* We have appended a line to incoming_cmd. Is the command done? */
2006 if (last_idx
== 0 && *conn
->incoming_cmd
!= '+')
2007 /* One line command, didn't start with '+'. */
2009 if (last_idx
+3 == conn
->incoming_cmd_cur_len
&&
2010 !memcmp(conn
->incoming_cmd
+ last_idx
, ".\r\n", 3)) {
2011 /* Just appended ".\r\n"; we're done. Remove it. */
2012 conn
->incoming_cmd_cur_len
-= 3;
2015 /* Otherwise, read another line. */
2017 data_len
= conn
->incoming_cmd_cur_len
;
2018 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
2022 while ((size_t)cmd_len
< data_len
2023 && !TOR_ISSPACE(conn
->incoming_cmd
[cmd_len
]))
2027 log_fn(LOG_NOTICE, "READ A COMMAND FROM THE BUFFER: <%s> [%d]",
2028 conn->incoming_cmd, (int)cmd_len);
2030 data_len
-= cmd_len
;
2031 conn
->incoming_cmd
[cmd_len
]='\0';
2032 args
= conn
->incoming_cmd
+cmd_len
+1;
2033 while (*args
== ' ' || *args
== '\t') {
2038 log_fn(LOG_NOTICE, "COMMAND IS: <%s>", conn->incoming_cmd);
2039 log_fn(LOG_NOTICE, "ARGS ARE: <%s>", args);
2042 if (!strcasecmp(conn
->incoming_cmd
, "QUIT")) {
2043 connection_write_str_to_buf("250 closing connection\r\n", conn
);
2044 connection_mark_for_close(conn
);
2048 if (conn
->state
== CONTROL_CONN_STATE_NEEDAUTH_V1
&&
2049 strcasecmp(conn
->incoming_cmd
, "AUTHENTICATE")) {
2050 connection_write_str_to_buf("514 Authentication required.\r\n", conn
);
2051 conn
->incoming_cmd_cur_len
= 0;
2055 if (!strcasecmp(conn
->incoming_cmd
, "SETCONF")) {
2056 if (handle_control_setconf(conn
, data_len
, args
))
2058 } else if (!strcasecmp(conn
->incoming_cmd
, "RESETCONF")) {
2059 if (handle_control_resetconf(conn
, data_len
, args
))
2061 } else if (!strcasecmp(conn
->incoming_cmd
, "GETCONF")) {
2062 if (handle_control_getconf(conn
, data_len
, args
))
2064 } else if (!strcasecmp(conn
->incoming_cmd
, "SETEVENTS")) {
2065 if (handle_control_setevents(conn
, data_len
, args
))
2067 } else if (!strcasecmp(conn
->incoming_cmd
, "AUTHENTICATE")) {
2068 if (handle_control_authenticate(conn
, data_len
, args
))
2070 } else if (!strcasecmp(conn
->incoming_cmd
, "SAVECONF")) {
2071 if (handle_control_saveconf(conn
, data_len
, args
))
2073 } else if (!strcasecmp(conn
->incoming_cmd
, "SIGNAL")) {
2074 if (handle_control_signal(conn
, data_len
, args
))
2076 } else if (!strcasecmp(conn
->incoming_cmd
, "MAPADDRESS")) {
2077 if (handle_control_mapaddress(conn
, data_len
, args
))
2079 } else if (!strcasecmp(conn
->incoming_cmd
, "GETINFO")) {
2080 if (handle_control_getinfo(conn
, data_len
, args
))
2082 } else if (!strcasecmp(conn
->incoming_cmd
, "EXTENDCIRCUIT")) {
2083 if (handle_control_extendcircuit(conn
, data_len
, args
))
2085 } else if (!strcasecmp(conn
->incoming_cmd
, "ATTACHSTREAM")) {
2086 if (handle_control_attachstream(conn
, data_len
, args
))
2088 } else if (!strcasecmp(conn
->incoming_cmd
, "+POSTDESCRIPTOR")) {
2089 if (handle_control_postdescriptor(conn
, data_len
, args
))
2091 } else if (!strcasecmp(conn
->incoming_cmd
, "REDIRECTSTREAM")) {
2092 if (handle_control_redirectstream(conn
, data_len
, args
))
2094 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSESTREAM")) {
2095 if (handle_control_closestream(conn
, data_len
, args
))
2097 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSECIRCUIT")) {
2098 if (handle_control_closecircuit(conn
, data_len
, args
))
2101 connection_printf_to_buf(conn
, "510 Unrecognized command \"%s\"\r\n",
2102 conn
->incoming_cmd
);
2105 conn
->incoming_cmd_cur_len
= 0;
2109 /** Called when data has arrived on a v0 control connection: Try to fetch
2110 * commands from conn->inbuf, and execute them.
2113 connection_control_process_inbuf_v0(connection_t
*conn
)
2116 uint16_t command_type
;
2120 /* Try to suck a control message from the buffer. */
2121 switch (fetch_from_buf_control0(conn
->inbuf
, &body_len
, &command_type
, &body
,
2122 conn
->state
== CONTROL_CONN_STATE_NEEDAUTH_V0
))
2126 log_fn(LOG_INFO
, "Detected v1 control protocol on connection (fd %d)",
2128 conn
->state
= CONTROL_CONN_STATE_NEEDAUTH_V1
;
2129 return connection_control_process_inbuf_v1(conn
);
2132 log_fn(LOG_WARN
, "Error in control command. Failing.");
2135 /* Control command not all here yet. Wait. */
2138 /* We got a command. Process it. */
2144 /* We got a command. If we need authentication, only authentication
2145 * commands will be considered. */
2146 if (conn
->state
== CONTROL_CONN_STATE_NEEDAUTH_V0
&&
2147 command_type
!= CONTROL0_CMD_AUTHENTICATE
) {
2148 log_fn(LOG_WARN
, "Rejecting '%s' command; authentication needed.",
2149 control_cmd_to_string(command_type
));
2150 send_control0_error(conn
, ERR_UNAUTHORIZED
, "Authentication required");
2155 if (command_type
== CONTROL0_CMD_FRAGMENTHEADER
||
2156 command_type
== CONTROL0_CMD_FRAGMENT
) {
2157 if (handle_control_fragments(conn
, command_type
, body_len
, body
))
2160 if (conn
->incoming_cmd_cur_len
!= conn
->incoming_cmd_len
)
2163 command_type
= conn
->incoming_cmd_type
;
2164 body_len
= conn
->incoming_cmd_len
;
2165 body
= conn
->incoming_cmd
;
2166 conn
->incoming_cmd
= NULL
;
2167 } else if (conn
->incoming_cmd
) {
2168 log_fn(LOG_WARN
, "Dropping incomplete fragmented command");
2169 tor_free(conn
->incoming_cmd
);
2172 /* Okay, we're willing to process the command. */
2173 switch (command_type
)
2175 case CONTROL0_CMD_SETCONF
:
2176 if (handle_control_setconf(conn
, body_len
, body
))
2179 case CONTROL0_CMD_GETCONF
:
2180 if (handle_control_getconf(conn
, body_len
, body
))
2183 case CONTROL0_CMD_SETEVENTS
:
2184 if (handle_control_setevents(conn
, body_len
, body
))
2187 case CONTROL0_CMD_AUTHENTICATE
:
2188 if (handle_control_authenticate(conn
, body_len
, body
))
2191 case CONTROL0_CMD_SAVECONF
:
2192 if (handle_control_saveconf(conn
, body_len
, body
))
2195 case CONTROL0_CMD_SIGNAL
:
2196 if (handle_control_signal(conn
, body_len
, body
))
2199 case CONTROL0_CMD_MAPADDRESS
:
2200 if (handle_control_mapaddress(conn
, body_len
, body
))
2203 case CONTROL0_CMD_GETINFO
:
2204 if (handle_control_getinfo(conn
, body_len
, body
))
2207 case CONTROL0_CMD_EXTENDCIRCUIT
:
2208 if (handle_control_extendcircuit(conn
, body_len
, body
))
2211 case CONTROL0_CMD_ATTACHSTREAM
:
2212 if (handle_control_attachstream(conn
, body_len
, body
))
2215 case CONTROL0_CMD_POSTDESCRIPTOR
:
2216 if (handle_control_postdescriptor(conn
, body_len
, body
))
2219 case CONTROL0_CMD_REDIRECTSTREAM
:
2220 if (handle_control_redirectstream(conn
, body_len
, body
))
2223 case CONTROL0_CMD_CLOSESTREAM
:
2224 if (handle_control_closestream(conn
, body_len
, body
))
2227 case CONTROL0_CMD_CLOSECIRCUIT
:
2228 if (handle_control_closecircuit(conn
, body_len
, body
))
2231 case CONTROL0_CMD_ERROR
:
2232 case CONTROL0_CMD_DONE
:
2233 case CONTROL0_CMD_CONFVALUE
:
2234 case CONTROL0_CMD_EVENT
:
2235 case CONTROL0_CMD_INFOVALUE
:
2236 log_fn(LOG_WARN
, "Received client-only '%s' command; ignoring.",
2237 control_cmd_to_string(command_type
));
2238 send_control0_error(conn
, ERR_UNRECOGNIZED_TYPE
,
2239 "Command type only valid from server to tor client");
2241 case CONTROL0_CMD_FRAGMENTHEADER
:
2242 case CONTROL0_CMD_FRAGMENT
:
2243 log_fn(LOG_WARN
, "Recieved command fragment out of order; ignoring.");
2244 send_control0_error(conn
, ERR_SYNTAX
, "Bad fragmentation on command.");
2246 log_fn(LOG_WARN
, "Received unrecognized command type %d; ignoring.",
2248 send_control0_error(conn
, ERR_UNRECOGNIZED_TYPE
,
2249 "Unrecognized command type");
2253 goto again
; /* There might be more data. */
2256 /** Called when <b>conn</b> has received more bytes on its inbuf.
2259 connection_control_process_inbuf(connection_t
*conn
)
2262 tor_assert(conn
->type
== CONN_TYPE_CONTROL
);
2264 if (STATE_IS_V0(conn
->state
))
2265 return connection_control_process_inbuf_v0(conn
);
2267 return connection_control_process_inbuf_v1(conn
);
2270 /** Something has happened to circuit <b>circ</b>: tell any interested
2271 * control connections. */
2273 control_event_circuit_status(circuit_t
*circ
, circuit_status_event_t tp
)
2276 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS
))
2279 tor_assert(CIRCUIT_IS_ORIGIN(circ
));
2281 path
= circuit_list_path(circ
,0);
2282 if (EVENT_IS_INTERESTING0(EVENT_CIRCUIT_STATUS
)) {
2283 size_t path_len
= strlen(path
);
2284 msg
= tor_malloc(1+4+path_len
+1); /* event, circid, path, NUL. */
2285 msg
[0] = (uint8_t) tp
;
2286 set_uint32(msg
+1, htonl(circ
->global_identifier
));
2287 strlcpy(msg
+5,path
,path_len
+1);
2289 send_control0_event(EVENT_CIRCUIT_STATUS
, (uint32_t)(path_len
+6), msg
);
2292 if (EVENT_IS_INTERESTING1(EVENT_CIRCUIT_STATUS
)) {
2296 case CIRC_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
2297 case CIRC_EVENT_BUILT
: status
= "BUILT"; break;
2298 case CIRC_EVENT_EXTENDED
: status
= "EXTENDED"; break;
2299 case CIRC_EVENT_FAILED
: status
= "FAILED"; break;
2300 case CIRC_EVENT_CLOSED
: status
= "CLOSED"; break;
2302 log_fn(LOG_WARN
, "Unrecognized status code %d", (int)tp
);
2305 send_control1_event(EVENT_CIRCUIT_STATUS
,
2306 "650 CIRC %lu %s %s\r\n",
2307 (unsigned long)circ
->global_identifier
,
2315 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
2316 * <b>buf</b>, determine the address:port combination requested on
2317 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
2320 write_stream_target_to_buf(connection_t
*conn
, char *buf
, size_t len
)
2323 if (conn
->chosen_exit_name
)
2324 if (tor_snprintf(buf2
, sizeof(buf2
), ".%s.exit", conn
->chosen_exit_name
)<0)
2326 if (tor_snprintf(buf
, len
, "%s%s:%d",
2327 conn
->socks_request
->address
,
2328 conn
->chosen_exit_name
? buf2
: "",
2329 conn
->socks_request
->port
)<0)
2334 /** Something has happened to the stream associated with AP connection
2335 * <b>conn</b>: tell any interested control connections. */
2337 control_event_stream_status(connection_t
*conn
, stream_status_event_t tp
)
2342 tor_assert(conn
->type
== CONN_TYPE_AP
);
2343 tor_assert(conn
->socks_request
);
2345 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS
))
2348 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
2349 if (EVENT_IS_INTERESTING0(EVENT_STREAM_STATUS
)) {
2351 msg
= tor_malloc(5+len
+1);
2352 msg
[0] = (uint8_t) tp
;
2353 set_uint32(msg
+1, htonl(conn
->global_identifier
));
2354 strlcpy(msg
+5, buf
, len
+1);
2356 send_control0_event(EVENT_STREAM_STATUS
, (uint32_t)(5+len
+1), msg
);
2359 if (EVENT_IS_INTERESTING1(EVENT_STREAM_STATUS
)) {
2364 case STREAM_EVENT_SENT_CONNECT
: status
= "SENTCONNECT"; break;
2365 case STREAM_EVENT_SENT_RESOLVE
: status
= "SENTRESOLVE"; break;
2366 case STREAM_EVENT_SUCCEEDED
: status
= "SUCCEEDED"; break;
2367 case STREAM_EVENT_FAILED
: status
= "FAILED"; break;
2368 case STREAM_EVENT_CLOSED
: status
= "CLOSED"; break;
2369 case STREAM_EVENT_NEW
: status
= "NEW"; break;
2370 case STREAM_EVENT_NEW_RESOLVE
: status
= "NEWRESOLVE"; break;
2371 case STREAM_EVENT_FAILED_RETRIABLE
: status
= "DETACHED"; break;
2373 log_fn(LOG_WARN
, "Unrecognized status code %d", (int)tp
);
2376 circ
= circuit_get_by_edge_conn(conn
);
2377 send_control1_event(EVENT_STREAM_STATUS
,
2378 "650 STREAM %lu %s %lu %s\r\n",
2379 (unsigned long)conn
->global_identifier
, status
,
2380 circ
?(unsigned long)circ
->global_identifier
: 0ul,
2382 /* XXX need to specify its intended exit, etc? */
2387 /** Something has happened to the OR connection <b>conn</b>: tell any
2388 * interested control connections. */
2390 control_event_or_conn_status(connection_t
*conn
,or_conn_status_event_t tp
)
2392 char buf
[HEX_DIGEST_LEN
+3]; /* status, dollar, identity, NUL */
2395 tor_assert(conn
->type
== CONN_TYPE_OR
);
2397 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS
))
2400 if (EVENT_IS_INTERESTING0(EVENT_OR_CONN_STATUS
)) {
2401 buf
[0] = (uint8_t)tp
;
2402 strlcpy(buf
+1,conn
->nickname
,sizeof(buf
)-1);
2403 len
= strlen(buf
+1);
2404 send_control0_event(EVENT_OR_CONN_STATUS
, (uint32_t)(len
+1), buf
);
2406 if (EVENT_IS_INTERESTING1(EVENT_OR_CONN_STATUS
)) {
2410 case OR_CONN_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
2411 case OR_CONN_EVENT_CONNECTED
: status
= "CONNECTED"; break;
2412 case OR_CONN_EVENT_FAILED
: status
= "FAILED"; break;
2413 case OR_CONN_EVENT_CLOSED
: status
= "CLOSED"; break;
2415 log_fn(LOG_WARN
, "Unrecognized status code %d", (int)tp
);
2418 send_control1_event(EVENT_OR_CONN_STATUS
,
2419 "650 ORCONN %s %s\r\n",
2420 conn
->nickname
, status
);
2425 /** A second or more has elapsed: tell any interested control
2426 * connections how much bandwidth we used. */
2428 control_event_bandwidth_used(uint32_t n_read
, uint32_t n_written
)
2432 if (EVENT_IS_INTERESTING0(EVENT_BANDWIDTH_USED
)) {
2433 set_uint32(buf
, htonl(n_read
));
2434 set_uint32(buf
+4, htonl(n_written
));
2435 send_control0_event(EVENT_BANDWIDTH_USED
, 8, buf
);
2437 if (EVENT_IS_INTERESTING1(EVENT_BANDWIDTH_USED
)) {
2438 send_control1_event(EVENT_BANDWIDTH_USED
,
2439 "650 BW %lu %lu\r\n",
2440 (unsigned long)n_read
,
2441 (unsigned long)n_written
);
2447 /** Called when we are sending a log message to the controllers: suspend
2448 * sending further log messages to the controllers until we're done. Used by
2449 * CONN_LOG_PROTECT. */
2451 disable_control_logging(void)
2453 ++disable_log_messages
;
2456 /** We're done sending a log message to the controllers: re-enable controller
2457 * logging. Used by CONN_LOG_PROTECT. */
2459 enable_control_logging(void)
2461 if (--disable_log_messages
< 0)
2465 /** We got a log message: tell any interested control connections. */
2467 control_event_logmsg(int severity
, const char *msg
)
2471 if (disable_log_messages
)
2474 oldlog
= EVENT_IS_INTERESTING0(EVENT_LOG_OBSOLETE
) &&
2475 (severity
== LOG_NOTICE
|| severity
== LOG_WARN
|| severity
== LOG_ERR
);
2476 event
= log_severity_to_event(severity
);
2478 if (event
<0 || !EVENT_IS_INTERESTING0(event
))
2481 if (oldlog
|| event
) {
2482 size_t len
= strlen(msg
);
2483 ++disable_log_messages
;
2485 send_control0_event(event
, (uint32_t)(len
+1), msg
);
2487 send_control0_event(EVENT_LOG_OBSOLETE
, (uint32_t)(len
+1), msg
);
2488 --disable_log_messages
;
2491 event
= log_severity_to_event(severity
);
2492 if (event
>= 0 && EVENT_IS_INTERESTING1(event
)) {
2495 if (strchr(msg
, '\n')) {
2497 b
= tor_strdup(msg
);
2498 for (cp
= b
; *cp
; ++cp
)
2499 if (*cp
== '\r' || *cp
== '\n')
2503 case LOG_DEBUG
: s
= "DEBUG"; break;
2504 case LOG_INFO
: s
= "INFO"; break;
2505 case LOG_NOTICE
: s
= "NOTICE"; break;
2506 case LOG_WARN
: s
= "WARN"; break;
2507 case LOG_ERR
: s
= "ERR"; break;
2508 default: s
= "UnknownLogSeverity"; break;
2510 ++disable_log_messages
;
2511 send_control1_event(event
, "650 %s %s\r\n", s
, b
?b
:msg
);
2512 --disable_log_messages
;
2517 /** Called whenever we receive new router descriptors: tell any
2518 * interested control connections. <b>routers</b> is a list of
2519 * DIGEST_LEN-byte identity digests.
2522 control_event_descriptors_changed(smartlist_t
*routers
)
2526 smartlist_t
*identities
;
2527 char buf
[HEX_DIGEST_LEN
+1];
2529 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC
))
2531 identities
= smartlist_create();
2532 SMARTLIST_FOREACH(routers
, routerinfo_t
*, r
,
2534 base16_encode(buf
,sizeof(buf
),r
->identity_digest
,DIGEST_LEN
);
2535 smartlist_add(identities
, tor_strdup(buf
));
2537 if (EVENT_IS_INTERESTING0(EVENT_NEW_DESC
)) {
2538 msg
= smartlist_join_strings(identities
, ",", 0, &len
);
2539 send_control0_event(EVENT_NEW_DESC
, len
+1, msg
);
2542 if (EVENT_IS_INTERESTING1(EVENT_NEW_DESC
)) {
2543 msg
= smartlist_join_strings(identities
, " ", 0, &len
);
2544 send_control1_event(EVENT_NEW_DESC
, "650 NEWDESC %s\r\n", msg
);
2547 SMARTLIST_FOREACH(identities
, char *, cp
, tor_free(cp
));
2548 smartlist_free(identities
);
2553 /** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
2554 * <b>expires</b> values less than 3 are special; see connection_edge.c. */
2556 control_event_address_mapped(const char *from
, const char *to
, time_t expires
)
2558 if (!EVENT_IS_INTERESTING1(EVENT_ADDRMAP
))
2562 send_control1_event(EVENT_ADDRMAP
, "650 ADDRMAP %s %s NEVER\r\n", from
, to
);
2564 char buf
[ISO_TIME_LEN
+1];
2565 format_local_iso_time(buf
,expires
);
2566 send_control1_event(EVENT_ADDRMAP
, "650 ADDRMAP %s %s \"%s\"\r\n",
2573 /** Choose a random authentication cookie and write it to disk.
2574 * Anybody who can read the cookie from disk will be considered
2575 * authorized to use the control connection. */
2577 init_cookie_authentication(int enabled
)
2582 authentication_cookie_is_set
= 0;
2586 tor_snprintf(fname
, sizeof(fname
), "%s/control_auth_cookie",
2587 get_options()->DataDirectory
);
2588 crypto_rand(authentication_cookie
, AUTHENTICATION_COOKIE_LEN
);
2589 authentication_cookie_is_set
= 1;
2590 if (write_bytes_to_file(fname
, authentication_cookie
,
2591 AUTHENTICATION_COOKIE_LEN
, 1)) {
2592 log_fn(LOG_WARN
,"Error writing authentication cookie.");