1 /* Copyright 2004-2007 Roger Dingledine, Nick Mathewson. */
2 /* See LICENSE for licensing information */
4 const char control_c_id
[] =
9 * \brief Implementation for Tor's control-socket interface.
14 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
15 * finished authentication and is accepting commands. */
16 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN_V0 || \
17 (s) == CONTROL_CONN_STATE_OPEN_V1)
18 /** Yield true iff <b>s</b> is the state of a control_connection_t that is
19 * speaking the V0 protocol.
21 #define STATE_IS_V0(s) ((s) == CONTROL_CONN_STATE_NEEDAUTH_V0 || \
22 (s) == CONTROL_CONN_STATE_OPEN_V0)
25 * See control-spec.txt and control-spec-v0.txt for full details on
29 /* Recognized version 0 message type codes; do not add new codes to this list.
30 * Version 0 is dead; version 1 doesn't use codes. */
31 #define CONTROL0_CMD_ERROR 0x0000
32 #define CONTROL0_CMD_DONE 0x0001
33 #define CONTROL0_CMD_SETCONF 0x0002
34 #define CONTROL0_CMD_GETCONF 0x0003
35 #define CONTROL0_CMD_CONFVALUE 0x0004
36 #define CONTROL0_CMD_SETEVENTS 0x0005
37 #define CONTROL0_CMD_EVENT 0x0006
38 #define CONTROL0_CMD_AUTHENTICATE 0x0007
39 #define CONTROL0_CMD_SAVECONF 0x0008
40 #define CONTROL0_CMD_SIGNAL 0x0009
41 #define CONTROL0_CMD_MAPADDRESS 0x000A
42 #define CONTROL0_CMD_GETINFO 0x000B
43 #define CONTROL0_CMD_INFOVALUE 0x000C
44 #define CONTROL0_CMD_EXTENDCIRCUIT 0x000D
45 #define CONTROL0_CMD_ATTACHSTREAM 0x000E
46 #define CONTROL0_CMD_POSTDESCRIPTOR 0x000F
47 #define CONTROL0_CMD_FRAGMENTHEADER 0x0010
48 #define CONTROL0_CMD_FRAGMENT 0x0011
49 #define CONTROL0_CMD_REDIRECTSTREAM 0x0012
50 #define CONTROL0_CMD_CLOSESTREAM 0x0013
51 #define CONTROL0_CMD_CLOSECIRCUIT 0x0014
52 #define _CONTROL0_CMD_MAX_RECOGNIZED 0x0014
54 /* Recognized version 0 error codes. Do not expand. */
55 #define ERR_UNSPECIFIED 0x0000
56 #define ERR_INTERNAL 0x0001
57 #define ERR_UNRECOGNIZED_TYPE 0x0002
58 #define ERR_SYNTAX 0x0003
59 #define ERR_UNRECOGNIZED_CONFIG_KEY 0x0004
60 #define ERR_INVALID_CONFIG_VALUE 0x0005
61 #define ERR_UNRECOGNIZED_EVENT_CODE 0x0006
62 #define ERR_UNAUTHORIZED 0x0007
63 #define ERR_REJECTED_AUTHENTICATION 0x0008
64 #define ERR_RESOURCE_EXHAUSTED 0x0009
65 #define ERR_NO_STREAM 0x000A
66 #define ERR_NO_CIRC 0x000B
67 #define ERR_NO_ROUTER 0x000C
69 /* Recognized asynchronous event types. It's okay to expand this list
70 * because it is used both as a list of v0 event types, and as indices
71 * into the bitfield to determine which controllers want which events.
73 #define _EVENT_MIN 0x0001
74 #define EVENT_CIRCUIT_STATUS 0x0001
75 #define EVENT_STREAM_STATUS 0x0002
76 #define EVENT_OR_CONN_STATUS 0x0003
77 #define EVENT_BANDWIDTH_USED 0x0004
78 #define EVENT_LOG_OBSOLETE 0x0005
79 #define EVENT_NEW_DESC 0x0006
80 #define EVENT_DEBUG_MSG 0x0007
81 #define EVENT_INFO_MSG 0x0008
82 #define EVENT_NOTICE_MSG 0x0009
83 #define EVENT_WARN_MSG 0x000A
84 #define EVENT_ERR_MSG 0x000B
85 #define LAST_V0_EVENT 0x000B
86 #define EVENT_ADDRMAP 0x000C
87 #define EVENT_AUTHDIR_NEWDESCS 0x000D
88 #define EVENT_DESCCHANGED 0x000E
89 #define EVENT_NS 0x000F
90 #define EVENT_STATUS_CLIENT 0x0010
91 #define EVENT_STATUS_SERVER 0x0011
92 #define EVENT_STATUS_GENERAL 0x0012
93 #define EVENT_GUARD 0x0013
94 #define EVENT_STREAM_BANDWIDTH_USED 0x0014
95 #define _EVENT_MAX 0x0014
96 /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
98 /** Array mapping from message type codes to human-readable message
99 * type names. Used for compatibility with version 0 of the control
100 * protocol. Do not add new items to this list. */
101 static const char * CONTROL0_COMMANDS
[_CONTROL0_CMD_MAX_RECOGNIZED
+1] = {
125 /** Bitfield: The bit 1<<e is set if <b>any</b> open control
126 * connection is interested in events of type <b>e</b>. We use this
127 * so that we can decide to skip generating event messages that nobody
128 * has interest in without having to walk over the global connection
131 typedef uint32_t event_mask_t
;
132 static event_mask_t global_event_mask0
= 0;
133 static event_mask_t global_event_mask1long
= 0;
134 static event_mask_t global_event_mask1short
= 0;
136 /** True iff we have disabled log messages from being sent to the controller */
137 static int disable_log_messages
= 0;
139 /** Macro: true if any control connection is interested in events of type
141 #define EVENT_IS_INTERESTING0(e) (global_event_mask0 & (1<<(e)))
142 #define EVENT_IS_INTERESTING1(e) \
143 ((global_event_mask1long|global_event_mask1short) & (1<<(e)))
144 #define EVENT_IS_INTERESTING1L(e) (global_event_mask1long & (1<<(e)))
145 #define EVENT_IS_INTERESTING1S(e) (global_event_mask1short & (1<<(e)))
146 #define EVENT_IS_INTERESTING(e) \
147 ((global_event_mask0|global_event_mask1short|global_event_mask1long) \
150 /** If we're using cookie-type authentication, how long should our cookies be?
152 #define AUTHENTICATION_COOKIE_LEN 32
154 /** If true, we've set authentication_cookie to a secret code and
155 * stored it to disk. */
156 static int authentication_cookie_is_set
= 0;
157 static char authentication_cookie
[AUTHENTICATION_COOKIE_LEN
];
159 #define SHORT_NAMES 1
161 #define ALL_NAMES (SHORT_NAMES|LONG_NAMES)
162 #define EXTENDED_FORMAT 4
163 #define NONEXTENDED_FORMAT 8
164 #define ALL_FORMATS (EXTENDED_FORMAT|NONEXTENDED_FORMAT)
165 typedef int event_format_t
;
167 static void connection_printf_to_buf(control_connection_t
*conn
,
168 const char *format
, ...)
170 /*static*/ size_t write_escaped_data(const char *data
, size_t len
,
171 int translate_newlines
, char **out
);
172 /*static*/ size_t read_escaped_data(const char *data
, size_t len
,
173 int translate_newlines
, char **out
);
174 static void send_control0_message(control_connection_t
*conn
, uint16_t type
,
175 uint32_t len
, const char *body
);
176 static void send_control_done(control_connection_t
*conn
);
177 static void send_control_done2(control_connection_t
*conn
, const char *msg
,
179 static void send_control0_error(control_connection_t
*conn
, uint16_t error
,
180 const char *message
);
181 static void send_control0_event(uint16_t event
, uint32_t len
,
183 static void send_control1_event(uint16_t event
, event_format_t which
,
184 const char *format
, ...)
186 static void send_control1_event_extended(uint16_t event
, event_format_t which
,
187 const char *format
, ...)
189 static int handle_control_setconf(control_connection_t
*conn
, uint32_t len
,
191 static int handle_control_resetconf(control_connection_t
*conn
, uint32_t len
,
193 static int handle_control_getconf(control_connection_t
*conn
, uint32_t len
,
195 static int handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
197 static int handle_control_authenticate(control_connection_t
*conn
,
200 static int handle_control_saveconf(control_connection_t
*conn
, uint32_t len
,
202 static int handle_control_signal(control_connection_t
*conn
, uint32_t len
,
204 static int handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
206 static char *list_getinfo_options(void);
207 static int handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
209 static int handle_control_extendcircuit(control_connection_t
*conn
,
212 static int handle_control_setpurpose(control_connection_t
*conn
,
214 uint32_t len
, const char *body
);
215 static int handle_control_attachstream(control_connection_t
*conn
,
218 static int handle_control_postdescriptor(control_connection_t
*conn
,
221 static int handle_control_redirectstream(control_connection_t
*conn
,
224 static int handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
226 static int handle_control_closecircuit(control_connection_t
*conn
,
229 static int handle_control_usefeature(control_connection_t
*conn
,
232 static int write_stream_target_to_buf(edge_connection_t
*conn
, char *buf
,
234 static void orconn_target_get_name(int long_names
, char *buf
, size_t len
,
235 or_connection_t
*conn
);
237 /** Given a possibly invalid message type code <b>cmd</b>, return a
238 * human-readable string equivalent. */
239 static INLINE
const char *
240 control_cmd_to_string(uint16_t cmd
)
242 return (cmd
<=_CONTROL0_CMD_MAX_RECOGNIZED
) ?
243 CONTROL0_COMMANDS
[cmd
] : "Unknown";
246 /** Given a control event code for a message event, return the corresponding
249 event_to_log_severity(int event
)
252 case EVENT_DEBUG_MSG
: return LOG_DEBUG
;
253 case EVENT_INFO_MSG
: return LOG_INFO
;
254 case EVENT_NOTICE_MSG
: return LOG_NOTICE
;
255 case EVENT_WARN_MSG
: return LOG_WARN
;
256 case EVENT_ERR_MSG
: return LOG_ERR
;
261 /** Given a log severity, return the corresponding control event code. */
263 log_severity_to_event(int severity
)
266 case LOG_DEBUG
: return EVENT_DEBUG_MSG
;
267 case LOG_INFO
: return EVENT_INFO_MSG
;
268 case LOG_NOTICE
: return EVENT_NOTICE_MSG
;
269 case LOG_WARN
: return EVENT_WARN_MSG
;
270 case LOG_ERR
: return EVENT_ERR_MSG
;
275 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
276 * connection's event_mask field. */
278 control_update_global_event_mask(void)
280 connection_t
**conns
;
282 event_mask_t old_mask
, new_mask
;
283 old_mask
= global_event_mask0
;
284 old_mask
|= global_event_mask1short
;
285 old_mask
|= global_event_mask1long
;
287 global_event_mask0
= 0;
288 global_event_mask1short
= 0;
289 global_event_mask1long
= 0;
290 get_connection_array(&conns
, &n_conns
);
291 for (i
= 0; i
< n_conns
; ++i
) {
292 if (conns
[i
]->type
== CONN_TYPE_CONTROL
&&
293 STATE_IS_OPEN(conns
[i
]->state
)) {
294 control_connection_t
*conn
= TO_CONTROL_CONN(conns
[i
]);
295 if (STATE_IS_V0(conn
->_base
.state
))
296 global_event_mask0
|= conn
->event_mask
;
297 else if (conn
->use_long_names
)
298 global_event_mask1long
|= conn
->event_mask
;
300 global_event_mask1short
|= conn
->event_mask
;
304 new_mask
= global_event_mask0
;
305 new_mask
|= global_event_mask1short
;
306 new_mask
|= global_event_mask1long
;
308 /* Handle the aftermath. Set up the log callback to tell us only what
309 * we want to hear...*/
310 control_adjust_event_log_severity();
312 /* ...then, if we've started logging stream bw, clear the appropriate
314 if (! (old_mask
& EVENT_STREAM_BANDWIDTH_USED
) &&
315 (new_mask
& EVENT_STREAM_BANDWIDTH_USED
)) {
316 for (i
= 0; i
< n_conns
; ++i
) {
317 if (conns
[i
]->type
== CONN_TYPE_AP
) {
318 edge_connection_t
*conn
= TO_EDGE_CONN(conns
[i
]);
319 conn
->n_written
= conn
->n_read
= 0;
325 /** Adjust the log severities that result in control_event_logmsg being called
326 * to match the severity of log messages that any controllers are interested
329 control_adjust_event_log_severity(void)
332 int min_log_event
=EVENT_ERR_MSG
, max_log_event
=EVENT_DEBUG_MSG
;
334 for (i
= EVENT_DEBUG_MSG
; i
<= EVENT_ERR_MSG
; ++i
) {
335 if (EVENT_IS_INTERESTING(i
)) {
340 for (i
= EVENT_ERR_MSG
; i
>= EVENT_DEBUG_MSG
; --i
) {
341 if (EVENT_IS_INTERESTING(i
)) {
346 if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE
) ||
347 EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
)) {
348 if (min_log_event
> EVENT_NOTICE_MSG
)
349 min_log_event
= EVENT_NOTICE_MSG
;
350 if (max_log_event
< EVENT_ERR_MSG
)
351 max_log_event
= EVENT_ERR_MSG
;
353 change_callback_log_severity(event_to_log_severity(min_log_event
),
354 event_to_log_severity(max_log_event
),
355 control_event_logmsg
);
358 /** Append a NUL-terminated string <b>s</b> to the end of
359 * <b>conn</b>-\>outbuf
362 connection_write_str_to_buf(const char *s
, control_connection_t
*conn
)
364 size_t len
= strlen(s
);
365 connection_write_to_buf(s
, len
, TO_CONN(conn
));
368 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
369 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
370 * the contents of <b>data</b> into *<b>out</b>, adding a period
371 * before any period that that appears at the start of a line, and
372 * adding a period-CRLF line at the end. If <b>translate_newlines</b>
373 * is true, replace all LF characters sequences with CRLF. Return the
374 * number of bytes in *<b>out</b>.
377 write_escaped_data(const char *data
, size_t len
, int translate_newlines
,
380 size_t sz_out
= len
+8;
385 for (i
=0; i
<(int)len
; ++i
) {
387 sz_out
+= 2; /* Maybe add a CR; maybe add a dot. */
389 *out
= outp
= tor_malloc(sz_out
+1);
394 if (translate_newlines
)
397 } else if (*data
== '.') {
407 if (outp
< *out
+2 || memcmp(outp
-2, "\r\n", 2)) {
414 *outp
= '\0'; /* NUL-terminate just in case. */
415 tor_assert((outp
- *out
) <= (int)sz_out
);
419 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
420 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
421 * the contents of <b>data</b> into *<b>out</b>, removing any period
422 * that appears at the start of a line. If <b>translate_newlines</b>
423 * is true, replace all CRLF sequences with LF. Return the number of
424 * bytes in *<b>out</b>. */
426 read_escaped_data(const char *data
, size_t len
, int translate_newlines
,
433 *out
= outp
= tor_malloc(len
+1);
440 if (translate_newlines
)
441 next
= tor_memmem(data
, end
-data
, "\r\n", 2);
443 next
= tor_memmem(data
, end
-data
, "\r\n.", 3);
445 memcpy(outp
, data
, next
-data
);
449 memcpy(outp
, data
, end
-data
);
454 if (translate_newlines
) {
466 /** Given a pointer to a string starting at <b>start</b> containing
467 * <b>in_len_max</b> characters, decode a string beginning with a single
468 * quote, containing any number of non-quote characters or characters escaped
469 * with a backslash, and ending with a final quote. Place the resulting
470 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
471 * store its length in <b>out_len</b>. On success, return a pointer to the
472 * character immediately following the escaped string. On failure, return
475 get_escaped_string(const char *start
, size_t in_len_max
,
476 char **out
, size_t *out_len
)
478 const char *cp
, *end
;
486 end
= start
+in_len_max
;
488 /* Calculate length. */
492 else if (*cp
== '\\') {
494 return NULL
; /* Can't escape EOS. */
497 } else if (*cp
== '\"') {
505 outp
= *out
= tor_malloc(len
+1);
515 tor_assert((outp
- *out
) == (int)*out_len
);
520 /** Acts like sprintf, but writes its formatted string to the end of
521 * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
522 * but it will always end with a CRLF sequence.
524 * Currently the length of the message is limited to 1024 (including the
527 connection_printf_to_buf(control_connection_t
*conn
, const char *format
, ...)
529 #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
531 char buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
];
535 r
= tor_vsnprintf(buf
, sizeof(buf
), format
, ap
);
538 log_warn(LD_BUG
, "Unable to format string for controller.");
542 if (memcmp("\r\n\0", buf
+len
-2, 3)) {
543 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-1] = '\0';
544 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-2] = '\n';
545 buf
[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE
-3] = '\r';
547 connection_write_to_buf(buf
, len
, TO_CONN(conn
));
550 /** Send a message of type <b>type</b> containing <b>len</b> bytes
551 * from <b>body</b> along the control connection <b>conn</b> */
553 send_control0_message(control_connection_t
*conn
, uint16_t type
, uint32_t len
,
558 tor_assert(STATE_IS_V0(conn
->_base
.state
));
559 tor_assert(len
|| !body
);
560 tor_assert(type
<= _CONTROL0_CMD_MAX_RECOGNIZED
);
562 set_uint16(buf
, htons(len
));
563 set_uint16(buf
+2, htons(type
));
564 connection_write_to_buf(buf
, 4, TO_CONN(conn
));
566 connection_write_to_buf(body
, len
, TO_CONN(conn
));
568 set_uint16(buf
, htons(65535));
569 set_uint16(buf
+2, htons(CONTROL0_CMD_FRAGMENTHEADER
));
570 set_uint16(buf
+4, htons(type
));
571 set_uint32(buf
+6, htonl(len
));
572 connection_write_to_buf(buf
, 10, TO_CONN(conn
));
573 connection_write_to_buf(body
, 65535-6, TO_CONN(conn
));
577 size_t chunklen
= (len
<65535)?len
:65535;
578 set_uint16(buf
, htons((uint16_t)chunklen
));
579 set_uint16(buf
+2, htons(CONTROL0_CMD_FRAGMENT
));
580 connection_write_to_buf(buf
, 4, TO_CONN(conn
));
581 connection_write_to_buf(body
, chunklen
, TO_CONN(conn
));
588 /** Send a "DONE" message down the control connection <b>conn</b> */
590 send_control_done(control_connection_t
*conn
)
592 if (STATE_IS_V0(conn
->_base
.state
)) {
593 send_control0_message(conn
, CONTROL0_CMD_DONE
, 0, NULL
);
595 connection_write_str_to_buf("250 OK\r\n", conn
);
599 /** Send a "DONE" message down the v0 control message <b>conn</b>, with body
600 * as provided in the <b>len</b> bytes at <b>msg</b>.
603 send_control_done2(control_connection_t
*conn
, const char *msg
, size_t len
)
607 send_control0_message(conn
, CONTROL0_CMD_DONE
, len
, msg
);
610 /** Send an error message with error code <b>error</b> and body
611 * <b>message</b> down the connection <b>conn</b> */
613 send_control0_error(control_connection_t
*conn
, uint16_t error
,
618 set_uint16(buf
, htons(error
));
619 len
= strlen(message
);
620 tor_assert(len
< (256-2));
621 memcpy(buf
+2, message
, len
);
622 send_control0_message(conn
, CONTROL0_CMD_ERROR
, (uint16_t)(len
+2), buf
);
625 /** Send an 'event' message of event type <b>event</b>, containing
626 * <b>len</b> bytes in <b>body</b> to every control connection that
627 * is interested in it. */
629 send_control0_event(uint16_t event
, uint32_t len
, const char *body
)
631 connection_t
**conns
;
636 tor_assert(event
>= _EVENT_MIN
&& event
<= LAST_V0_EVENT
);
639 buf
= tor_malloc_zero(buflen
);
640 set_uint16(buf
, htons(event
));
641 memcpy(buf
+2, body
, len
);
643 get_connection_array(&conns
, &n_conns
);
644 for (i
= 0; i
< n_conns
; ++i
) {
645 if (conns
[i
]->type
== CONN_TYPE_CONTROL
&&
646 !conns
[i
]->marked_for_close
&&
647 conns
[i
]->state
== CONTROL_CONN_STATE_OPEN_V0
) {
648 control_connection_t
*control_conn
= TO_CONTROL_CONN(conns
[i
]);
649 if (control_conn
->event_mask
& (1<<event
)) {
650 send_control0_message(control_conn
, CONTROL0_CMD_EVENT
, buflen
, buf
);
651 if (event
== EVENT_ERR_MSG
)
652 connection_handle_write(TO_CONN(control_conn
), 1);
660 /* Send an event to all v1 controllers that are listening for code
661 * <b>event</b>. The event's body is given by <b>msg</b>.
663 * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
664 * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
665 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
666 * to contollers that <em>have</em> enabled VERBOSE_NAMES.
668 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
669 * respect to the EXTENDED_EVENTS feature. */
671 send_control1_event_string(uint16_t event
, event_format_t which
,
674 connection_t
**conns
;
677 tor_assert(event
>= _EVENT_MIN
&& event
<= _EVENT_MAX
);
679 get_connection_array(&conns
, &n_conns
);
680 for (i
= 0; i
< n_conns
; ++i
) {
681 if (conns
[i
]->type
== CONN_TYPE_CONTROL
&&
682 !conns
[i
]->marked_for_close
&&
683 conns
[i
]->state
== CONTROL_CONN_STATE_OPEN_V1
) {
684 control_connection_t
*control_conn
= TO_CONTROL_CONN(conns
[i
]);
685 if (control_conn
->use_long_names
) {
686 if (!(which
& LONG_NAMES
))
689 if (!(which
& SHORT_NAMES
))
692 if (control_conn
->use_extended_events
) {
693 if (!(which
& EXTENDED_FORMAT
))
696 if (!(which
& NONEXTENDED_FORMAT
))
699 if (control_conn
->event_mask
& (1<<event
)) {
701 connection_write_to_buf(msg
, strlen(msg
), TO_CONN(control_conn
));
702 if (event
== EVENT_ERR_MSG
)
704 else if (event
== EVENT_STATUS_GENERAL
)
705 is_err
= !strcmpstart(msg
, "STATUS_GENERAL ERR ");
706 else if (event
== EVENT_STATUS_CLIENT
)
707 is_err
= !strcmpstart(msg
, "STATUS_CLIENT ERR ");
708 else if (event
== EVENT_STATUS_SERVER
)
709 is_err
= !strcmpstart(msg
, "STATUS_SERVER ERR ");
711 connection_handle_write(TO_CONN(control_conn
), 1);
717 /** Helper for send_control1_event and send_control1_event_extended:
718 * Send an event to all v1 controllers that are listening for code
719 * <b>event</b>. The event's body is created by the printf-style format in
720 * <b>format</b>, and other arguments as provided.
722 * If <b>extended</b> is true, and the format contains a single '@' character,
723 * it will be replaced with a space and all text after that character will be
724 * sent only to controllers that have enabled extended events.
726 * Currently the length of the message is limited to 1024 (including the
729 send_control1_event_impl(uint16_t event
, event_format_t which
, int extended
,
730 const char *format
, va_list ap
)
732 /* This is just a little longer than the longest allowed log message */
733 #define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
735 char buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
];
739 r
= tor_vsnprintf(buf
, sizeof(buf
), format
, ap
);
741 log_warn(LD_BUG
, "Unable to format event for controller.");
746 if (memcmp("\r\n\0", buf
+len
-2, 3)) {
747 /* if it is not properly terminated, do it now */
748 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-1] = '\0';
749 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-2] = '\n';
750 buf
[SEND_CONTROL1_EVENT_BUFFERSIZE
-3] = '\r';
753 if (extended
&& (cp
= strchr(buf
, '@'))) {
754 which
&= ~ALL_FORMATS
;
756 send_control1_event_string(event
, which
|EXTENDED_FORMAT
, buf
);
757 memcpy(cp
, "\r\n\0", 3);
758 send_control1_event_string(event
, which
|NONEXTENDED_FORMAT
, buf
);
760 send_control1_event_string(event
, which
|ALL_FORMATS
, buf
);
764 /* Send an event to all v1 controllers that are listening for code
765 * <b>event</b>. The event's body is created by the printf-style format in
766 * <b>format</b>, and other arguments as provided.
768 * Currently the length of the message is limited to 1024 (including the
771 send_control1_event(uint16_t event
, event_format_t which
,
772 const char *format
, ...)
775 va_start(ap
, format
);
776 send_control1_event_impl(event
, which
, 0, format
, ap
);
780 /* Send an event to all v1 controllers that are listening for code
781 * <b>event</b>. The event's body is created by the printf-style format in
782 * <b>format</b>, and other arguments as provided.
784 * If the format contains a single '@' character, it will be replaced with a
785 * space and all text after that character will be sent only to controllers
786 * that have enabled extended events.
788 * Currently the length of the message is limited to 1024 (including the
791 send_control1_event_extended(uint16_t event
, event_format_t which
,
792 const char *format
, ...)
795 va_start(ap
, format
);
796 send_control1_event_impl(event
, which
, 1, format
, ap
);
800 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
801 static origin_circuit_t
*
802 get_circ(const char *id
)
806 n_id
= tor_parse_ulong(id
, 10, 0, ULONG_MAX
, &ok
, NULL
);
809 return circuit_get_by_global_id(n_id
);
812 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
813 static edge_connection_t
*
814 get_stream(const char *id
)
818 edge_connection_t
*conn
;
819 n_id
= tor_parse_ulong(id
, 10, 0, ULONG_MAX
, &ok
, NULL
);
822 conn
= connection_get_by_global_id(n_id
);
823 if (!conn
|| conn
->_base
.type
!= CONN_TYPE_AP
)
828 /** Helper for setconf and resetconf. Acts like setconf, except
829 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
833 control_setconf_helper(control_connection_t
*conn
, uint32_t len
, char *body
,
834 int use_defaults
, int clear_first
)
837 config_line_t
*lines
=NULL
;
839 char *errstring
= NULL
;
840 int v0
= STATE_IS_V0(conn
->_base
.state
);
844 smartlist_t
*entries
= smartlist_create();
845 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
846 * separated by space. break it into a list of configuration entries. */
851 while (!TOR_ISSPACE(*eq
) && *eq
!= '=')
853 key
= tor_strndup(body
, eq
-body
);
860 char *val_start
= body
;
861 while (!TOR_ISSPACE(*body
))
863 val
= tor_strndup(val_start
, body
-val_start
);
864 val_len
= strlen(val
);
866 body
= (char*)get_escaped_string(body
, (len
- (body
-start
)),
869 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn
);
870 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
871 smartlist_free(entries
);
875 ent_len
= strlen(key
)+val_len
+3;
876 entry
= tor_malloc(ent_len
+1);
877 tor_snprintf(entry
, ent_len
, "%s %s", key
, val
);
883 smartlist_add(entries
, entry
);
884 while (TOR_ISSPACE(*body
))
888 smartlist_add(entries
, tor_strdup(""));
889 config
= smartlist_join_strings(entries
, "\n", 0, NULL
);
890 SMARTLIST_FOREACH(entries
, char *, cp
, tor_free(cp
));
891 smartlist_free(entries
);
893 if (config_get_lines(config
, &lines
) < 0) {
894 log_warn(LD_CONTROL
,"Controller gave us config lines we can't parse.");
895 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
902 if (config_get_lines(body
, &lines
) < 0) {
904 "V0 controller gave us config lines we can't parse.");
905 send_control0_error(conn
, ERR_SYNTAX
, "Couldn't parse configuration");
910 if ((r
=options_trial_assign(lines
, use_defaults
,
911 clear_first
, &errstring
)) < 0) {
915 "Controller gave us config lines that didn't validate: %s.",
919 v0_err
= ERR_UNRECOGNIZED_CONFIG_KEY
;
920 msg
= "552 Unrecognized option";
923 v0_err
= ERR_INVALID_CONFIG_VALUE
;
924 msg
= "513 Unacceptable option value";
927 v0_err
= ERR_INVALID_CONFIG_VALUE
;
928 msg
= "553 Transition not allowed";
932 v0_err
= ERR_INVALID_CONFIG_VALUE
;
933 msg
= "553 Unable to set option";
937 send_control0_error(conn
, v0_err
, msg
);
939 connection_printf_to_buf(conn
, "%s: %s\r\n", msg
, errstring
);
941 config_free_lines(lines
);
945 config_free_lines(lines
);
946 send_control_done(conn
);
950 /** Called when we receive a SETCONF message: parse the body and try
951 * to update our configuration. Reply with a DONE or ERROR message.
952 * Modifies the contents of body.*/
954 handle_control_setconf(control_connection_t
*conn
, uint32_t len
, char *body
)
956 return control_setconf_helper(conn
, len
, body
, 0, 1);
959 /** Called when we receive a RESETCONF message: parse the body and try
960 * to update our configuration. Reply with a DONE or ERROR message.
961 * Modifies the contents of body. */
963 handle_control_resetconf(control_connection_t
*conn
, uint32_t len
, char *body
)
965 int v0
= STATE_IS_V0(conn
->_base
.state
);
967 return control_setconf_helper(conn
, len
, body
, 1, 1);
970 /** Called when we receive a GETCONF message. Parse the request, and
971 * reply with a CONFVALUE or an ERROR message */
973 handle_control_getconf(control_connection_t
*conn
, uint32_t body_len
,
976 smartlist_t
*questions
= NULL
;
977 smartlist_t
*answers
= NULL
;
978 smartlist_t
*unrecognized
= NULL
;
981 or_options_t
*options
= get_options();
982 int v0
= STATE_IS_V0(conn
->_base
.state
);
984 questions
= smartlist_create();
985 (void) body_len
; /* body is nul-terminated; so we can ignore len. */
987 smartlist_split_string(questions
, body
, "\n",
988 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
990 smartlist_split_string(questions
, body
, " ",
991 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
993 answers
= smartlist_create();
994 unrecognized
= smartlist_create();
995 SMARTLIST_FOREACH(questions
, char *, q
,
997 if (!option_is_recognized(q
)) {
999 send_control0_error(conn
, ERR_UNRECOGNIZED_CONFIG_KEY
, q
);
1002 smartlist_add(unrecognized
, q
);
1005 config_line_t
*answer
= option_get_assignment(options
,q
);
1006 if (!v0
&& !answer
) {
1007 const char *name
= option_get_canonical_name(q
);
1008 size_t alen
= strlen(name
)+8;
1009 char *astr
= tor_malloc(alen
);
1010 tor_snprintf(astr
, alen
, "250-%s\r\n", name
);
1011 smartlist_add(answers
, astr
);
1015 config_line_t
*next
;
1016 size_t alen
= strlen(answer
->key
)+strlen(answer
->value
)+8;
1017 char *astr
= tor_malloc(alen
);
1019 tor_snprintf(astr
, alen
, "%s %s\n", answer
->key
, answer
->value
);
1021 tor_snprintf(astr
, alen
, "250-%s=%s\r\n",
1022 answer
->key
, answer
->value
);
1023 smartlist_add(answers
, astr
);
1025 next
= answer
->next
;
1026 tor_free(answer
->key
);
1027 tor_free(answer
->value
);
1035 msg
= smartlist_join_strings(answers
, "", 0, &msg_len
);
1036 send_control0_message(conn
, CONTROL0_CMD_CONFVALUE
,
1037 (uint16_t)msg_len
, msg_len
?msg
:NULL
);
1040 if ((len
= smartlist_len(unrecognized
))) {
1041 for (i
=0; i
< len
-1; ++i
)
1042 connection_printf_to_buf(conn
,
1043 "552-Unrecognized configuration key \"%s\"\r\n",
1044 (char*)smartlist_get(unrecognized
, i
));
1045 connection_printf_to_buf(conn
,
1046 "552 Unrecognized configuration key \"%s\"\r\n",
1047 (char*)smartlist_get(unrecognized
, len
-1));
1048 } else if ((len
= smartlist_len(answers
))) {
1049 char *tmp
= smartlist_get(answers
, len
-1);
1050 tor_assert(strlen(tmp
)>4);
1052 msg
= smartlist_join_strings(answers
, "", 0, &msg_len
);
1053 connection_write_to_buf(msg
, msg_len
, TO_CONN(conn
));
1055 connection_write_str_to_buf("250 OK\r\n", conn
);
1061 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
1062 smartlist_free(answers
);
1065 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
1066 smartlist_free(questions
);
1068 smartlist_free(unrecognized
);
1074 /** Called when we get a SETEVENTS message: update conn->event_mask,
1075 * and reply with DONE or ERROR. */
1077 handle_control_setevents(control_connection_t
*conn
, uint32_t len
,
1080 uint16_t event_code
;
1081 uint32_t event_mask
= 0;
1082 unsigned int extended
= 0;
1084 if (STATE_IS_V0(conn
->_base
.state
)) {
1086 send_control0_error(conn
, ERR_SYNTAX
,
1087 "Odd number of bytes in setevents message");
1091 for (; len
; len
-= 2, body
+= 2) {
1092 event_code
= ntohs(get_uint16(body
));
1093 if (event_code
< _EVENT_MIN
|| event_code
> LAST_V0_EVENT
) {
1094 send_control0_error(conn
, ERR_UNRECOGNIZED_EVENT_CODE
,
1095 "Unrecognized event code");
1098 event_mask
|= (1 << event_code
);
1101 smartlist_t
*events
= smartlist_create();
1102 smartlist_split_string(events
, body
, " ",
1103 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1104 SMARTLIST_FOREACH(events
, const char *, ev
,
1106 if (!strcasecmp(ev
, "EXTENDED")) {
1109 } else if (!strcasecmp(ev
, "CIRC"))
1110 event_code
= EVENT_CIRCUIT_STATUS
;
1111 else if (!strcasecmp(ev
, "STREAM"))
1112 event_code
= EVENT_STREAM_STATUS
;
1113 else if (!strcasecmp(ev
, "ORCONN"))
1114 event_code
= EVENT_OR_CONN_STATUS
;
1115 else if (!strcasecmp(ev
, "BW"))
1116 event_code
= EVENT_BANDWIDTH_USED
;
1117 else if (!strcasecmp(ev
, "DEBUG"))
1118 event_code
= EVENT_DEBUG_MSG
;
1119 else if (!strcasecmp(ev
, "INFO"))
1120 event_code
= EVENT_INFO_MSG
;
1121 else if (!strcasecmp(ev
, "NOTICE"))
1122 event_code
= EVENT_NOTICE_MSG
;
1123 else if (!strcasecmp(ev
, "WARN"))
1124 event_code
= EVENT_WARN_MSG
;
1125 else if (!strcasecmp(ev
, "ERR"))
1126 event_code
= EVENT_ERR_MSG
;
1127 else if (!strcasecmp(ev
, "NEWDESC"))
1128 event_code
= EVENT_NEW_DESC
;
1129 else if (!strcasecmp(ev
, "ADDRMAP"))
1130 event_code
= EVENT_ADDRMAP
;
1131 else if (!strcasecmp(ev
, "AUTHDIR_NEWDESCS"))
1132 event_code
= EVENT_AUTHDIR_NEWDESCS
;
1133 else if (!strcasecmp(ev
, "DESCCHANGED"))
1134 event_code
= EVENT_DESCCHANGED
;
1135 else if (!strcasecmp(ev
, "NS"))
1136 event_code
= EVENT_NS
;
1137 else if (!strcasecmp(ev
, "STATUS_GENERAL"))
1138 event_code
= EVENT_STATUS_GENERAL
;
1139 else if (!strcasecmp(ev
, "STATUS_CLIENT"))
1140 event_code
= EVENT_STATUS_CLIENT
;
1141 else if (!strcasecmp(ev
, "STATUS_SERVER"))
1142 event_code
= EVENT_STATUS_SERVER
;
1143 else if (!strcasecmp(ev
, "GUARD"))
1144 event_code
= EVENT_GUARD
;
1145 else if (!strcasecmp(ev
, "GUARDS")) {
1146 /* XXX tolerate buggy spec in 0.1.2.5-alpha through 0.1.2.10-rc */
1147 event_code
= EVENT_GUARD
;
1148 } else if (!strcasecmp(ev
, "STREAM_BW"))
1149 event_code
= EVENT_STREAM_BANDWIDTH_USED
;
1151 connection_printf_to_buf(conn
, "552 Unrecognized event \"%s\"\r\n",
1153 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
1154 smartlist_free(events
);
1157 event_mask
|= (1 << event_code
);
1159 SMARTLIST_FOREACH(events
, char *, e
, tor_free(e
));
1160 smartlist_free(events
);
1162 conn
->event_mask
= event_mask
;
1164 conn
->use_extended_events
= 1;
1166 control_update_global_event_mask();
1167 send_control_done(conn
);
1171 /** Decode the hashed, base64'd password stored in <b>hashed</b>. If
1172 * <b>buf</b> is provided, store the hashed password in the first
1173 * S2K_SPECIFIER_LEN+DIGEST_LEN bytes of <b>buf</b>. Return 0 on
1174 * success, -1 on failure.
1177 decode_hashed_password(char *buf
, const char *hashed
)
1180 if (!strcmpstart(hashed
, "16:")) {
1181 if (base16_decode(decoded
, sizeof(decoded
), hashed
+3, strlen(hashed
+3))<0
1182 || strlen(hashed
+3) != (S2K_SPECIFIER_LEN
+DIGEST_LEN
)*2) {
1186 if (base64_decode(decoded
, sizeof(decoded
), hashed
, strlen(hashed
))
1187 != S2K_SPECIFIER_LEN
+DIGEST_LEN
) {
1192 memcpy(buf
, decoded
, S2K_SPECIFIER_LEN
+DIGEST_LEN
);
1196 /** Called when we get an AUTHENTICATE message. Check whether the
1197 * authentication is valid, and if so, update the connection's state to
1198 * OPEN. Reply with DONE or ERROR.
1201 handle_control_authenticate(control_connection_t
*conn
, uint32_t len
,
1204 int used_quoted_string
= 0;
1205 or_options_t
*options
= get_options();
1206 const char *errstr
= NULL
;
1208 size_t password_len
;
1209 if (STATE_IS_V0(conn
->_base
.state
)) {
1210 password
= (char*)body
;
1213 if (TOR_ISXDIGIT(body
[0])) {
1215 while (TOR_ISXDIGIT(body
[i
]))
1217 password
= tor_malloc(i
/2 + 1);
1218 if (base16_decode(password
, i
/2+1, body
, i
)<0) {
1219 connection_write_str_to_buf(
1220 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1221 "password? If so, the standard requires that you put it in "
1222 "double quotes.\r\n", conn
);
1227 } else if (TOR_ISSPACE(body
[0])) {
1228 password
= tor_strdup("");
1231 if (!get_escaped_string(body
, len
, &password
, &password_len
)) {
1232 connection_write_str_to_buf("551 Invalid quoted string. You need "
1233 "to put the password in double quotes.\r\n", conn
);
1236 used_quoted_string
= 1;
1239 if (options
->CookieAuthentication
&& authentication_cookie_is_set
) {
1240 if (password_len
!= AUTHENTICATION_COOKIE_LEN
) {
1241 log_warn(LD_CONTROL
, "Got authentication cookie with wrong length (%d)",
1243 errstr
= "Wrong length on authentication cookie.";
1245 } else if (memcmp(authentication_cookie
, password
, password_len
)) {
1246 log_warn(LD_CONTROL
, "Got mismatched authentication cookie");
1247 errstr
= "Authentication cookie did not match expected value.";
1252 } else if (options
->HashedControlPassword
) {
1253 char expected
[S2K_SPECIFIER_LEN
+DIGEST_LEN
];
1254 char received
[DIGEST_LEN
];
1255 if (decode_hashed_password(expected
, options
->HashedControlPassword
)<0) {
1256 log_warn(LD_CONTROL
,
1257 "Couldn't decode HashedControlPassword: invalid base16");
1258 errstr
= "Couldn't decode HashedControlPassword value in configuration.";
1261 secret_to_key(received
,DIGEST_LEN
,password
,password_len
,expected
);
1262 if (!memcmp(expected
+S2K_SPECIFIER_LEN
, received
, DIGEST_LEN
))
1265 if (used_quoted_string
)
1266 errstr
= "Password did not match HashedControlPassword value from "
1269 errstr
= "Password did not match HashedControlPassword value from "
1270 "configuration. Maybe you tried a plain text password? "
1271 "If so, the standard requires that you put it in double quotes.";
1274 /* if Tor doesn't demand any stronger authentication, then
1275 * the controller can get in with anything. */
1280 if (STATE_IS_V0(conn
->_base
.state
))
1281 send_control0_error(conn
,ERR_REJECTED_AUTHENTICATION
,
1282 "Authentication failed");
1286 errstr
= "Unknown reason.";
1287 connection_printf_to_buf(conn
, "515 Authentication failed: %s\r\n",
1292 log_info(LD_CONTROL
, "Authenticated control connection (%d)", conn
->_base
.s
);
1293 send_control_done(conn
);
1294 if (STATE_IS_V0(conn
->_base
.state
))
1295 conn
->_base
.state
= CONTROL_CONN_STATE_OPEN_V0
;
1297 conn
->_base
.state
= CONTROL_CONN_STATE_OPEN_V1
;
1303 /** Called when we get a SAVECONF command. Try to flush the current options to
1304 * disk, and report success or failure. */
1306 handle_control_saveconf(control_connection_t
*conn
, uint32_t len
,
1311 if (options_save_current()<0) {
1312 if (STATE_IS_V0(conn
->_base
.state
))
1313 send_control0_error(conn
, ERR_INTERNAL
,
1314 "Unable to write configuration to disk.");
1316 connection_write_str_to_buf(
1317 "551 Unable to write configuration to disk.\r\n", conn
);
1319 send_control_done(conn
);
1324 /** Called when we get a SIGNAL command. React to the provided signal, and
1325 * report success or failure. (If the signal results in a shutdown, success
1326 * may not be reported.) */
1328 handle_control_signal(control_connection_t
*conn
, uint32_t len
,
1332 if (STATE_IS_V0(conn
->_base
.state
)) {
1334 send_control0_error(conn
, ERR_SYNTAX
,
1335 "Body of SIGNAL command too long or too short.");
1338 sig
= (uint8_t)body
[0];
1341 case 1: sig
= SIGHUP
; break;
1342 case 2: sig
= SIGINT
; break;
1343 case 10: sig
= SIGUSR1
; break;
1344 case 12: sig
= SIGUSR2
; break;
1345 case 15: sig
= SIGTERM
; break;
1346 case SIGNEWNYM
: break;
1348 send_control0_error(conn
, ERR_SYNTAX
, "Unrecognized signal number.");
1355 while (body
[n
] && ! TOR_ISSPACE(body
[n
]))
1357 s
= tor_strndup(body
, n
);
1358 if (!strcasecmp(s
, "RELOAD") || !strcasecmp(s
, "HUP"))
1360 else if (!strcasecmp(s
, "SHUTDOWN") || !strcasecmp(s
, "INT"))
1362 else if (!strcasecmp(s
, "DUMP") || !strcasecmp(s
, "USR1"))
1364 else if (!strcasecmp(s
, "DEBUG") || !strcasecmp(s
, "USR2"))
1366 else if (!strcasecmp(s
, "HALT") || !strcasecmp(s
, "TERM"))
1368 else if (!strcasecmp(s
, "NEWNYM"))
1370 else if (!strcasecmp(s
, "CLEARDNSCACHE"))
1371 sig
= SIGCLEARDNSCACHE
;
1373 connection_printf_to_buf(conn
, "552 Unrecognized signal code \"%s\"\r\n",
1382 /* Send DONE first, in case the signal makes us shut down. */
1383 send_control_done(conn
);
1384 control_signal_act(sig
);
1388 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1389 * and report success or failrue. */
1391 handle_control_mapaddress(control_connection_t
*conn
, uint32_t len
,
1399 int v0
= STATE_IS_V0(conn
->_base
.state
);
1400 (void) len
; /* body is nul-terminated, so it's safe to ignore the length. */
1402 lines
= smartlist_create();
1403 elts
= smartlist_create();
1404 reply
= smartlist_create();
1406 smartlist_split_string(lines
, body
, "\n",
1407 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1409 smartlist_split_string(lines
, body
, " ",
1410 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1411 SMARTLIST_FOREACH(lines
, char *, line
,
1415 smartlist_split_string(elts
, line
, " ", 0, 2);
1417 smartlist_split_string(elts
, line
, "=", 0, 2);
1418 if (smartlist_len(elts
) == 2) {
1419 const char *from
= smartlist_get(elts
,0);
1420 const char *to
= smartlist_get(elts
,1);
1421 size_t anslen
= strlen(line
)+512;
1422 char *ans
= tor_malloc(anslen
);
1423 if (address_is_invalid_destination(to
, 1)) {
1425 tor_snprintf(ans
, anslen
,
1426 "512-syntax error: invalid address '%s'", to
);
1427 smartlist_add(reply
, ans
);
1429 tor_free(ans
); /* don't respond if v0 */
1430 log_warn(LD_CONTROL
,
1431 "Skipping invalid argument '%s' in MapAddress msg", to
);
1432 } else if (!strcmp(from
, ".") || !strcmp(from
, "0.0.0.0")) {
1433 const char *address
= addressmap_register_virtual_address(
1434 !strcmp(from
,".") ? RESOLVED_TYPE_HOSTNAME
: RESOLVED_TYPE_IPV4
,
1438 tor_snprintf(ans
, anslen
,
1439 "451-resource exhausted: skipping '%s'", line
);
1440 smartlist_add(reply
, ans
);
1442 tor_free(ans
); /* don't respond if v0 */
1443 log_warn(LD_CONTROL
,
1444 "Unable to allocate address for '%s' in MapAddress msg",
1448 tor_snprintf(ans
, anslen
, "%s %s", address
, to
);
1450 tor_snprintf(ans
, anslen
, "250-%s=%s", address
, to
);
1451 smartlist_add(reply
, ans
);
1454 addressmap_register(from
, tor_strdup(to
), 1);
1456 tor_snprintf(ans
, anslen
, "%s", line
);
1458 tor_snprintf(ans
, anslen
, "250-%s", line
);
1459 smartlist_add(reply
, ans
);
1463 size_t anslen
= strlen(line
)+256;
1464 char *ans
= tor_malloc(anslen
);
1465 tor_snprintf(ans
, anslen
, "512-syntax error: mapping '%s' is "
1466 "not of expected form 'foo=bar'.", line
);
1467 smartlist_add(reply
, ans
);
1469 log_info(LD_CONTROL
, "Skipping MapAddress '%s': wrong "
1470 "number of items.", safe_str(line
));
1472 SMARTLIST_FOREACH(elts
, char *, cp
, tor_free(cp
));
1473 smartlist_clear(elts
);
1475 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
1476 smartlist_free(lines
);
1477 smartlist_free(elts
);
1480 r
= smartlist_join_strings(reply
, "\n", 1, &sz
);
1481 send_control_done2(conn
,r
,sz
);
1484 if (smartlist_len(reply
)) {
1485 ((char*)smartlist_get(reply
,smartlist_len(reply
)-1))[3] = ' ';
1486 r
= smartlist_join_strings(reply
, "\r\n", 1, &sz
);
1487 connection_write_to_buf(r
, sz
, TO_CONN(conn
));
1490 const char *response
=
1491 "512 syntax error: not enough arguments to mapaddress.\r\n";
1492 connection_write_to_buf(response
, strlen(response
), TO_CONN(conn
));
1496 SMARTLIST_FOREACH(reply
, char *, cp
, tor_free(cp
));
1497 smartlist_free(reply
);
1501 /** Implementation helper for GETINFO: knows the answers for various
1502 * trivial-to-implement questions. */
1504 getinfo_helper_misc(control_connection_t
*conn
, const char *question
,
1508 if (!strcmp(question
, "version")) {
1509 *answer
= tor_strdup(VERSION
);
1510 } else if (!strcmp(question
, "config-file")) {
1511 *answer
= tor_strdup(get_torrc_fname());
1512 } else if (!strcmp(question
, "info/names")) {
1513 *answer
= list_getinfo_options();
1514 } else if (!strcmp(question
, "events/names")) {
1515 *answer
= tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
1516 "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
1517 "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
1519 } else if (!strcmp(question
, "features/names")) {
1520 *answer
= tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1521 } else if (!strcmp(question
, "address")) {
1523 if (router_pick_published_address(get_options(), &addr
) < 0)
1525 *answer
= tor_dup_addr(addr
);
1526 } else if (!strcmp(question
, "dir-usage")) {
1527 *answer
= directory_dump_request_log();
1528 } else if (!strcmp(question
, "fingerprint")) {
1529 routerinfo_t
*me
= router_get_my_routerinfo();
1531 *answer
= tor_strdup("");
1533 *answer
= tor_malloc(HEX_DIGEST_LEN
+1);
1534 base16_encode(*answer
, HEX_DIGEST_LEN
+1, me
->cache_info
.identity_digest
,
1541 /** Implementation helper for GETINFO: knows the answers for questions about
1542 * directory information. */
1544 getinfo_helper_dir(control_connection_t
*control_conn
,
1545 const char *question
, char **answer
)
1547 if (!strcmpstart(question
, "desc/id/")) {
1548 routerinfo_t
*ri
= router_get_by_hexdigest(question
+strlen("desc/id/"));
1550 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1552 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
1554 } else if (!strcmpstart(question
, "desc/name/")) {
1555 routerinfo_t
*ri
= router_get_by_nickname(question
+strlen("desc/name/"),1);
1557 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1559 *answer
= tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
);
1561 } else if (!strcmp(question
, "desc/all-recent")) {
1562 routerlist_t
*routerlist
= router_get_routerlist();
1563 smartlist_t
*sl
= smartlist_create();
1564 if (routerlist
&& routerlist
->routers
) {
1565 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
1567 const char *body
= signed_descriptor_get_body(&ri
->cache_info
);
1570 tor_strndup(body
, ri
->cache_info
.signed_descriptor_len
));
1573 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
1574 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
1576 } else if (!strcmpstart(question
, "dir/server/")) {
1577 size_t answer_len
= 0, url_len
= strlen(question
)+2;
1578 char *url
= tor_malloc(url_len
);
1579 smartlist_t
*descs
= smartlist_create();
1583 tor_snprintf(url
, url_len
, "/tor/%s", question
+4);
1584 res
= dirserv_get_routerdescs(descs
, url
, &msg
);
1586 log_warn(LD_CONTROL
, "getinfo '%s': %s", question
, msg
);
1589 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
1590 answer_len
+= sd
->signed_descriptor_len
);
1591 cp
= *answer
= tor_malloc(answer_len
+1);
1592 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, sd
,
1594 memcpy(cp
, signed_descriptor_get_body(sd
),
1595 sd
->signed_descriptor_len
);
1596 cp
+= sd
->signed_descriptor_len
;
1600 smartlist_free(descs
);
1601 } else if (!strcmpstart(question
, "dir/status/")) {
1602 if (get_options()->DirPort
) {
1605 smartlist_t
*status_list
= smartlist_create();
1606 dirserv_get_networkstatus_v2(status_list
,
1607 question
+strlen("dir/status/"));
1608 SMARTLIST_FOREACH(status_list
, cached_dir_t
*, d
, len
+= d
->dir_len
);
1609 cp
= *answer
= tor_malloc(len
+1);
1610 SMARTLIST_FOREACH(status_list
, cached_dir_t
*, d
, {
1611 memcpy(cp
, d
->dir
, d
->dir_len
);
1615 smartlist_free(status_list
);
1617 smartlist_t
*fp_list
= smartlist_create();
1618 smartlist_t
*status_list
= smartlist_create();
1619 size_t fn_len
= strlen(get_options()->DataDirectory
)+HEX_DIGEST_LEN
+32;
1620 char *fn
= tor_malloc(fn_len
+1);
1621 char hex_id
[HEX_DIGEST_LEN
+1];
1622 dirserv_get_networkstatus_v2_fingerprints(
1623 fp_list
, question
+strlen("dir/status/"));
1624 SMARTLIST_FOREACH(fp_list
, const char *, fp
, {
1626 base16_encode(hex_id
, sizeof(hex_id
), fp
, DIGEST_LEN
);
1627 tor_snprintf(fn
, fn_len
, "%s/cached-status/%s",
1628 get_options()->DataDirectory
, hex_id
);
1629 s
= read_file_to_str(fn
, 0, NULL
);
1631 smartlist_add(status_list
, s
);
1633 SMARTLIST_FOREACH(fp_list
, char *, fp
, tor_free(fp
));
1634 smartlist_free(fp_list
);
1635 *answer
= smartlist_join_strings(status_list
, "", 0, NULL
);
1636 SMARTLIST_FOREACH(status_list
, char *, s
, tor_free(s
));
1637 smartlist_free(status_list
);
1639 } else if (!strcmp(question
, "network-status")) {
1640 routerlist_t
*routerlist
= router_get_routerlist();
1641 int verbose
= control_conn
->use_long_names
;
1642 if (!routerlist
|| !routerlist
->routers
||
1643 list_server_status(routerlist
->routers
, answer
, verbose
? 2 : 1) < 0) {
1650 /** Implementation helper for GETINFO: knows how to generate summaries of the
1651 * current states of things we send events about. */
1653 getinfo_helper_events(control_connection_t
*control_conn
,
1654 const char *question
, char **answer
)
1656 if (!strcmp(question
, "circuit-status")) {
1658 smartlist_t
*status
= smartlist_create();
1659 for (circ
= _circuit_get_global_list(); circ
; circ
= circ
->next
) {
1663 if (! CIRCUIT_IS_ORIGIN(circ
) || circ
->marked_for_close
)
1665 if (control_conn
->use_long_names
)
1666 path
= circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ
));
1668 path
= circuit_list_path(TO_ORIGIN_CIRCUIT(circ
),0);
1669 if (circ
->state
== CIRCUIT_STATE_OPEN
)
1671 else if (strlen(path
))
1676 slen
= strlen(path
)+strlen(state
)+20;
1677 s
= tor_malloc(slen
+1);
1678 tor_snprintf(s
, slen
, "%lu %s %s",
1679 (unsigned long)TO_ORIGIN_CIRCUIT(circ
)->global_identifier
,
1681 smartlist_add(status
, s
);
1684 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1685 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1686 smartlist_free(status
);
1687 } else if (!strcmp(question
, "stream-status")) {
1688 connection_t
**conns
;
1691 smartlist_t
*status
= smartlist_create();
1692 get_connection_array(&conns
, &n_conns
);
1693 for (i
=0; i
< n_conns
; ++i
) {
1695 edge_connection_t
*conn
;
1699 origin_circuit_t
*origin_circ
= NULL
;
1700 if (conns
[i
]->type
!= CONN_TYPE_AP
||
1701 conns
[i
]->marked_for_close
||
1702 conns
[i
]->state
== AP_CONN_STATE_SOCKS_WAIT
||
1703 conns
[i
]->state
== AP_CONN_STATE_NATD_WAIT
)
1705 conn
= TO_EDGE_CONN(conns
[i
]);
1706 switch (conn
->_base
.state
)
1708 case AP_CONN_STATE_CONTROLLER_WAIT
:
1709 case AP_CONN_STATE_CIRCUIT_WAIT
:
1710 if (conn
->socks_request
&&
1711 SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
))
1712 state
= "NEWRESOLVE";
1716 case AP_CONN_STATE_RENDDESC_WAIT
:
1717 case AP_CONN_STATE_CONNECT_WAIT
:
1718 state
= "SENTCONNECT"; break;
1719 case AP_CONN_STATE_RESOLVE_WAIT
:
1720 state
= "SENTRESOLVE"; break;
1721 case AP_CONN_STATE_OPEN
:
1722 state
= "SUCCEEDED"; break;
1724 log_warn(LD_BUG
, "Asked for stream in unknown state %d",
1728 circ
= circuit_get_by_edge_conn(conn
);
1729 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
1730 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
1731 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
1732 slen
= strlen(buf
)+strlen(state
)+32;
1733 s
= tor_malloc(slen
+1);
1734 tor_snprintf(s
, slen
, "%lu %s %lu %s",
1735 (unsigned long) conn
->global_identifier
,state
,
1737 (unsigned long)origin_circ
->global_identifier
: 0ul,
1739 smartlist_add(status
, s
);
1741 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1742 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1743 smartlist_free(status
);
1744 } else if (!strcmp(question
, "orconn-status")) {
1745 connection_t
**conns
;
1747 smartlist_t
*status
= smartlist_create();
1748 get_connection_array(&conns
, &n_conns
);
1749 for (i
=0; i
< n_conns
; ++i
) {
1754 or_connection_t
*conn
;
1755 if (conns
[i
]->type
!= CONN_TYPE_OR
|| conns
[i
]->marked_for_close
)
1757 conn
= TO_OR_CONN(conns
[i
]);
1758 if (conn
->_base
.state
== OR_CONN_STATE_OPEN
)
1759 state
= "CONNECTED";
1760 else if (conn
->nickname
)
1764 orconn_target_get_name(control_conn
->use_long_names
, name
, sizeof(name
),
1766 slen
= strlen(name
)+strlen(state
)+2;
1767 s
= tor_malloc(slen
+1);
1768 tor_snprintf(s
, slen
, "%s %s", name
, state
);
1769 smartlist_add(status
, s
);
1771 *answer
= smartlist_join_strings(status
, "\r\n", 0, NULL
);
1772 SMARTLIST_FOREACH(status
, char *, cp
, tor_free(cp
));
1773 smartlist_free(status
);
1774 } else if (!strcmpstart(question
, "addr-mappings/")) {
1775 time_t min_e
, max_e
;
1776 smartlist_t
*mappings
;
1777 if (!strcmp(question
, "addr-mappings/all")) {
1778 min_e
= 0; max_e
= TIME_MAX
;
1779 } else if (!strcmp(question
, "addr-mappings/cache")) {
1780 min_e
= 2; max_e
= TIME_MAX
;
1781 } else if (!strcmp(question
, "addr-mappings/config")) {
1782 min_e
= 0; max_e
= 0;
1783 } else if (!strcmp(question
, "addr-mappings/control")) {
1784 min_e
= 1; max_e
= 1;
1788 mappings
= smartlist_create();
1789 addressmap_get_mappings(mappings
, min_e
, max_e
);
1790 *answer
= smartlist_join_strings(mappings
, "\r\n", 0, NULL
);
1791 SMARTLIST_FOREACH(mappings
, char *, cp
, tor_free(cp
));
1792 smartlist_free(mappings
);
1797 /** Callback function for GETINFO: on a given control connection, try to
1798 * answer the question <b>q</b> and store the newly-allocated answer in
1799 * *<b>a</b>. If there's no answer, or an error occurs, just don't set
1800 * <b>a</b>. Return 0.
1802 typedef int (*getinfo_helper_t
)(control_connection_t
*,
1803 const char *q
, char **a
);
1805 /** A single item for the GETINFO question-to-answer-function table. */
1806 typedef struct getinfo_item_t
{
1807 const char *varname
; /**< The value (or prefix) of the question. */
1808 getinfo_helper_t fn
; /**< The function that knows the answer: NULL if
1809 * this entry is documentation-only. */
1810 const char *desc
; /**< Description of the variable. */
1811 int is_prefix
; /** Must varname match exactly, or must it be a prefix? */
1814 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
1815 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
1816 #define DOC(name, desc) { name, NULL, desc, 0 }
1818 /** Table mapping questions accepted by GETINFO to the functions that know how
1819 * to answer them. */
1820 static const getinfo_item_t getinfo_items
[] = {
1821 ITEM("version", misc
, "The current version of Tor."),
1822 ITEM("config-file", misc
, "Current location of the \"torrc\" file."),
1823 ITEM("accounting/bytes", accounting
,
1824 "Number of bytes read/written so far in the accounting interval."),
1825 ITEM("accounting/bytes-left", accounting
,
1826 "Number of bytes left to write/read so far in the accounting interval."),
1827 ITEM("accounting/enabled", accounting
, "Is accounting currently enabled?"),
1828 ITEM("accounting/hibernating", accounting
, "Are we hibernating or awake?"),
1829 ITEM("accounting/interval-start", accounting
,
1830 "Time when the accounting period starts."),
1831 ITEM("accounting/interval-end", accounting
,
1832 "Time when the accounting period ends."),
1833 ITEM("accounting/interval-wake", accounting
,
1834 "Time to wake up in this accounting period."),
1835 ITEM("helper-nodes", entry_guards
, NULL
), /* deprecated */
1836 ITEM("entry-guards", entry_guards
,
1837 "Which nodes are we using as entry guards?"),
1838 ITEM("fingerprint", misc
, NULL
),
1839 PREFIX("config/", config
, "Current configuration values."),
1841 "List of configuration options, types, and documentation."),
1842 ITEM("info/names", misc
,
1843 "List of GETINFO options, types, and documentation."),
1844 ITEM("events/names", misc
,
1845 "Events that the controller can ask for with SETEVENTS."),
1846 ITEM("features/names", misc
, "What arguments can USEFEATURE take?"),
1847 PREFIX("desc/id/", dir
, "Router descriptors by ID."),
1848 PREFIX("desc/name/", dir
, "Router descriptors by nickname."),
1849 ITEM("desc/all-recent", dir
,
1850 "All non-expired, non-superseded router descriptors."),
1851 ITEM("ns/all", networkstatus
,
1852 "Brief summary of router status (v2 directory format)"),
1853 PREFIX("ns/id/", networkstatus
,
1854 "Brief summary of router status by ID (v2 directory format)."),
1855 PREFIX("ns/name/", networkstatus
,
1856 "Brief summary of router status by nickname (v2 directory format)."),
1858 PREFIX("unregisterd-servers-", dirserv_unregistered
, NULL
),
1859 ITEM("network-status", dir
,
1860 "Brief summary of router status (v1 directory format)"),
1861 ITEM("circuit-status", events
, "List of current circuits originating here."),
1862 ITEM("stream-status", events
,"List of current streams."),
1863 ITEM("orconn-status", events
, "A list of current OR connections."),
1864 PREFIX("addr-mappings/", events
, NULL
),
1865 DOC("addr-mappings/all", "Current address mappings."),
1866 DOC("addr-mappings/cache", "Current cached DNS replies."),
1867 DOC("addr-mappings/config", "Current address mappings from configuration."),
1868 DOC("addr-mappings/control", "Current address mappings from controller."),
1870 ITEM("address", misc
, "IP address of this Tor host, if we can guess it."),
1871 ITEM("dir-usage", misc
, "Breakdown of bytes transferred over DirPort."),
1872 PREFIX("dir/server/", dir
,"Router descriptors as retrieved from a DirPort."),
1873 PREFIX("dir/status/", dir
,"Networkstatus docs as retrieved from a DirPort."),
1874 PREFIX("exit-policy/default", policies
,
1875 "The default value appended to the configured exit policy."),
1877 { NULL
, NULL
, NULL
, 0 }
1880 /** Allocate and return a list of recognized GETINFO options. */
1882 list_getinfo_options(void)
1886 smartlist_t
*lines
= smartlist_create();
1888 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
1889 if (!getinfo_items
[i
].desc
)
1892 tor_snprintf(buf
, sizeof(buf
), "%s%s -- %s\n",
1893 getinfo_items
[i
].varname
,
1894 getinfo_items
[i
].is_prefix
? "*" : "",
1895 getinfo_items
[i
].desc
);
1896 smartlist_add(lines
, tor_strdup(buf
));
1898 smartlist_sort_strings(lines
);
1900 ans
= smartlist_join_strings(lines
, "", 0, NULL
);
1901 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
1902 smartlist_free(lines
);
1907 /** Lookup the 'getinfo' entry <b>question</b>, and return
1908 * the answer in <b>*answer</b> (or NULL if key not recognized).
1909 * Return 0 if success or unrecognized, or -1 if recognized but
1910 * internal error. */
1912 handle_getinfo_helper(control_connection_t
*control_conn
,
1913 const char *question
, char **answer
)
1916 *answer
= NULL
; /* unrecognized key by default */
1918 for (i
= 0; getinfo_items
[i
].varname
; ++i
) {
1920 if (getinfo_items
[i
].is_prefix
)
1921 match
= !strcmpstart(question
, getinfo_items
[i
].varname
);
1923 match
= !strcmp(question
, getinfo_items
[i
].varname
);
1925 tor_assert(getinfo_items
[i
].fn
);
1926 return getinfo_items
[i
].fn(control_conn
, question
, answer
);
1930 return 0; /* unrecognized */
1933 /** Called when we receive a GETINFO command. Try to fetch all requested
1934 * information, and reply with information or error message. */
1936 handle_control_getinfo(control_connection_t
*conn
, uint32_t len
,
1939 smartlist_t
*questions
= NULL
;
1940 smartlist_t
*answers
= NULL
;
1941 smartlist_t
*unrecognized
= NULL
;
1942 char *msg
= NULL
, *ans
= NULL
;
1944 int v0
= STATE_IS_V0(conn
->_base
.state
);
1945 (void) len
; /* body is nul-terminated, so it's safe to ignore the length. */
1947 questions
= smartlist_create();
1949 smartlist_split_string(questions
, body
, "\n",
1950 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1952 smartlist_split_string(questions
, body
, " ",
1953 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1954 answers
= smartlist_create();
1955 unrecognized
= smartlist_create();
1956 SMARTLIST_FOREACH(questions
, const char *, q
,
1958 if (handle_getinfo_helper(conn
, q
, &ans
) < 0) {
1960 send_control0_error(conn
, ERR_INTERNAL
, body
);
1962 connection_write_str_to_buf("551 Internal error\r\n", conn
);
1967 send_control0_error(conn
, ERR_UNRECOGNIZED_CONFIG_KEY
, body
);
1970 smartlist_add(unrecognized
, (char*)q
);
1972 smartlist_add(answers
, tor_strdup(q
));
1973 smartlist_add(answers
, ans
);
1976 if (smartlist_len(unrecognized
)) {
1979 for (i
=0; i
< smartlist_len(unrecognized
)-1; ++i
)
1980 connection_printf_to_buf(conn
,
1981 "552-Unrecognized key \"%s\"\r\n",
1982 (char*)smartlist_get(unrecognized
, i
));
1983 connection_printf_to_buf(conn
,
1984 "552 Unrecognized key \"%s\"\r\n",
1985 (char*)smartlist_get(unrecognized
, i
));
1990 msg
= smartlist_join_strings2(answers
, "\0", 1, 1, &msg_len
);
1991 tor_assert(msg_len
> 0); /* it will at least be terminated */
1992 send_control0_message(conn
, CONTROL0_CMD_INFOVALUE
,
1996 for (i
= 0; i
< smartlist_len(answers
); i
+= 2) {
1997 char *k
= smartlist_get(answers
, i
);
1998 char *v
= smartlist_get(answers
, i
+1);
1999 if (!strchr(v
, '\n') && !strchr(v
, '\r')) {
2000 connection_printf_to_buf(conn
, "250-%s=", k
);
2001 connection_write_str_to_buf(v
, conn
);
2002 connection_write_str_to_buf("\r\n", conn
);
2006 len
= write_escaped_data(v
, strlen(v
), 1, &esc
);
2007 connection_printf_to_buf(conn
, "250+%s=\r\n", k
);
2008 connection_write_to_buf(esc
, len
, TO_CONN(conn
));
2012 connection_write_str_to_buf("250 OK\r\n", conn
);
2017 SMARTLIST_FOREACH(answers
, char *, cp
, tor_free(cp
));
2018 smartlist_free(answers
);
2021 SMARTLIST_FOREACH(questions
, char *, cp
, tor_free(cp
));
2022 smartlist_free(questions
);
2024 smartlist_free(unrecognized
);
2030 /** If *<b>string</b> contains a recognized purpose (for
2031 * circuits if <b>for_circuits</b> is 1, else for routers),
2032 * possibly prefaced with the string "purpose=", then assign it
2033 * and return 0. Otherwise return -1.
2035 * If it's prefaced with "purpose=", then set *<b>string</b> to
2036 * the remainder of the string. */
2038 get_purpose(char **string
, int for_circuits
, uint8_t *purpose
)
2040 if (!strcmpstart(*string
, "purpose="))
2041 *string
+= strlen("purpose=");
2043 if (!strcmp(*string
, "general"))
2044 *purpose
= for_circuits
? CIRCUIT_PURPOSE_C_GENERAL
:
2045 ROUTER_PURPOSE_GENERAL
;
2046 else if (!strcmp(*string
, "controller"))
2047 *purpose
= for_circuits
? CIRCUIT_PURPOSE_CONTROLLER
:
2048 ROUTER_PURPOSE_CONTROLLER
;
2049 else { /* not a recognized purpose */
2055 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
2056 * circuit, and report success or failure. */
2058 handle_control_extendcircuit(control_connection_t
*conn
, uint32_t len
,
2061 smartlist_t
*router_nicknames
=NULL
, *routers
=NULL
;
2063 origin_circuit_t
*circ
= NULL
;
2066 uint8_t intended_purpose
= CIRCUIT_PURPOSE_C_GENERAL
;
2068 v0
= STATE_IS_V0(conn
->_base
.state
);
2069 router_nicknames
= smartlist_create();
2073 send_control0_error(conn
, ERR_SYNTAX
, "extendcircuit message too short");
2076 smartlist_split_string(router_nicknames
, body
+4, ",", 0, 0);
2077 circ_id
= ntohl(get_uint32(body
));
2079 /* start a new circuit */
2082 circ
= circuit_get_by_global_id(circ_id
);
2085 send_control0_error(conn
, ERR_NO_CIRC
,
2086 "No circuit found with given ID");
2092 args
= smartlist_create();
2093 smartlist_split_string(args
, body
, " ",
2094 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2095 if (smartlist_len(args
)<2) {
2096 connection_printf_to_buf(conn
,
2097 "512 Missing argument to EXTENDCIRCUIT\r\n");
2098 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2099 smartlist_free(args
);
2103 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,0));
2104 if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
,0)))) {
2105 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2106 (char*)smartlist_get(args
, 0));
2108 smartlist_split_string(router_nicknames
, smartlist_get(args
,1), ",", 0, 0);
2110 if (zero_circ
&& smartlist_len(args
)>2) {
2111 char *purp
= smartlist_get(args
,2);
2112 if (get_purpose(&purp
, 1, &intended_purpose
) < 0) {
2113 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
2114 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2115 smartlist_free(args
);
2119 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2120 smartlist_free(args
);
2121 if (!zero_circ
&& !circ
) {
2126 routers
= smartlist_create();
2127 SMARTLIST_FOREACH(router_nicknames
, const char *, n
,
2129 routerinfo_t
*r
= router_get_by_nickname(n
, 1);
2132 send_control0_error(conn
, ERR_NO_ROUTER
, n
);
2134 connection_printf_to_buf(conn
, "552 No such router \"%s\"\r\n", n
);
2137 smartlist_add(routers
, r
);
2139 if (!smartlist_len(routers
)) {
2141 send_control0_error(conn
, ERR_SYNTAX
, "No router names provided");
2143 connection_write_str_to_buf("512 No router names provided\r\n", conn
);
2148 /* start a new circuit */
2149 circ
= origin_circuit_init(intended_purpose
, 0, 0, 0, 0);
2152 /* now circ refers to something that is ready to be extended */
2153 SMARTLIST_FOREACH(routers
, routerinfo_t
*, r
,
2155 extend_info_t
*info
= extend_info_from_router(r
);
2156 circuit_append_new_exit(circ
, info
);
2157 extend_info_free(info
);
2160 /* now that we've populated the cpath, start extending */
2163 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
2164 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
2166 send_control0_error(conn
, ERR_INTERNAL
, "couldn't start circuit");
2168 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn
);
2172 if (circ
->_base
.state
== CIRCUIT_STATE_OPEN
) {
2174 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
2175 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
2176 log_info(LD_CONTROL
,
2177 "send_next_onion_skin failed; circuit marked for closing.");
2178 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
2180 send_control0_error(conn
, ERR_INTERNAL
, "couldn't send onion skin");
2182 connection_write_str_to_buf("551 Couldn't send onion skinr\n", conn
);
2189 set_uint32(reply
, htonl(circ
->global_identifier
));
2190 send_control_done2(conn
, reply
, sizeof(reply
));
2192 connection_printf_to_buf(conn
, "250 EXTENDED %lu\r\n",
2193 (unsigned long)circ
->global_identifier
);
2195 if (zero_circ
) /* send a 'launched' event, for completeness */
2196 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
2198 SMARTLIST_FOREACH(router_nicknames
, char *, n
, tor_free(n
));
2199 smartlist_free(router_nicknames
);
2201 smartlist_free(routers
);
2205 /** Called when we get a SETCIRCUITPURPOSE (if <b>for_circuits</b>
2206 * is 1) or SETROUTERPURPOSE message. If we can find
2207 * the circuit/router and it's a valid purpose, change it. */
2209 handle_control_setpurpose(control_connection_t
*conn
, int for_circuits
,
2210 uint32_t len
, const char *body
)
2212 origin_circuit_t
*circ
= NULL
;
2213 routerinfo_t
*ri
= NULL
;
2214 uint8_t new_purpose
;
2215 smartlist_t
*args
= smartlist_create();
2216 (void) len
; /* body is nul-terminated, so it's safe to ignore the length. */
2217 smartlist_split_string(args
, body
, " ",
2218 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2219 if (smartlist_len(args
)<2) {
2220 connection_printf_to_buf(conn
,
2221 "512 Missing argument to SET%sPURPOSE\r\n",
2222 for_circuits
? "CIRCUIT" : "ROUTER");
2227 if (!(circ
= get_circ(smartlist_get(args
,0)))) {
2228 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2229 (char*)smartlist_get(args
, 0));
2233 if (!(ri
= router_get_by_nickname(smartlist_get(args
,0), 0))) {
2234 connection_printf_to_buf(conn
, "552 Unknown router \"%s\"\r\n",
2235 (char*)smartlist_get(args
, 0));
2241 char *purp
= smartlist_get(args
,1);
2242 if (get_purpose(&purp
, for_circuits
, &new_purpose
) < 0) {
2243 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n", purp
);
2249 circ
->_base
.purpose
= new_purpose
;
2251 ri
->purpose
= new_purpose
;
2252 connection_write_str_to_buf("250 OK\r\n", conn
);
2255 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2256 smartlist_free(args
);
2260 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
2261 * stream, and report success or failure. */
2263 handle_control_attachstream(control_connection_t
*conn
, uint32_t len
,
2266 edge_connection_t
*ap_conn
= NULL
;
2267 origin_circuit_t
*circ
= NULL
;
2270 if (STATE_IS_V0(conn
->_base
.state
)) {
2274 send_control0_error(conn
, ERR_SYNTAX
, "attachstream message too short");
2278 conn_id
= ntohl(get_uint32(body
));
2279 circ_id
= ntohl(get_uint32(body
+4));
2280 zero_circ
= circ_id
== 0;
2282 if (!(ap_conn
= connection_get_by_global_id(conn_id
))) {
2283 send_control0_error(conn
, ERR_NO_STREAM
,
2284 "No connection found with given ID");
2287 if (circ_id
&& !(circ
= circuit_get_by_global_id(circ_id
))) {
2288 send_control0_error(conn
, ERR_NO_CIRC
, "No circuit found with given ID");
2293 args
= smartlist_create();
2294 smartlist_split_string(args
, body
, " ",
2295 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2296 if (smartlist_len(args
)<2) {
2297 connection_printf_to_buf(conn
,
2298 "512 Missing argument to ATTACHSTREAM\r\n");
2299 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2300 smartlist_free(args
);
2304 zero_circ
= !strcmp("0", (char*)smartlist_get(args
,1));
2306 if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))) {
2307 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2308 (char*)smartlist_get(args
, 0));
2309 } else if (!zero_circ
&& !(circ
= get_circ(smartlist_get(args
, 1)))) {
2310 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2311 (char*)smartlist_get(args
, 1));
2313 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2314 smartlist_free(args
);
2315 if (!ap_conn
|| (!zero_circ
&& !circ
))
2319 if (ap_conn
->_base
.state
!= AP_CONN_STATE_CONTROLLER_WAIT
&&
2320 ap_conn
->_base
.state
!= AP_CONN_STATE_CONNECT_WAIT
&&
2321 ap_conn
->_base
.state
!= AP_CONN_STATE_RESOLVE_WAIT
) {
2322 if (STATE_IS_V0(conn
->_base
.state
)) {
2323 send_control0_error(conn
, ERR_NO_STREAM
,
2324 "Connection is not managed by controller.");
2326 connection_write_str_to_buf(
2327 "555 Connection is not managed by controller.\r\n",
2333 /* Do we need to detach it first? */
2334 if (ap_conn
->_base
.state
!= AP_CONN_STATE_CONTROLLER_WAIT
) {
2335 circuit_t
*tmpcirc
= circuit_get_by_edge_conn(ap_conn
);
2336 connection_edge_end(ap_conn
, END_STREAM_REASON_TIMEOUT
,
2337 ap_conn
->cpath_layer
);
2338 /* Un-mark it as ending, since we're going to reuse it. */
2339 ap_conn
->_base
.edge_has_sent_end
= 0;
2340 ap_conn
->end_reason
= 0;
2342 circuit_detach_stream(tmpcirc
,ap_conn
);
2343 ap_conn
->_base
.state
= AP_CONN_STATE_CONTROLLER_WAIT
;
2346 if (circ
&& (circ
->_base
.state
!= CIRCUIT_STATE_OPEN
)) {
2347 if (STATE_IS_V0(conn
->_base
.state
))
2348 send_control0_error(conn
, ERR_INTERNAL
,
2349 "Refuse to attach stream to non-open, origin circ.");
2351 connection_write_str_to_buf(
2352 "551 Can't attach stream to non-open, origin circuit\r\n",
2356 if (circ
&& circuit_get_cpath_len(circ
) < 2) {
2357 if (STATE_IS_V0(conn
->_base
.state
))
2358 send_control0_error(conn
, ERR_INTERNAL
,
2359 "Refuse to attach stream to one-hop circuit.");
2361 connection_write_str_to_buf(
2362 "551 Can't attach stream to one-hop circuit.\r\n",
2366 if (connection_ap_handshake_rewrite_and_attach(ap_conn
, circ
) < 0) {
2367 if (STATE_IS_V0(conn
->_base
.state
))
2368 send_control0_error(conn
, ERR_INTERNAL
, "Unable to attach stream.");
2370 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn
);
2373 send_control_done(conn
);
2377 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
2378 * descriptor, and report success or failure. */
2380 handle_control_postdescriptor(control_connection_t
*conn
, uint32_t len
,
2384 int v0
= STATE_IS_V0(conn
->_base
.state
);
2385 const char *msg
=NULL
;
2386 uint8_t purpose
= ROUTER_PURPOSE_GENERAL
;
2391 char *cp
= memchr(body
, '\n', len
);
2392 smartlist_t
*args
= smartlist_create();
2395 smartlist_split_string(args
, body
, " ",
2396 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2397 if (smartlist_len(args
)) {
2398 char *purp
= smartlist_get(args
,0);
2399 if (get_purpose(&purp
, 0, &purpose
) < 0) {
2400 connection_printf_to_buf(conn
, "552 Unknown purpose \"%s\"\r\n",
2402 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2403 smartlist_free(args
);
2407 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2408 smartlist_free(args
);
2409 read_escaped_data(cp
, len
-(cp
-body
), 1, &desc
);
2412 switch (router_load_single_router(desc
, purpose
, &msg
)) {
2414 if (!msg
) msg
= "Could not parse descriptor";
2416 send_control0_error(conn
,ERR_SYNTAX
,msg
);
2418 connection_printf_to_buf(conn
, "554 %s\r\n", msg
);
2421 if (!msg
) msg
= "Descriptor not added";
2423 send_control_done2(conn
,msg
,0);
2425 connection_printf_to_buf(conn
, "251 %s\r\n",msg
);
2428 send_control_done(conn
);
2437 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
2438 * address of the named AP stream, and report success or failure. */
2440 handle_control_redirectstream(control_connection_t
*conn
, uint32_t len
,
2443 edge_connection_t
*ap_conn
= NULL
;
2445 char *new_addr
= NULL
;
2446 uint16_t new_port
= 0;
2447 if (STATE_IS_V0(conn
->_base
.state
)) {
2449 send_control0_error(conn
, ERR_SYNTAX
,
2450 "redirectstream message too short");
2453 conn_id
= ntohl(get_uint32(body
));
2455 if (!(ap_conn
= connection_get_by_global_id(conn_id
))
2456 || ap_conn
->_base
.state
!= CONN_TYPE_AP
2457 || ap_conn
->socks_request
) {
2458 send_control0_error(conn
, ERR_NO_STREAM
,
2459 "No AP connection found with given ID");
2462 new_addr
= tor_strdup(body
+4);
2465 args
= smartlist_create();
2466 smartlist_split_string(args
, body
, " ",
2467 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2468 if (smartlist_len(args
) < 2)
2469 connection_printf_to_buf(conn
,
2470 "512 Missing argument to REDIRECTSTREAM\r\n");
2471 else if (!(ap_conn
= get_stream(smartlist_get(args
, 0)))
2472 || !ap_conn
->socks_request
) {
2473 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2474 (char*)smartlist_get(args
, 0));
2477 if (smartlist_len(args
) > 2) { /* they included a port too */
2478 new_port
= (uint16_t) tor_parse_ulong(smartlist_get(args
, 2),
2479 10, 1, 65535, &ok
, NULL
);
2482 connection_printf_to_buf(conn
, "512 Cannot parse port \"%s\"\r\n",
2483 (char*)smartlist_get(args
, 2));
2485 new_addr
= tor_strdup(smartlist_get(args
, 1));
2489 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2490 smartlist_free(args
);
2495 strlcpy(ap_conn
->socks_request
->address
, new_addr
,
2496 sizeof(ap_conn
->socks_request
->address
));
2498 ap_conn
->socks_request
->port
= new_port
;
2500 send_control_done(conn
);
2504 /** Called when we get a CLOSESTREAM command; try to close the named stream
2505 * and report success or failure. */
2507 handle_control_closestream(control_connection_t
*conn
, uint32_t len
,
2510 edge_connection_t
*ap_conn
=NULL
;
2513 if (STATE_IS_V0(conn
->_base
.state
)) {
2516 send_control0_error(conn
, ERR_SYNTAX
, "closestream message too short");
2520 conn_id
= ntohl(get_uint32(body
));
2521 reason
= *(uint8_t*)(body
+4);
2523 if (!(ap_conn
= connection_get_by_global_id(conn_id
))
2524 || ap_conn
->_base
.state
!= CONN_TYPE_AP
2525 || ap_conn
->socks_request
) {
2526 send_control0_error(conn
, ERR_NO_STREAM
,
2527 "No AP connection found with given ID");
2533 args
= smartlist_create();
2534 smartlist_split_string(args
, body
, " ",
2535 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2536 if (smartlist_len(args
)<2)
2537 connection_printf_to_buf(conn
,
2538 "512 Missing argument to CLOSESTREAM\r\n");
2539 else if (!(ap_conn
= get_stream(smartlist_get(args
, 0))))
2540 connection_printf_to_buf(conn
, "552 Unknown stream \"%s\"\r\n",
2541 (char*)smartlist_get(args
, 0));
2543 reason
= (uint8_t) tor_parse_ulong(smartlist_get(args
,1), 10, 0, 255,
2546 connection_printf_to_buf(conn
, "552 Unrecognized reason \"%s\"\r\n",
2547 (char*)smartlist_get(args
, 1));
2551 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2552 smartlist_free(args
);
2557 connection_mark_unattached_ap(ap_conn
, reason
);
2558 send_control_done(conn
);
2562 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
2563 * and report success or failure. */
2565 handle_control_closecircuit(control_connection_t
*conn
, uint32_t len
,
2568 origin_circuit_t
*circ
= NULL
;
2571 if (STATE_IS_V0(conn
->_base
.state
)) {
2574 send_control0_error(conn
, ERR_SYNTAX
, "closecircuit message too short");
2577 circ_id
= ntohl(get_uint32(body
));
2578 safe
= (*(uint8_t*)(body
+4)) & 1;
2580 if (!(circ
= circuit_get_by_global_id(circ_id
))) {
2581 send_control0_error(conn
, ERR_NO_CIRC
,
2582 "No circuit found with given ID");
2587 args
= smartlist_create();
2588 smartlist_split_string(args
, body
, " ",
2589 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2590 if (smartlist_len(args
)<1)
2591 connection_printf_to_buf(conn
,
2592 "512 Missing argument to CLOSECIRCUIT\r\n");
2593 else if (!(circ
=get_circ(smartlist_get(args
, 0))))
2594 connection_printf_to_buf(conn
, "552 Unknown circuit \"%s\"\r\n",
2595 (char*)smartlist_get(args
, 0));
2598 for (i
=1; i
< smartlist_len(args
); ++i
) {
2599 if (!strcasecmp(smartlist_get(args
, i
), "IfUnused"))
2602 log_info(LD_CONTROL
, "Skipping unknown option %s",
2603 (char*)smartlist_get(args
,i
));
2606 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2607 smartlist_free(args
);
2612 if (!safe
|| !circ
->p_streams
) {
2613 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_REQUESTED
);
2616 send_control_done(conn
);
2620 /** Called when we get a USEFEATURE command: parse the feature list, and
2621 * set up the control_connection's options properly. */
2623 handle_control_usefeature(control_connection_t
*conn
,
2628 int verbose_names
= 0, extended_events
= 0;
2630 (void) len
; /* body is nul-terminated; it's safe to ignore the length */
2631 tor_assert(! STATE_IS_V0(conn
->_base
.state
));
2632 args
= smartlist_create();
2633 smartlist_split_string(args
, body
, " ",
2634 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2635 SMARTLIST_FOREACH(args
, const char *, arg
, {
2636 if (!strcasecmp(arg
, "VERBOSE_NAMES"))
2638 else if (!strcasecmp(arg
, "EXTENDED_EVENTS")) /* <- documented */
2639 extended_events
= 1;
2640 else if (!strcasecmp(arg
, "EXTENDED_FORMAT")) {
2641 /* remove this in 0.1.2.4; EXTENDED_FORMAT only ever worked for a
2642 * little while during 0.1.2.2-alpha-dev. */
2643 log_warn(LD_GENERAL
,
2644 "EXTENDED_FORMAT is deprecated; use EXTENDED_EVENTS "
2646 extended_events
= 1;
2648 connection_printf_to_buf(conn
, "552 Unrecognized feature \"%s\"\r\n",
2656 if (verbose_names
) {
2657 conn
->use_long_names
= 1;
2658 control_update_global_event_mask();
2660 if (extended_events
)
2661 conn
->use_extended_events
= 1;
2662 send_control_done(conn
);
2665 SMARTLIST_FOREACH(args
, char *, cp
, tor_free(cp
));
2666 smartlist_free(args
);
2670 /** Called when we get a v0 FRAGMENTHEADER or FRAGMENT command; try to append
2671 * the data to conn->incoming_cmd, setting conn->incoming_(type|len|cur_len)
2672 * as appropriate. If the command is malformed, drop it and all pending
2673 * fragments and report failure.
2676 handle_control_fragments(control_connection_t
*conn
, uint16_t command_type
,
2677 uint32_t body_len
, const char *body
)
2679 if (command_type
== CONTROL0_CMD_FRAGMENTHEADER
) {
2680 if (conn
->incoming_cmd
) {
2681 log_warn(LD_CONTROL
, "Dropping incomplete fragmented command; new "
2682 "fragmented command was begun.");
2683 tor_free(conn
->incoming_cmd
);
2686 send_control0_error(conn
, ERR_SYNTAX
, "FRAGMENTHEADER too short.");
2689 conn
->incoming_cmd_type
= ntohs(get_uint16(body
));
2690 conn
->incoming_cmd_len
= ntohl(get_uint32(body
+2));
2691 conn
->incoming_cmd_cur_len
= 0;
2692 conn
->incoming_cmd
= tor_malloc(conn
->incoming_cmd_len
);
2695 } else if (command_type
== CONTROL0_CMD_FRAGMENT
) {
2696 if (!conn
->incoming_cmd
) {
2697 send_control0_error(conn
, ERR_SYNTAX
, "Out-of-place FRAGMENT");
2704 if (conn
->incoming_cmd_cur_len
+ body_len
> conn
->incoming_cmd_len
) {
2705 tor_free(conn
->incoming_cmd
);
2706 send_control0_error(conn
, ERR_SYNTAX
,
2707 "Fragmented data exceeds declared length");
2710 memcpy(conn
->incoming_cmd
+ conn
->incoming_cmd_cur_len
,
2712 conn
->incoming_cmd_cur_len
+= body_len
;
2716 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
2718 connection_control_finished_flushing(control_connection_t
*conn
)
2722 connection_stop_writing(TO_CONN(conn
));
2726 /** Called when <b>conn</b> has gotten its socket closed. */
2728 connection_control_reached_eof(control_connection_t
*conn
)
2732 log_info(LD_CONTROL
,"Control connection reached EOF. Closing.");
2733 connection_mark_for_close(TO_CONN(conn
));
2737 /** Called when data has arrived on a v1 control connection: Try to fetch
2738 * commands from conn->inbuf, and execute them.
2741 connection_control_process_inbuf_v1(control_connection_t
*conn
)
2748 tor_assert(conn
->_base
.state
== CONTROL_CONN_STATE_OPEN_V1
||
2749 conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH_V1
);
2751 if (!conn
->incoming_cmd
) {
2752 conn
->incoming_cmd
= tor_malloc(1024);
2753 conn
->incoming_cmd_len
= 1024;
2754 conn
->incoming_cmd_cur_len
= 0;
2761 /* First, fetch a line. */
2763 data_len
= conn
->incoming_cmd_len
- conn
->incoming_cmd_cur_len
;
2764 r
= fetch_from_buf_line(conn
->_base
.inbuf
,
2765 conn
->incoming_cmd
+conn
->incoming_cmd_cur_len
,
2768 /* Line not all here yet. Wait. */
2771 while (conn
->incoming_cmd_len
< data_len
+conn
->incoming_cmd_cur_len
)
2772 conn
->incoming_cmd_len
*= 2;
2773 conn
->incoming_cmd
= tor_realloc(conn
->incoming_cmd
,
2774 conn
->incoming_cmd_len
);
2778 tor_assert(data_len
);
2780 last_idx
= conn
->incoming_cmd_cur_len
;
2781 conn
->incoming_cmd_cur_len
+= data_len
;
2783 /* We have appended a line to incoming_cmd. Is the command done? */
2784 if (last_idx
== 0 && *conn
->incoming_cmd
!= '+')
2785 /* One line command, didn't start with '+'. */
2787 if (last_idx
+3 == conn
->incoming_cmd_cur_len
&&
2788 !memcmp(conn
->incoming_cmd
+ last_idx
, ".\r\n", 3)) {
2789 /* Just appended ".\r\n"; we're done. Remove it. */
2790 conn
->incoming_cmd_cur_len
-= 3;
2793 /* Otherwise, read another line. */
2795 data_len
= conn
->incoming_cmd_cur_len
;
2796 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
2800 while ((size_t)cmd_len
< data_len
2801 && !TOR_ISSPACE(conn
->incoming_cmd
[cmd_len
]))
2804 data_len
-= cmd_len
;
2805 conn
->incoming_cmd
[cmd_len
]='\0';
2806 args
= conn
->incoming_cmd
+cmd_len
+1;
2807 while (*args
== ' ' || *args
== '\t') {
2812 if (!strcasecmp(conn
->incoming_cmd
, "QUIT")) {
2813 connection_write_str_to_buf("250 closing connection\r\n", conn
);
2814 connection_mark_for_close(TO_CONN(conn
));
2818 if (conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH_V1
&&
2819 strcasecmp(conn
->incoming_cmd
, "AUTHENTICATE")) {
2820 connection_write_str_to_buf("514 Authentication required.\r\n", conn
);
2821 conn
->incoming_cmd_cur_len
= 0;
2825 if (!strcasecmp(conn
->incoming_cmd
, "SETCONF")) {
2826 if (handle_control_setconf(conn
, data_len
, args
))
2828 } else if (!strcasecmp(conn
->incoming_cmd
, "RESETCONF")) {
2829 if (handle_control_resetconf(conn
, data_len
, args
))
2831 } else if (!strcasecmp(conn
->incoming_cmd
, "GETCONF")) {
2832 if (handle_control_getconf(conn
, data_len
, args
))
2834 } else if (!strcasecmp(conn
->incoming_cmd
, "SETEVENTS")) {
2835 if (handle_control_setevents(conn
, data_len
, args
))
2837 } else if (!strcasecmp(conn
->incoming_cmd
, "AUTHENTICATE")) {
2838 if (handle_control_authenticate(conn
, data_len
, args
))
2840 } else if (!strcasecmp(conn
->incoming_cmd
, "SAVECONF")) {
2841 if (handle_control_saveconf(conn
, data_len
, args
))
2843 } else if (!strcasecmp(conn
->incoming_cmd
, "SIGNAL")) {
2844 if (handle_control_signal(conn
, data_len
, args
))
2846 } else if (!strcasecmp(conn
->incoming_cmd
, "MAPADDRESS")) {
2847 if (handle_control_mapaddress(conn
, data_len
, args
))
2849 } else if (!strcasecmp(conn
->incoming_cmd
, "GETINFO")) {
2850 if (handle_control_getinfo(conn
, data_len
, args
))
2852 } else if (!strcasecmp(conn
->incoming_cmd
, "EXTENDCIRCUIT")) {
2853 if (handle_control_extendcircuit(conn
, data_len
, args
))
2855 } else if (!strcasecmp(conn
->incoming_cmd
, "SETCIRCUITPURPOSE")) {
2856 if (handle_control_setpurpose(conn
, 1, data_len
, args
))
2858 } else if (!strcasecmp(conn
->incoming_cmd
, "SETROUTERPURPOSE")) {
2859 if (handle_control_setpurpose(conn
, 0, data_len
, args
))
2861 } else if (!strcasecmp(conn
->incoming_cmd
, "ATTACHSTREAM")) {
2862 if (handle_control_attachstream(conn
, data_len
, args
))
2864 } else if (!strcasecmp(conn
->incoming_cmd
, "+POSTDESCRIPTOR")) {
2865 if (handle_control_postdescriptor(conn
, data_len
, args
))
2867 } else if (!strcasecmp(conn
->incoming_cmd
, "REDIRECTSTREAM")) {
2868 if (handle_control_redirectstream(conn
, data_len
, args
))
2870 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSESTREAM")) {
2871 if (handle_control_closestream(conn
, data_len
, args
))
2873 } else if (!strcasecmp(conn
->incoming_cmd
, "CLOSECIRCUIT")) {
2874 if (handle_control_closecircuit(conn
, data_len
, args
))
2876 } else if (!strcasecmp(conn
->incoming_cmd
, "USEFEATURE")) {
2877 if (handle_control_usefeature(conn
, data_len
, args
))
2880 connection_printf_to_buf(conn
, "510 Unrecognized command \"%s\"\r\n",
2881 conn
->incoming_cmd
);
2884 conn
->incoming_cmd_cur_len
= 0;
2888 /** Called when data has arrived on a v0 control connection: Try to fetch
2889 * commands from conn->inbuf, and execute them.
2892 connection_control_process_inbuf_v0(control_connection_t
*conn
)
2895 uint16_t command_type
;
2897 static int have_warned_about_v0_protocol
= 0;
2900 /* Try to suck a control message from the buffer. */
2901 switch (fetch_from_buf_control0(conn
->_base
.inbuf
, &body_len
, &command_type
,
2903 conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH_V0
))
2907 log_info(LD_CONTROL
,
2908 "Detected v1 control protocol on connection (fd %d)",
2910 conn
->_base
.state
= CONTROL_CONN_STATE_NEEDAUTH_V1
;
2911 return connection_control_process_inbuf_v1(conn
);
2914 log_warn(LD_CONTROL
, "Error in control command. Failing.");
2917 /* Control command not all here yet. Wait. */
2920 /* We got a command. Process it. */
2926 if (!have_warned_about_v0_protocol
) {
2927 log_warn(LD_CONTROL
, "An application has connected to us using the "
2928 "version 0 control prototol, which has been deprecated since "
2929 "Tor 0.1.1.1-alpha. This protocol will not be supported by "
2930 "future versions of Tor; please use the v1 control protocol "
2932 have_warned_about_v0_protocol
= 1;
2935 /* We got a command. If we need authentication, only authentication
2936 * commands will be considered. */
2937 if (conn
->_base
.state
== CONTROL_CONN_STATE_NEEDAUTH_V0
&&
2938 command_type
!= CONTROL0_CMD_AUTHENTICATE
) {
2939 log_info(LD_CONTROL
, "Rejecting '%s' command; authentication needed.",
2940 control_cmd_to_string(command_type
));
2941 send_control0_error(conn
, ERR_UNAUTHORIZED
, "Authentication required");
2946 if (command_type
== CONTROL0_CMD_FRAGMENTHEADER
||
2947 command_type
== CONTROL0_CMD_FRAGMENT
) {
2948 if (handle_control_fragments(conn
, command_type
, body_len
, body
))
2951 if (conn
->incoming_cmd_cur_len
!= conn
->incoming_cmd_len
)
2954 command_type
= conn
->incoming_cmd_type
;
2955 body_len
= conn
->incoming_cmd_len
;
2956 body
= conn
->incoming_cmd
;
2957 conn
->incoming_cmd
= NULL
;
2958 } else if (conn
->incoming_cmd
) {
2959 log_warn(LD_CONTROL
, "Dropping incomplete fragmented command");
2960 tor_free(conn
->incoming_cmd
);
2963 /* Okay, we're willing to process the command. */
2964 switch (command_type
)
2966 case CONTROL0_CMD_SETCONF
:
2967 if (handle_control_setconf(conn
, body_len
, body
))
2970 case CONTROL0_CMD_GETCONF
:
2971 if (handle_control_getconf(conn
, body_len
, body
))
2974 case CONTROL0_CMD_SETEVENTS
:
2975 if (handle_control_setevents(conn
, body_len
, body
))
2978 case CONTROL0_CMD_AUTHENTICATE
:
2979 if (handle_control_authenticate(conn
, body_len
, body
))
2982 case CONTROL0_CMD_SAVECONF
:
2983 if (handle_control_saveconf(conn
, body_len
, body
))
2986 case CONTROL0_CMD_SIGNAL
:
2987 if (handle_control_signal(conn
, body_len
, body
))
2990 case CONTROL0_CMD_MAPADDRESS
:
2991 if (handle_control_mapaddress(conn
, body_len
, body
))
2994 case CONTROL0_CMD_GETINFO
:
2995 if (handle_control_getinfo(conn
, body_len
, body
))
2998 case CONTROL0_CMD_EXTENDCIRCUIT
:
2999 if (handle_control_extendcircuit(conn
, body_len
, body
))
3002 case CONTROL0_CMD_ATTACHSTREAM
:
3003 if (handle_control_attachstream(conn
, body_len
, body
))
3006 case CONTROL0_CMD_POSTDESCRIPTOR
:
3007 if (handle_control_postdescriptor(conn
, body_len
, body
))
3010 case CONTROL0_CMD_REDIRECTSTREAM
:
3011 if (handle_control_redirectstream(conn
, body_len
, body
))
3014 case CONTROL0_CMD_CLOSESTREAM
:
3015 if (handle_control_closestream(conn
, body_len
, body
))
3018 case CONTROL0_CMD_CLOSECIRCUIT
:
3019 if (handle_control_closecircuit(conn
, body_len
, body
))
3022 case CONTROL0_CMD_ERROR
:
3023 case CONTROL0_CMD_DONE
:
3024 case CONTROL0_CMD_CONFVALUE
:
3025 case CONTROL0_CMD_EVENT
:
3026 case CONTROL0_CMD_INFOVALUE
:
3027 log_warn(LD_CONTROL
, "Received client-only '%s' command; ignoring.",
3028 control_cmd_to_string(command_type
));
3029 send_control0_error(conn
, ERR_UNRECOGNIZED_TYPE
,
3030 "Command type only valid from server to tor client");
3032 case CONTROL0_CMD_FRAGMENTHEADER
:
3033 case CONTROL0_CMD_FRAGMENT
:
3034 log_warn(LD_CONTROL
,
3035 "Recieved command fragment out of order; ignoring.");
3036 send_control0_error(conn
, ERR_SYNTAX
, "Bad fragmentation on command.");
3038 log_warn(LD_CONTROL
, "Received unrecognized command type %d; ignoring.",
3040 send_control0_error(conn
, ERR_UNRECOGNIZED_TYPE
,
3041 "Unrecognized command type");
3045 goto again
; /* There might be more data. */
3048 /** Called when <b>conn</b> has received more bytes on its inbuf.
3051 connection_control_process_inbuf(control_connection_t
*conn
)
3055 if (STATE_IS_V0(conn
->_base
.state
))
3056 return connection_control_process_inbuf_v0(conn
);
3058 return connection_control_process_inbuf_v1(conn
);
3061 /** Convert a numeric reason for destroying a circuit into a string for a
3064 circuit_end_reason_to_string(int reason
)
3066 if (reason
>= 0 && reason
& END_CIRC_REASON_FLAG_REMOTE
)
3067 reason
&= ~END_CIRC_REASON_FLAG_REMOTE
;
3069 case END_CIRC_AT_ORIGIN
:
3070 /* This shouldn't get passed here; it's a catch-all reason. */
3072 case END_CIRC_REASON_NONE
:
3073 /* This shouldn't get passed here; it's a catch-all reason. */
3075 case END_CIRC_REASON_TORPROTOCOL
:
3076 return "TORPROTOCOL";
3077 case END_CIRC_REASON_INTERNAL
:
3079 case END_CIRC_REASON_REQUESTED
:
3081 case END_CIRC_REASON_HIBERNATING
:
3082 return "HIBERNATING";
3083 case END_CIRC_REASON_RESOURCELIMIT
:
3084 return "RESOURCELIMIT";
3085 case END_CIRC_REASON_CONNECTFAILED
:
3086 return "CONNECTFAILED";
3087 case END_CIRC_REASON_OR_IDENTITY
:
3088 return "OR_IDENTITY";
3089 case END_CIRC_REASON_OR_CONN_CLOSED
:
3090 return "OR_CONN_CLOSED";
3091 case END_CIRC_REASON_FINISHED
:
3093 case END_CIRC_REASON_TIMEOUT
:
3095 case END_CIRC_REASON_DESTROYED
:
3097 case END_CIRC_REASON_NOPATH
:
3099 case END_CIRC_REASON_NOSUCHSERVICE
:
3100 return "NOSUCHSERVICE";
3102 log_warn(LD_BUG
, "Unrecognized reason code %d", (int)reason
);
3107 /** Something has happened to circuit <b>circ</b>: tell any interested
3108 * control connections. */
3110 control_event_circuit_status(origin_circuit_t
*circ
, circuit_status_event_t tp
,
3113 char *path
=NULL
, *msg
;
3114 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS
))
3118 if (EVENT_IS_INTERESTING0(EVENT_CIRCUIT_STATUS
) ||
3119 EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS
))
3120 path
= circuit_list_path(circ
,0);
3121 if (EVENT_IS_INTERESTING0(EVENT_CIRCUIT_STATUS
)) {
3122 size_t path_len
= strlen(path
);
3123 msg
= tor_malloc(1+4+path_len
+1); /* event, circid, path, NUL. */
3124 msg
[0] = (uint8_t) tp
;
3125 set_uint32(msg
+1, htonl(circ
->global_identifier
));
3126 strlcpy(msg
+5,path
,path_len
+1);
3128 send_control0_event(EVENT_CIRCUIT_STATUS
, (uint32_t)(path_len
+6), msg
);
3131 if (EVENT_IS_INTERESTING1(EVENT_CIRCUIT_STATUS
)) {
3133 char reason_buf
[64];
3134 int providing_reason
=0;
3137 case CIRC_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
3138 case CIRC_EVENT_BUILT
: status
= "BUILT"; break;
3139 case CIRC_EVENT_EXTENDED
: status
= "EXTENDED"; break;
3140 case CIRC_EVENT_FAILED
: status
= "FAILED"; break;
3141 case CIRC_EVENT_CLOSED
: status
= "CLOSED"; break;
3143 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3147 if (tp
== CIRC_EVENT_FAILED
|| tp
== CIRC_EVENT_CLOSED
) {
3148 const char *reason_str
= circuit_end_reason_to_string(reason_code
);
3149 char *reason
= NULL
;
3152 reason
= tor_malloc(16);
3153 tor_snprintf(reason
, 16, "UNKNOWN_%d", reason_code
);
3154 reason_str
= reason
;
3156 if (reason_code
> 0 && reason_code
& END_CIRC_REASON_FLAG_REMOTE
) {
3157 tor_snprintf(reason_buf
, sizeof(reason_buf
),
3158 "REASON=DESTROYED REMOTE_REASON=%s", reason_str
);
3160 tor_snprintf(reason_buf
, sizeof(reason_buf
),
3161 "REASON=%s", reason_str
);
3166 if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS
)) {
3167 const char *sp
= strlen(path
) ? " " : "";
3168 if (providing_reason
)
3169 send_control1_event_extended(EVENT_CIRCUIT_STATUS
, SHORT_NAMES
,
3170 "650 CIRC %lu %s%s%s@%s\r\n",
3171 (unsigned long)circ
->global_identifier
,
3172 status
, sp
, path
, reason_buf
);
3174 send_control1_event_extended(EVENT_CIRCUIT_STATUS
, SHORT_NAMES
,
3175 "650 CIRC %lu %s%s%s\r\n",
3176 (unsigned long)circ
->global_identifier
,
3179 if (EVENT_IS_INTERESTING1L(EVENT_CIRCUIT_STATUS
)) {
3180 char *vpath
= circuit_list_path_for_controller(circ
);
3181 const char *sp
= strlen(vpath
) ? " " : "";
3182 if (providing_reason
)
3183 send_control1_event_extended(EVENT_CIRCUIT_STATUS
, LONG_NAMES
,
3184 "650 CIRC %lu %s%s%s@%s\r\n",
3185 (unsigned long)circ
->global_identifier
,
3186 status
, sp
, vpath
, reason_buf
);
3188 send_control1_event_extended(EVENT_CIRCUIT_STATUS
, LONG_NAMES
,
3189 "650 CIRC %lu %s%s%s\r\n",
3190 (unsigned long)circ
->global_identifier
,
3200 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
3201 * <b>buf</b>, determine the address:port combination requested on
3202 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
3205 write_stream_target_to_buf(edge_connection_t
*conn
, char *buf
, size_t len
)
3208 if (conn
->chosen_exit_name
)
3209 if (tor_snprintf(buf2
, sizeof(buf2
), ".%s.exit", conn
->chosen_exit_name
)<0)
3211 if (tor_snprintf(buf
, len
, "%s%s%s:%d",
3212 conn
->socks_request
->address
,
3213 conn
->chosen_exit_name
? buf2
: "",
3214 !conn
->chosen_exit_name
&&
3215 connection_edge_is_rendezvous_stream(conn
) ? ".onion" : "",
3216 conn
->socks_request
->port
)<0)
3221 /** Convert the reason for ending a stream <b>reason</b> into the format used
3222 * in STREAM events. Return NULL if the reason is unrecognized. */
3224 stream_end_reason_to_string(int reason
)
3226 reason
&= END_STREAM_REASON_MASK
;
3228 case END_STREAM_REASON_MISC
: return "MISC";
3229 case END_STREAM_REASON_RESOLVEFAILED
: return "RESOLVEFAILED";
3230 case END_STREAM_REASON_CONNECTREFUSED
: return "CONNECTREFUSED";
3231 case END_STREAM_REASON_EXITPOLICY
: return "EXITPOLICY";
3232 case END_STREAM_REASON_DESTROY
: return "DESTROY";
3233 case END_STREAM_REASON_DONE
: return "DONE";
3234 case END_STREAM_REASON_TIMEOUT
: return "TIMEOUT";
3235 case END_STREAM_REASON_HIBERNATING
: return "HIBERNATING";
3236 case END_STREAM_REASON_INTERNAL
: return "INTERNAL";
3237 case END_STREAM_REASON_RESOURCELIMIT
: return "RESOURCELIMIT";
3238 case END_STREAM_REASON_CONNRESET
: return "CONNRESET";
3239 case END_STREAM_REASON_TORPROTOCOL
: return "TORPROTOCOL";
3240 case END_STREAM_REASON_NOTDIRECTORY
: return "NOTDIRECTORY";
3242 case END_STREAM_REASON_CANT_ATTACH
: return "CANT_ATTACH";
3243 case END_STREAM_REASON_NET_UNREACHABLE
: return "NET_UNREACHABLE";
3244 case END_STREAM_REASON_SOCKSPROTOCOL
: return "SOCKS_PROTOCOL";
3246 default: return NULL
;
3250 /** Something has happened to the stream associated with AP connection
3251 * <b>conn</b>: tell any interested control connections. */
3253 control_event_stream_status(edge_connection_t
*conn
, stream_status_event_t tp
,
3259 tor_assert(conn
->socks_request
);
3261 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS
))
3264 if (tp
== STREAM_EVENT_CLOSED
&&
3265 (reason_code
& END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
))
3268 write_stream_target_to_buf(conn
, buf
, sizeof(buf
));
3269 if (EVENT_IS_INTERESTING0(EVENT_STREAM_STATUS
)) {
3271 msg
= tor_malloc(5+len
+1);
3272 msg
[0] = (uint8_t) tp
;
3273 set_uint32(msg
+1, htonl(conn
->global_identifier
));
3274 strlcpy(msg
+5, buf
, len
+1);
3276 send_control0_event(EVENT_STREAM_STATUS
, (uint32_t)(5+len
+1), msg
);
3279 if (EVENT_IS_INTERESTING1(EVENT_STREAM_STATUS
)) {
3280 char reason_buf
[64];
3283 origin_circuit_t
*origin_circ
= NULL
;
3284 reason_buf
[0] = '\0';
3287 case STREAM_EVENT_SENT_CONNECT
: status
= "SENTCONNECT"; break;
3288 case STREAM_EVENT_SENT_RESOLVE
: status
= "SENTRESOLVE"; break;
3289 case STREAM_EVENT_SUCCEEDED
: status
= "SUCCEEDED"; break;
3290 case STREAM_EVENT_FAILED
: status
= "FAILED"; break;
3291 case STREAM_EVENT_CLOSED
: status
= "CLOSED"; break;
3292 case STREAM_EVENT_NEW
: status
= "NEW"; break;
3293 case STREAM_EVENT_NEW_RESOLVE
: status
= "NEWRESOLVE"; break;
3294 case STREAM_EVENT_FAILED_RETRIABLE
: status
= "DETACHED"; break;
3295 case STREAM_EVENT_REMAP
: status
= "REMAP"; break;
3297 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3300 if (reason_code
&& (tp
== STREAM_EVENT_FAILED
||
3301 tp
== STREAM_EVENT_CLOSED
||
3302 tp
== STREAM_EVENT_FAILED_RETRIABLE
)) {
3303 const char *reason_str
= stream_end_reason_to_string(reason_code
);
3307 tor_snprintf(r
, 16, "UNKNOWN_%d", reason_code
);
3310 if (reason_code
& END_STREAM_REASON_FLAG_REMOTE
)
3311 tor_snprintf(reason_buf
, sizeof(reason_buf
),
3312 "REASON=END REMOTE_REASON=%s", reason_str
);
3314 tor_snprintf(reason_buf
, sizeof(reason_buf
),
3315 "REASON=%s", reason_str
);
3317 } else if (reason_code
&& tp
== STREAM_EVENT_REMAP
) {
3318 switch (reason_code
) {
3319 case REMAP_STREAM_SOURCE_CACHE
:
3320 strlcpy(reason_buf
, "SOURCE=CACHE", sizeof(reason_buf
));
3322 case REMAP_STREAM_SOURCE_EXIT
:
3323 strlcpy(reason_buf
, "SOURCE=EXIT", sizeof(reason_buf
));
3326 tor_snprintf(reason_buf
, sizeof(reason_buf
), "REASON=UNKNOWN_%d",
3331 circ
= circuit_get_by_edge_conn(conn
);
3332 if (circ
&& CIRCUIT_IS_ORIGIN(circ
))
3333 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
3334 send_control1_event_extended(EVENT_STREAM_STATUS
, ALL_NAMES
,
3335 "650 STREAM %lu %s %lu %s@%s\r\n",
3336 (unsigned long)conn
->global_identifier
, status
,
3338 (unsigned long)origin_circ
->global_identifier
: 0ul,
3340 /* XXX need to specify its intended exit, etc? */
3345 /** Figure out the best name for the target router of an OR connection
3346 * <b>conn</b>, and write it into the <b>len</b>-character buffer
3347 * <b>name</b>. Use verbose names if <b>long_names</b> is set. */
3349 orconn_target_get_name(int long_names
,
3350 char *name
, size_t len
, or_connection_t
*conn
)
3354 strlcpy(name
, conn
->nickname
, len
);
3356 tor_snprintf(name
, len
, "%s:%d",
3357 conn
->_base
.address
, conn
->_base
.port
);
3359 routerinfo_t
*ri
= router_get_by_digest(conn
->identity_digest
);
3361 tor_assert(len
> MAX_VERBOSE_NICKNAME_LEN
);
3362 router_get_verbose_nickname(name
, ri
);
3363 } else if (! tor_digest_is_zero(conn
->identity_digest
)) {
3365 base16_encode(name
+1, len
-1, conn
->identity_digest
,
3368 tor_snprintf(name
, len
, "%s:%d",
3369 conn
->_base
.address
, conn
->_base
.port
);
3374 /** Convert a TOR_TLS_* error code into an END_OR_CONN_* reason. */
3376 control_tls_error_to_reason(int e
)
3379 case TOR_TLS_ERROR_IO
:
3380 return END_OR_CONN_REASON_TLS_IO_ERROR
;
3381 case TOR_TLS_ERROR_CONNREFUSED
:
3382 return END_OR_CONN_REASON_TCP_REFUSED
;
3383 case TOR_TLS_ERROR_CONNRESET
:
3384 return END_OR_CONN_REASON_TLS_CONNRESET
;
3385 case TOR_TLS_ERROR_NO_ROUTE
:
3386 return END_OR_CONN_REASON_TLS_NO_ROUTE
;
3387 case TOR_TLS_ERROR_TIMEOUT
:
3388 return END_OR_CONN_REASON_TLS_TIMEOUT
;
3389 case TOR_TLS_WANTREAD
:
3390 case TOR_TLS_WANTWRITE
:
3393 return END_OR_CONN_REASON_DONE
;
3395 return END_OR_CONN_REASON_TLS_MISC
;
3399 /** Convert the reason for ending an OR connection <b>r</b> into the format
3400 * used in ORCONN events. Return NULL if the reason is unrecognized. */
3402 or_conn_end_reason_to_string(int r
)
3405 case END_OR_CONN_REASON_DONE
:
3406 return "REASON=DONE";
3407 case END_OR_CONN_REASON_TCP_REFUSED
:
3408 return "REASON=CONNECTREFUSED";
3409 case END_OR_CONN_REASON_OR_IDENTITY
:
3410 return "REASON=IDENTITY";
3411 case END_OR_CONN_REASON_TLS_CONNRESET
:
3412 return "REASON=CONNECTRESET";
3413 case END_OR_CONN_REASON_TLS_TIMEOUT
:
3414 return "REASON=TIMEOUT";
3415 case END_OR_CONN_REASON_TLS_NO_ROUTE
:
3416 return "REASON=NOROUTE";
3417 case END_OR_CONN_REASON_TLS_IO_ERROR
:
3418 return "REASON=IOERROR";
3419 case END_OR_CONN_REASON_TLS_MISC
:
3420 return "REASON=MISC";
3424 log_warn(LD_BUG
, "Unrecognized or_conn reason code %d", r
);
3425 return "REASON=BOGUS";
3429 /** Called when the status of an OR connection <b>conn</b> changes: tell any
3430 * interested control connections. <b>tp</b> is the new status for the
3431 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
3432 * may be the reason why.
3435 control_event_or_conn_status(or_connection_t
*conn
, or_conn_status_event_t tp
,
3438 char buf
[HEX_DIGEST_LEN
+3]; /* status, dollar, identity, NUL */
3442 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS
))
3445 if (EVENT_IS_INTERESTING0(EVENT_OR_CONN_STATUS
)) {
3446 buf
[0] = (uint8_t)tp
;
3447 strlcpy(buf
+1,conn
->nickname
? conn
->nickname
: "",sizeof(buf
)-1);
3448 len
= strlen(buf
+1);
3449 send_control0_event(EVENT_OR_CONN_STATUS
, (uint32_t)(len
+1), buf
);
3451 if (EVENT_IS_INTERESTING1(EVENT_OR_CONN_STATUS
)) {
3454 char ncircs_buf
[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
3457 case OR_CONN_EVENT_LAUNCHED
: status
= "LAUNCHED"; break;
3458 case OR_CONN_EVENT_CONNECTED
: status
= "CONNECTED"; break;
3459 case OR_CONN_EVENT_FAILED
: status
= "FAILED"; break;
3460 case OR_CONN_EVENT_CLOSED
: status
= "CLOSED"; break;
3461 case OR_CONN_EVENT_NEW
: status
= "NEW"; break;
3463 log_warn(LD_BUG
, "Unrecognized status code %d", (int)tp
);
3466 ncircs
= circuit_count_pending_on_or_conn(conn
);
3467 ncircs
+= conn
->n_circuits
;
3468 if (ncircs
&& (tp
== OR_CONN_EVENT_FAILED
|| tp
== OR_CONN_EVENT_CLOSED
)) {
3469 tor_snprintf(ncircs_buf
, sizeof(ncircs_buf
), "%sNCIRCS=%d",
3470 reason
? " " : "", ncircs
);
3473 if (EVENT_IS_INTERESTING1S(EVENT_OR_CONN_STATUS
)) {
3474 orconn_target_get_name(0, name
, sizeof(name
), conn
);
3475 send_control1_event_extended(EVENT_OR_CONN_STATUS
, SHORT_NAMES
,
3476 "650 ORCONN %s %s@%s%s\r\n",
3478 or_conn_end_reason_to_string(reason
), ncircs_buf
);
3480 if (EVENT_IS_INTERESTING1L(EVENT_OR_CONN_STATUS
)) {
3481 orconn_target_get_name(1, name
, sizeof(name
), conn
);
3482 send_control1_event_extended(EVENT_OR_CONN_STATUS
, LONG_NAMES
,
3483 "650 ORCONN %s %s@%s%s\r\n",
3485 or_conn_end_reason_to_string(reason
), ncircs_buf
);
3491 /** A second or more has elapsed: tell any interested control
3492 * connections how much bandwidth streams have used. */
3494 control_event_stream_bandwidth_used(void)
3496 connection_t
**carray
;
3497 edge_connection_t
*conn
;
3500 if (EVENT_IS_INTERESTING1(EVENT_STREAM_BANDWIDTH_USED
)) {
3502 get_connection_array(&carray
, &n
);
3504 for (i
= 0; i
< n
; ++i
) {
3505 if (carray
[i
]->type
!= CONN_TYPE_AP
)
3507 conn
= TO_EDGE_CONN(carray
[i
]);
3508 if (!conn
->n_read
&& !conn
->n_written
)
3511 send_control1_event(EVENT_STREAM_BANDWIDTH_USED
, ALL_NAMES
,
3512 "650 STREAM_BW %lu %lu %lu\r\n",
3513 (unsigned long)conn
->global_identifier
,
3514 (unsigned long)conn
->n_read
,
3515 (unsigned long)conn
->n_written
);
3517 conn
->n_written
= conn
->n_read
= 0;
3524 /** A second or more has elapsed: tell any interested control
3525 * connections how much bandwidth we used. */
3527 control_event_bandwidth_used(uint32_t n_read
, uint32_t n_written
)
3531 if (EVENT_IS_INTERESTING0(EVENT_BANDWIDTH_USED
)) {
3532 set_uint32(buf
, htonl(n_read
));
3533 set_uint32(buf
+4, htonl(n_written
));
3534 send_control0_event(EVENT_BANDWIDTH_USED
, 8, buf
);
3536 if (EVENT_IS_INTERESTING1(EVENT_BANDWIDTH_USED
)) {
3537 send_control1_event(EVENT_BANDWIDTH_USED
, ALL_NAMES
,
3538 "650 BW %lu %lu\r\n",
3539 (unsigned long)n_read
,
3540 (unsigned long)n_written
);
3546 /** Called when we are sending a log message to the controllers: suspend
3547 * sending further log messages to the controllers until we're done. Used by
3548 * CONN_LOG_PROTECT. */
3550 disable_control_logging(void)
3552 ++disable_log_messages
;
3555 /** We're done sending a log message to the controllers: re-enable controller
3556 * logging. Used by CONN_LOG_PROTECT. */
3558 enable_control_logging(void)
3560 if (--disable_log_messages
< 0)
3564 /** We got a log message: tell any interested control connections. */
3566 control_event_logmsg(int severity
, uint32_t domain
, const char *msg
)
3570 if (disable_log_messages
)
3573 if (domain
== LD_BUG
&& EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL
) &&
3574 severity
<= LOG_NOTICE
) {
3575 char *esc
= esc_for_log(msg
);
3576 ++disable_log_messages
;
3577 control_event_general_status(severity
, "BUG REASON=\"%s\"", esc
);
3578 --disable_log_messages
;
3582 oldlog
= EVENT_IS_INTERESTING0(EVENT_LOG_OBSOLETE
) &&
3583 (severity
== LOG_NOTICE
|| severity
== LOG_WARN
|| severity
== LOG_ERR
);
3584 event
= log_severity_to_event(severity
);
3586 if (event
<0 || !EVENT_IS_INTERESTING0(event
))
3589 if (oldlog
|| event
) {
3590 size_t len
= strlen(msg
);
3591 ++disable_log_messages
;
3593 send_control0_event(event
, (uint32_t)(len
+1), msg
);
3595 send_control0_event(EVENT_LOG_OBSOLETE
, (uint32_t)(len
+1), msg
);
3596 --disable_log_messages
;
3599 event
= log_severity_to_event(severity
);
3600 if (event
>= 0 && EVENT_IS_INTERESTING1(event
)) {
3603 if (strchr(msg
, '\n')) {
3605 b
= tor_strdup(msg
);
3606 for (cp
= b
; *cp
; ++cp
)
3607 if (*cp
== '\r' || *cp
== '\n')
3611 case LOG_DEBUG
: s
= "DEBUG"; break;
3612 case LOG_INFO
: s
= "INFO"; break;
3613 case LOG_NOTICE
: s
= "NOTICE"; break;
3614 case LOG_WARN
: s
= "WARN"; break;
3615 case LOG_ERR
: s
= "ERR"; break;
3616 default: s
= "UnknownLogSeverity"; break;
3618 ++disable_log_messages
;
3619 send_control1_event(event
, ALL_NAMES
, "650 %s %s\r\n", s
, b
?b
:msg
);
3620 --disable_log_messages
;
3625 /** Called whenever we receive new router descriptors: tell any
3626 * interested control connections. <b>routers</b> is a list of
3627 * DIGEST_LEN-byte identity digests.
3630 control_event_descriptors_changed(smartlist_t
*routers
)
3634 smartlist_t
*identities
= NULL
;
3635 char buf
[HEX_DIGEST_LEN
+1];
3637 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC
))
3639 if (EVENT_IS_INTERESTING0(EVENT_NEW_DESC
) ||
3640 EVENT_IS_INTERESTING1S(EVENT_NEW_DESC
)) {
3641 identities
= smartlist_create();
3642 SMARTLIST_FOREACH(routers
, routerinfo_t
*, r
,
3644 base16_encode(buf
,sizeof(buf
),r
->cache_info
.identity_digest
,DIGEST_LEN
);
3645 smartlist_add(identities
, tor_strdup(buf
));
3648 if (EVENT_IS_INTERESTING0(EVENT_NEW_DESC
)) {
3649 msg
= smartlist_join_strings(identities
, ",", 0, &len
);
3650 send_control0_event(EVENT_NEW_DESC
, len
+1, msg
);
3653 if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC
)) {
3654 char *ids
= smartlist_join_strings(identities
, " ", 0, &len
);
3655 size_t len
= strlen(ids
)+32;
3656 msg
= tor_malloc(len
);
3657 tor_snprintf(msg
, len
, "650 NEWDESC %s\r\n", ids
);
3658 send_control1_event_string(EVENT_NEW_DESC
, SHORT_NAMES
|ALL_FORMATS
, msg
);
3662 if (EVENT_IS_INTERESTING1L(EVENT_NEW_DESC
)) {
3663 smartlist_t
*names
= smartlist_create();
3666 SMARTLIST_FOREACH(routers
, routerinfo_t
*, ri
, {
3667 char *b
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
3668 router_get_verbose_nickname(b
, ri
);
3669 smartlist_add(names
, b
);
3671 ids
= smartlist_join_strings(names
, " ", 0, &len
);
3672 len
= strlen(ids
)+32;
3673 msg
= tor_malloc(len
);
3674 tor_snprintf(msg
, len
, "650 NEWDESC %s\r\n", ids
);
3675 send_control1_event_string(EVENT_NEW_DESC
, LONG_NAMES
|ALL_FORMATS
, msg
);
3678 SMARTLIST_FOREACH(names
, char *, cp
, tor_free(cp
));
3679 smartlist_free(names
);
3682 SMARTLIST_FOREACH(identities
, char *, cp
, tor_free(cp
));
3683 smartlist_free(identities
);
3688 /** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
3689 * <b>expires</b> values less than 3 are special; see connection_edge.c. */
3691 control_event_address_mapped(const char *from
, const char *to
, time_t expires
)
3693 if (!EVENT_IS_INTERESTING1(EVENT_ADDRMAP
))
3697 send_control1_event(EVENT_ADDRMAP
, ALL_NAMES
,
3698 "650 ADDRMAP %s %s NEVER\r\n", from
, to
);
3700 char buf
[ISO_TIME_LEN
+1];
3701 format_local_iso_time(buf
,expires
);
3702 send_control1_event(EVENT_ADDRMAP
, ALL_NAMES
,
3703 "650 ADDRMAP %s %s \"%s\"\r\n",
3710 /** The authoritative dirserver has received a new descriptor that
3711 * has passed basic syntax checks and is properly self-signed.
3713 * Notify any interested party of the new descriptor and what has
3714 * been done with it, and also optionally give an explanation/reason. */
3716 control_event_or_authdir_new_descriptor(const char *action
,
3717 const char *descriptor
,
3720 char firstline
[1024];
3726 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS
))
3729 tor_snprintf(firstline
, sizeof(firstline
),
3730 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
3734 /* Escape the server descriptor properly */
3735 esclen
= write_escaped_data(descriptor
, strlen(descriptor
), 1, &esc
);
3737 totallen
= strlen(firstline
) + esclen
+ 1;
3738 buf
= tor_malloc(totallen
);
3739 strlcpy(buf
, firstline
, totallen
);
3740 strlcpy(buf
+strlen(firstline
), esc
, totallen
);
3741 send_control1_event_string(EVENT_AUTHDIR_NEWDESCS
, ALL_NAMES
|ALL_FORMATS
,
3750 /** Called when the local_routerstatus_ts <b>statuses</b> have changed: sends
3751 * an NS event to any controller that cares. */
3753 control_event_networkstatus_changed(smartlist_t
*statuses
)
3757 if (!EVENT_IS_INTERESTING(EVENT_NS
) || !smartlist_len(statuses
))
3760 strs
= smartlist_create();
3761 smartlist_add(strs
, tor_strdup("650+NS\r\n"));
3762 SMARTLIST_FOREACH(statuses
, local_routerstatus_t
*, rs
,
3764 s
= networkstatus_getinfo_helper_single(&rs
->status
);
3766 smartlist_add(strs
, s
);
3768 smartlist_add(strs
, tor_strdup("\r\n.\r\n"));
3770 s
= smartlist_join_strings(strs
, "", 0, NULL
);
3771 SMARTLIST_FOREACH(strs
, char *, cp
, tor_free(cp
));
3772 smartlist_free(strs
);
3773 send_control1_event_string(EVENT_NS
, ALL_NAMES
|ALL_FORMATS
, s
);
3778 /** Called when a single local_routerstatus_t has changed: Sends an NS event
3779 * to any countroller that cares. */
3781 control_event_networkstatus_changed_single(local_routerstatus_t
*rs
)
3783 smartlist_t
*statuses
;
3786 if (!EVENT_IS_INTERESTING(EVENT_NS
))
3789 statuses
= smartlist_create();
3790 smartlist_add(statuses
, rs
);
3791 r
= control_event_networkstatus_changed(statuses
);
3792 smartlist_free(statuses
);
3796 /** Our own router descriptor has changed; tell any controllers that care.
3799 control_event_my_descriptor_changed(void)
3801 send_control1_event(EVENT_DESCCHANGED
, ALL_NAMES
, "650 DESCCHANGED\r\n");
3805 /** Helper: sends a status event where <b>type</b> is one of
3806 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
3807 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
3808 * string corresponding to <b>args</b>. */
3810 control_event_status(int type
, int severity
, const char *format
, va_list args
)
3812 char format_buf
[160];
3813 const char *status
, *sev
;
3816 case EVENT_STATUS_GENERAL
:
3817 status
= "STATUS_GENERAL";
3819 case EVENT_STATUS_CLIENT
:
3820 status
= "STATUS_CLIENT";
3822 case EVENT_STATUS_SERVER
:
3823 status
= "STATUS_SEVER";
3826 log_warn(LD_BUG
, "Unrecognized status type %d", type
);
3840 log_warn(LD_BUG
, "Unrecognized status severity %d", severity
);
3843 if (tor_snprintf(format_buf
, sizeof(format_buf
), "650 %s %s %s\r\n",
3844 status
, sev
, format
)<0) {
3845 log_warn(LD_BUG
, "Format string too long.");
3849 send_control1_event_impl(type
, ALL_NAMES
|ALL_FORMATS
, 0, format_buf
, args
);
3853 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
3854 * by formatting the arguments using the printf-style <b>format</b>. */
3856 control_event_general_status(int severity
, const char *format
, ...)
3860 if (!EVENT_IS_INTERESTING1(EVENT_STATUS_GENERAL
))
3863 va_start(ap
, format
);
3864 r
= control_event_status(EVENT_STATUS_GENERAL
, severity
, format
, ap
);
3869 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
3870 * by formatting the arguments using the printf-style <b>format</b>. */
3872 control_event_client_status(int severity
, const char *format
, ...)
3876 if (!EVENT_IS_INTERESTING1(EVENT_STATUS_CLIENT
))
3879 va_start(ap
, format
);
3880 r
= control_event_status(EVENT_STATUS_CLIENT
, severity
, format
, ap
);
3885 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
3886 * by formatting the arguments using the printf-style <b>format</b>. */
3888 control_event_server_status(int severity
, const char *format
, ...)
3892 if (!EVENT_IS_INTERESTING1(EVENT_STATUS_SERVER
))
3895 va_start(ap
, format
);
3896 r
= control_event_status(EVENT_STATUS_SERVER
, severity
, format
, ap
);
3901 /** Called when the status of an entry guard with the given <b>nickname</b>
3902 * and identity <b>digest</b> has changed to <b>status</b>: tells any
3903 * controllers that care. */
3905 control_event_guard(const char *nickname
, const char *digest
,
3908 char hbuf
[HEX_DIGEST_LEN
+1];
3909 base16_encode(hbuf
, sizeof(hbuf
), digest
, DIGEST_LEN
);
3910 if (!EVENT_IS_INTERESTING1(EVENT_GUARD
))
3913 if (EVENT_IS_INTERESTING1L(EVENT_GUARD
)) {
3914 char buf
[MAX_VERBOSE_NICKNAME_LEN
+1];
3915 routerinfo_t
*ri
= router_get_by_digest(digest
);
3917 router_get_verbose_nickname(buf
, ri
);
3919 tor_snprintf(buf
, sizeof(buf
), "$%s~%s", hbuf
, nickname
);
3921 send_control1_event(EVENT_GUARD
, LONG_NAMES
,
3922 "650 GUARD ENTRY %s %s\r\n", buf
, status
);
3924 if (EVENT_IS_INTERESTING1S(EVENT_GUARD
)) {
3925 send_control1_event(EVENT_GUARD
, SHORT_NAMES
,
3926 "650 GUARD ENTRY $%s %s\r\n", hbuf
, status
);
3931 /** Choose a random authentication cookie and write it to disk.
3932 * Anybody who can read the cookie from disk will be considered
3933 * authorized to use the control connection. */
3935 init_cookie_authentication(int enabled
)
3940 authentication_cookie_is_set
= 0;
3944 tor_snprintf(fname
, sizeof(fname
), "%s/control_auth_cookie",
3945 get_options()->DataDirectory
);
3946 crypto_rand(authentication_cookie
, AUTHENTICATION_COOKIE_LEN
);
3947 authentication_cookie_is_set
= 1;
3948 if (write_bytes_to_file(fname
, authentication_cookie
,
3949 AUTHENTICATION_COOKIE_LEN
, 1)) {
3950 log_warn(LD_FS
,"Error writing authentication cookie.");