Fix a number of clang analyzer false-positives
[tor.git] / src / or / control.c
blob4a6b18d02ad0f40adfece4a31ab467aead24e426
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2013, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file control.c
7 * \brief Implementation for Tor's control-socket interface.
8 * See doc/spec/control-spec.txt for full details on protocol.
9 **/
11 #define CONTROL_PRIVATE
13 #include "or.h"
14 #include "addressmap.h"
15 #include "buffers.h"
16 #include "channel.h"
17 #include "channeltls.h"
18 #include "circuitbuild.h"
19 #include "circuitlist.h"
20 #include "circuitstats.h"
21 #include "circuituse.h"
22 #include "command.h"
23 #include "config.h"
24 #include "confparse.h"
25 #include "connection.h"
26 #include "connection_edge.h"
27 #include "connection_or.h"
28 #include "control.h"
29 #include "directory.h"
30 #include "dirserv.h"
31 #include "dnsserv.h"
32 #include "entrynodes.h"
33 #include "geoip.h"
34 #include "hibernate.h"
35 #include "main.h"
36 #include "networkstatus.h"
37 #include "nodelist.h"
38 #include "policies.h"
39 #include "reasons.h"
40 #include "rephist.h"
41 #include "router.h"
42 #include "routerlist.h"
43 #include "routerparse.h"
45 #ifndef _WIN32
46 #include <pwd.h>
47 #include <sys/resource.h>
48 #endif
50 #include "procmon.h"
52 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
53 * finished authentication and is accepting commands. */
54 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
56 /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
57 * connection is interested in events of type <b>e</b>. We use this
58 * so that we can decide to skip generating event messages that nobody
59 * has interest in without having to walk over the global connection
60 * list to find out.
61 **/
62 typedef uint64_t event_mask_t;
64 /** An event mask of all the events that any controller is interested in
65 * receiving. */
66 static event_mask_t global_event_mask = 0;
68 /** True iff we have disabled log messages from being sent to the controller */
69 static int disable_log_messages = 0;
71 /** Macro: true if any control connection is interested in events of type
72 * <b>e</b>. */
73 #define EVENT_IS_INTERESTING(e) \
74 (!! (global_event_mask & (((uint64_t)1)<<(e))))
76 /** If we're using cookie-type authentication, how long should our cookies be?
78 #define AUTHENTICATION_COOKIE_LEN 32
80 /** If true, we've set authentication_cookie to a secret code and
81 * stored it to disk. */
82 static int authentication_cookie_is_set = 0;
83 /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
84 * and which we're using to authenticate controllers. (If the controller can
85 * read it off disk, it has permission to connect.) */
86 static uint8_t *authentication_cookie = NULL;
88 #define SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT \
89 "Tor safe cookie authentication server-to-controller hash"
90 #define SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT \
91 "Tor safe cookie authentication controller-to-server hash"
92 #define SAFECOOKIE_SERVER_NONCE_LEN DIGEST256_LEN
94 /** A sufficiently large size to record the last bootstrap phase string. */
95 #define BOOTSTRAP_MSG_LEN 1024
97 /** What was the last bootstrap phase message we sent? We keep track
98 * of this so we can respond to getinfo status/bootstrap-phase queries. */
99 static char last_sent_bootstrap_message[BOOTSTRAP_MSG_LEN];
101 static void connection_printf_to_buf(control_connection_t *conn,
102 const char *format, ...)
103 CHECK_PRINTF(2,3);
104 static void send_control_event_impl(uint16_t event, event_format_t which,
105 const char *format, va_list ap)
106 CHECK_PRINTF(3,0);
107 static int control_event_status(int type, int severity, const char *format,
108 va_list args)
109 CHECK_PRINTF(3,0);
111 static void send_control_done(control_connection_t *conn);
112 static void send_control_event(uint16_t event, event_format_t which,
113 const char *format, ...)
114 CHECK_PRINTF(3,4);
115 static int handle_control_setconf(control_connection_t *conn, uint32_t len,
116 char *body);
117 static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
118 char *body);
119 static int handle_control_getconf(control_connection_t *conn, uint32_t len,
120 const char *body);
121 static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
122 const char *body);
123 static int handle_control_setevents(control_connection_t *conn, uint32_t len,
124 const char *body);
125 static int handle_control_authenticate(control_connection_t *conn,
126 uint32_t len,
127 const char *body);
128 static int handle_control_signal(control_connection_t *conn, uint32_t len,
129 const char *body);
130 static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
131 const char *body);
132 static char *list_getinfo_options(void);
133 static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
134 const char *body);
135 static int handle_control_extendcircuit(control_connection_t *conn,
136 uint32_t len,
137 const char *body);
138 static int handle_control_setcircuitpurpose(control_connection_t *conn,
139 uint32_t len, const char *body);
140 static int handle_control_attachstream(control_connection_t *conn,
141 uint32_t len,
142 const char *body);
143 static int handle_control_postdescriptor(control_connection_t *conn,
144 uint32_t len,
145 const char *body);
146 static int handle_control_redirectstream(control_connection_t *conn,
147 uint32_t len,
148 const char *body);
149 static int handle_control_closestream(control_connection_t *conn, uint32_t len,
150 const char *body);
151 static int handle_control_closecircuit(control_connection_t *conn,
152 uint32_t len,
153 const char *body);
154 static int handle_control_resolve(control_connection_t *conn, uint32_t len,
155 const char *body);
156 static int handle_control_usefeature(control_connection_t *conn,
157 uint32_t len,
158 const char *body);
159 static int write_stream_target_to_buf(entry_connection_t *conn, char *buf,
160 size_t len);
161 static void orconn_target_get_name(char *buf, size_t len,
162 or_connection_t *conn);
164 /** Given a control event code for a message event, return the corresponding
165 * log severity. */
166 static INLINE int
167 event_to_log_severity(int event)
169 switch (event) {
170 case EVENT_DEBUG_MSG: return LOG_DEBUG;
171 case EVENT_INFO_MSG: return LOG_INFO;
172 case EVENT_NOTICE_MSG: return LOG_NOTICE;
173 case EVENT_WARN_MSG: return LOG_WARN;
174 case EVENT_ERR_MSG: return LOG_ERR;
175 default: return -1;
179 /** Given a log severity, return the corresponding control event code. */
180 static INLINE int
181 log_severity_to_event(int severity)
183 switch (severity) {
184 case LOG_DEBUG: return EVENT_DEBUG_MSG;
185 case LOG_INFO: return EVENT_INFO_MSG;
186 case LOG_NOTICE: return EVENT_NOTICE_MSG;
187 case LOG_WARN: return EVENT_WARN_MSG;
188 case LOG_ERR: return EVENT_ERR_MSG;
189 default: return -1;
193 /** Helper: clear bandwidth counters of all origin circuits. */
194 static void
195 clear_circ_bw_fields(void)
197 circuit_t *circ;
198 origin_circuit_t *ocirc;
199 TOR_LIST_FOREACH(circ, circuit_get_global_list(), head) {
200 if (!CIRCUIT_IS_ORIGIN(circ))
201 continue;
202 ocirc = TO_ORIGIN_CIRCUIT(circ);
203 ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
207 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
208 * connection's event_mask field. */
209 void
210 control_update_global_event_mask(void)
212 smartlist_t *conns = get_connection_array();
213 event_mask_t old_mask, new_mask;
214 old_mask = global_event_mask;
216 global_event_mask = 0;
217 SMARTLIST_FOREACH(conns, connection_t *, _conn,
219 if (_conn->type == CONN_TYPE_CONTROL &&
220 STATE_IS_OPEN(_conn->state)) {
221 control_connection_t *conn = TO_CONTROL_CONN(_conn);
222 global_event_mask |= conn->event_mask;
226 new_mask = global_event_mask;
228 /* Handle the aftermath. Set up the log callback to tell us only what
229 * we want to hear...*/
230 control_adjust_event_log_severity();
232 /* ...then, if we've started logging stream or circ bw, clear the
233 * appropriate fields. */
234 if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
235 (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
236 SMARTLIST_FOREACH(conns, connection_t *, conn,
238 if (conn->type == CONN_TYPE_AP) {
239 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
240 edge_conn->n_written = edge_conn->n_read = 0;
244 if (! (old_mask & EVENT_CIRC_BANDWIDTH_USED) &&
245 (new_mask & EVENT_CIRC_BANDWIDTH_USED)) {
246 clear_circ_bw_fields();
250 /** Adjust the log severities that result in control_event_logmsg being called
251 * to match the severity of log messages that any controllers are interested
252 * in. */
253 void
254 control_adjust_event_log_severity(void)
256 int i;
257 int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
259 for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
260 if (EVENT_IS_INTERESTING(i)) {
261 min_log_event = i;
262 break;
265 for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
266 if (EVENT_IS_INTERESTING(i)) {
267 max_log_event = i;
268 break;
271 if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
272 if (min_log_event > EVENT_NOTICE_MSG)
273 min_log_event = EVENT_NOTICE_MSG;
274 if (max_log_event < EVENT_ERR_MSG)
275 max_log_event = EVENT_ERR_MSG;
277 if (min_log_event <= max_log_event)
278 change_callback_log_severity(event_to_log_severity(min_log_event),
279 event_to_log_severity(max_log_event),
280 control_event_logmsg);
281 else
282 change_callback_log_severity(LOG_ERR, LOG_ERR,
283 control_event_logmsg);
286 /** Return true iff the event with code <b>c</b> is being sent to any current
287 * control connection. This is useful if the amount of work needed to prepare
288 * to call the appropriate control_event_...() function is high.
291 control_event_is_interesting(int event)
293 return EVENT_IS_INTERESTING(event);
296 /** Append a NUL-terminated string <b>s</b> to the end of
297 * <b>conn</b>-\>outbuf.
299 static INLINE void
300 connection_write_str_to_buf(const char *s, control_connection_t *conn)
302 size_t len = strlen(s);
303 connection_write_to_buf(s, len, TO_CONN(conn));
306 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
307 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
308 * contents of <b>data</b> into *<b>out</b>, adding a period before any period
309 * that appears at the start of a line, and adding a period-CRLF line at
310 * the end. Replace all LF characters sequences with CRLF. Return the number
311 * of bytes in *<b>out</b>.
313 STATIC size_t
314 write_escaped_data(const char *data, size_t len, char **out)
316 size_t sz_out = len+8;
317 char *outp;
318 const char *start = data, *end;
319 int i;
320 int start_of_line;
321 for (i=0; i<(int)len; ++i) {
322 if (data[i]== '\n')
323 sz_out += 2; /* Maybe add a CR; maybe add a dot. */
325 *out = outp = tor_malloc(sz_out+1);
326 end = data+len;
327 start_of_line = 1;
328 while (data < end) {
329 if (*data == '\n') {
330 if (data > start && data[-1] != '\r')
331 *outp++ = '\r';
332 start_of_line = 1;
333 } else if (*data == '.') {
334 if (start_of_line) {
335 start_of_line = 0;
336 *outp++ = '.';
338 } else {
339 start_of_line = 0;
341 *outp++ = *data++;
343 if (outp < *out+2 || fast_memcmp(outp-2, "\r\n", 2)) {
344 *outp++ = '\r';
345 *outp++ = '\n';
347 *outp++ = '.';
348 *outp++ = '\r';
349 *outp++ = '\n';
350 *outp = '\0'; /* NUL-terminate just in case. */
351 tor_assert((outp - *out) <= (int)sz_out);
352 return outp - *out;
355 /** Given a <b>len</b>-character string in <b>data</b>, made of lines
356 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
357 * the contents of <b>data</b> into *<b>out</b>, removing any period
358 * that appears at the start of a line, and replacing all CRLF sequences
359 * with LF. Return the number of
360 * bytes in *<b>out</b>. */
361 STATIC size_t
362 read_escaped_data(const char *data, size_t len, char **out)
364 char *outp;
365 const char *next;
366 const char *end;
368 *out = outp = tor_malloc(len+1);
370 end = data+len;
372 while (data < end) {
373 /* we're at the start of a line. */
374 if (*data == '.')
375 ++data;
376 next = memchr(data, '\n', end-data);
377 if (next) {
378 size_t n_to_copy = next-data;
379 /* Don't copy a CR that precedes this LF. */
380 if (n_to_copy && *(next-1) == '\r')
381 --n_to_copy;
382 memcpy(outp, data, n_to_copy);
383 outp += n_to_copy;
384 data = next+1; /* This will point at the start of the next line,
385 * or the end of the string, or a period. */
386 } else {
387 memcpy(outp, data, end-data);
388 outp += (end-data);
389 *outp = '\0';
390 return outp - *out;
392 *outp++ = '\n';
395 *outp = '\0';
396 return outp - *out;
399 /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
400 * double-quoted string with escaped characters, return the length of that
401 * string (as encoded, including quotes). Otherwise return -1. */
402 static INLINE int
403 get_escaped_string_length(const char *start, size_t in_len_max,
404 int *chars_out)
406 const char *cp, *end;
407 int chars = 0;
409 if (*start != '\"')
410 return -1;
412 cp = start+1;
413 end = start+in_len_max;
415 /* Calculate length. */
416 while (1) {
417 if (cp >= end) {
418 return -1; /* Too long. */
419 } else if (*cp == '\\') {
420 if (++cp == end)
421 return -1; /* Can't escape EOS. */
422 ++cp;
423 ++chars;
424 } else if (*cp == '\"') {
425 break;
426 } else {
427 ++cp;
428 ++chars;
431 if (chars_out)
432 *chars_out = chars;
433 return (int)(cp - start+1);
436 /** As decode_escaped_string, but does not decode the string: copies the
437 * entire thing, including quotation marks. */
438 static const char *
439 extract_escaped_string(const char *start, size_t in_len_max,
440 char **out, size_t *out_len)
442 int length = get_escaped_string_length(start, in_len_max, NULL);
443 if (length<0)
444 return NULL;
445 *out_len = length;
446 *out = tor_strndup(start, *out_len);
447 return start+length;
450 /** Given a pointer to a string starting at <b>start</b> containing
451 * <b>in_len_max</b> characters, decode a string beginning with one double
452 * quote, containing any number of non-quote characters or characters escaped
453 * with a backslash, and ending with a final double quote. Place the resulting
454 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
455 * store its length in <b>out_len</b>. On success, return a pointer to the
456 * character immediately following the escaped string. On failure, return
457 * NULL. */
458 static const char *
459 decode_escaped_string(const char *start, size_t in_len_max,
460 char **out, size_t *out_len)
462 const char *cp, *end;
463 char *outp;
464 int len, n_chars = 0;
466 len = get_escaped_string_length(start, in_len_max, &n_chars);
467 if (len<0)
468 return NULL;
470 end = start+len-1; /* Index of last quote. */
471 tor_assert(*end == '\"');
472 outp = *out = tor_malloc(len+1);
473 *out_len = n_chars;
475 cp = start+1;
476 while (cp < end) {
477 if (*cp == '\\')
478 ++cp;
479 *outp++ = *cp++;
481 *outp = '\0';
482 tor_assert((outp - *out) == (int)*out_len);
484 return end+1;
487 /** Acts like sprintf, but writes its formatted string to the end of
488 * <b>conn</b>-\>outbuf. */
489 static void
490 connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
492 va_list ap;
493 char *buf = NULL;
494 int len;
496 va_start(ap,format);
497 len = tor_vasprintf(&buf, format, ap);
498 va_end(ap);
500 if (len < 0) {
501 log_err(LD_BUG, "Unable to format string for controller.");
502 tor_assert(0);
505 connection_write_to_buf(buf, (size_t)len, TO_CONN(conn));
507 tor_free(buf);
510 /** Write all of the open control ports to ControlPortWriteToFile */
511 void
512 control_ports_write_to_file(void)
514 smartlist_t *lines;
515 char *joined = NULL;
516 const or_options_t *options = get_options();
518 if (!options->ControlPortWriteToFile)
519 return;
521 lines = smartlist_new();
523 SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t *, conn) {
524 if (conn->type != CONN_TYPE_CONTROL_LISTENER || conn->marked_for_close)
525 continue;
526 #ifdef AF_UNIX
527 if (conn->socket_family == AF_UNIX) {
528 smartlist_add_asprintf(lines, "UNIX_PORT=%s\n", conn->address);
529 continue;
531 #endif
532 smartlist_add_asprintf(lines, "PORT=%s:%d\n", conn->address, conn->port);
533 } SMARTLIST_FOREACH_END(conn);
535 joined = smartlist_join_strings(lines, "", 0, NULL);
537 if (write_str_to_file(options->ControlPortWriteToFile, joined, 0) < 0) {
538 log_warn(LD_CONTROL, "Writing %s failed: %s",
539 options->ControlPortWriteToFile, strerror(errno));
541 #ifndef _WIN32
542 if (options->ControlPortFileGroupReadable) {
543 if (chmod(options->ControlPortWriteToFile, 0640)) {
544 log_warn(LD_FS,"Unable to make %s group-readable.",
545 options->ControlPortWriteToFile);
548 #endif
549 tor_free(joined);
550 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
551 smartlist_free(lines);
554 /** Send a "DONE" message down the control connection <b>conn</b>. */
555 static void
556 send_control_done(control_connection_t *conn)
558 connection_write_str_to_buf("250 OK\r\n", conn);
561 /** Send an event to all v1 controllers that are listening for code
562 * <b>event</b>. The event's body is given by <b>msg</b>.
564 * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
565 * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
566 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
567 * to controllers that <em>have</em> enabled VERBOSE_NAMES.
569 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
570 * respect to the EXTENDED_EVENTS feature. */
571 MOCK_IMPL(STATIC void,
572 send_control_event_string,(uint16_t event, event_format_t which,
573 const char *msg))
575 smartlist_t *conns = get_connection_array();
576 (void)which;
577 tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
579 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
580 if (conn->type == CONN_TYPE_CONTROL &&
581 !conn->marked_for_close &&
582 conn->state == CONTROL_CONN_STATE_OPEN) {
583 control_connection_t *control_conn = TO_CONTROL_CONN(conn);
585 if (control_conn->event_mask & (1<<event)) {
586 int is_err = 0;
587 connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
588 if (event == EVENT_ERR_MSG)
589 is_err = 1;
590 else if (event == EVENT_STATUS_GENERAL)
591 is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
592 else if (event == EVENT_STATUS_CLIENT)
593 is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
594 else if (event == EVENT_STATUS_SERVER)
595 is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
596 if (is_err)
597 connection_flush(TO_CONN(control_conn));
600 } SMARTLIST_FOREACH_END(conn);
603 /** Helper for send_control_event and control_event_status:
604 * Send an event to all v1 controllers that are listening for code
605 * <b>event</b>. The event's body is created by the printf-style format in
606 * <b>format</b>, and other arguments as provided. */
607 static void
608 send_control_event_impl(uint16_t event, event_format_t which,
609 const char *format, va_list ap)
611 char *buf = NULL;
612 int len;
614 len = tor_vasprintf(&buf, format, ap);
615 if (len < 0) {
616 log_warn(LD_BUG, "Unable to format event for controller.");
617 return;
620 send_control_event_string(event, which|ALL_FORMATS, buf);
622 tor_free(buf);
625 /** Send an event to all v1 controllers that are listening for code
626 * <b>event</b>. The event's body is created by the printf-style format in
627 * <b>format</b>, and other arguments as provided. */
628 static void
629 send_control_event(uint16_t event, event_format_t which,
630 const char *format, ...)
632 va_list ap;
633 va_start(ap, format);
634 send_control_event_impl(event, which, format, ap);
635 va_end(ap);
638 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
639 static origin_circuit_t *
640 get_circ(const char *id)
642 uint32_t n_id;
643 int ok;
644 n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
645 if (!ok)
646 return NULL;
647 return circuit_get_by_global_id(n_id);
650 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
651 static entry_connection_t *
652 get_stream(const char *id)
654 uint64_t n_id;
655 int ok;
656 connection_t *conn;
657 n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
658 if (!ok)
659 return NULL;
660 conn = connection_get_by_global_id(n_id);
661 if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
662 return NULL;
663 return TO_ENTRY_CONN(conn);
666 /** Helper for setconf and resetconf. Acts like setconf, except
667 * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
668 * contents of body.
670 static int
671 control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
672 int use_defaults)
674 setopt_err_t opt_err;
675 config_line_t *lines=NULL;
676 char *start = body;
677 char *errstring = NULL;
678 const int clear_first = 1;
680 char *config;
681 smartlist_t *entries = smartlist_new();
683 /* We have a string, "body", of the format '(key(=val|="val")?)' entries
684 * separated by space. break it into a list of configuration entries. */
685 while (*body) {
686 char *eq = body;
687 char *key;
688 char *entry;
689 while (!TOR_ISSPACE(*eq) && *eq != '=')
690 ++eq;
691 key = tor_strndup(body, eq-body);
692 body = eq+1;
693 if (*eq == '=') {
694 char *val=NULL;
695 size_t val_len=0;
696 if (*body != '\"') {
697 char *val_start = body;
698 while (!TOR_ISSPACE(*body))
699 body++;
700 val = tor_strndup(val_start, body-val_start);
701 val_len = strlen(val);
702 } else {
703 body = (char*)extract_escaped_string(body, (len - (body-start)),
704 &val, &val_len);
705 if (!body) {
706 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
707 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
708 smartlist_free(entries);
709 tor_free(key);
710 return 0;
713 tor_asprintf(&entry, "%s %s", key, val);
714 tor_free(key);
715 tor_free(val);
716 } else {
717 entry = key;
719 smartlist_add(entries, entry);
720 while (TOR_ISSPACE(*body))
721 ++body;
724 smartlist_add(entries, tor_strdup(""));
725 config = smartlist_join_strings(entries, "\n", 0, NULL);
726 SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
727 smartlist_free(entries);
729 if (config_get_lines(config, &lines, 0) < 0) {
730 log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
731 connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
732 conn);
733 tor_free(config);
734 return 0;
736 tor_free(config);
738 opt_err = options_trial_assign(lines, use_defaults, clear_first, &errstring);
740 const char *msg;
741 switch (opt_err) {
742 case SETOPT_ERR_MISC:
743 msg = "552 Unrecognized option";
744 break;
745 case SETOPT_ERR_PARSE:
746 msg = "513 Unacceptable option value";
747 break;
748 case SETOPT_ERR_TRANSITION:
749 msg = "553 Transition not allowed";
750 break;
751 case SETOPT_ERR_SETTING:
752 default:
753 msg = "553 Unable to set option";
754 break;
755 case SETOPT_OK:
756 config_free_lines(lines);
757 send_control_done(conn);
758 return 0;
760 log_warn(LD_CONTROL,
761 "Controller gave us config lines that didn't validate: %s",
762 errstring);
763 connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
764 config_free_lines(lines);
765 tor_free(errstring);
766 return 0;
770 /** Called when we receive a SETCONF message: parse the body and try
771 * to update our configuration. Reply with a DONE or ERROR message.
772 * Modifies the contents of body.*/
773 static int
774 handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
776 return control_setconf_helper(conn, len, body, 0);
779 /** Called when we receive a RESETCONF message: parse the body and try
780 * to update our configuration. Reply with a DONE or ERROR message.
781 * Modifies the contents of body. */
782 static int
783 handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
785 return control_setconf_helper(conn, len, body, 1);
788 /** Called when we receive a GETCONF message. Parse the request, and
789 * reply with a CONFVALUE or an ERROR message */
790 static int
791 handle_control_getconf(control_connection_t *conn, uint32_t body_len,
792 const char *body)
794 smartlist_t *questions = smartlist_new();
795 smartlist_t *answers = smartlist_new();
796 smartlist_t *unrecognized = smartlist_new();
797 char *msg = NULL;
798 size_t msg_len;
799 const or_options_t *options = get_options();
800 int i, len;
802 (void) body_len; /* body is NUL-terminated; so we can ignore len. */
803 smartlist_split_string(questions, body, " ",
804 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
805 SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
806 if (!option_is_recognized(q)) {
807 smartlist_add(unrecognized, (char*) q);
808 } else {
809 config_line_t *answer = option_get_assignment(options,q);
810 if (!answer) {
811 const char *name = option_get_canonical_name(q);
812 smartlist_add_asprintf(answers, "250-%s\r\n", name);
815 while (answer) {
816 config_line_t *next;
817 smartlist_add_asprintf(answers, "250-%s=%s\r\n",
818 answer->key, answer->value);
820 next = answer->next;
821 tor_free(answer->key);
822 tor_free(answer->value);
823 tor_free(answer);
824 answer = next;
827 } SMARTLIST_FOREACH_END(q);
829 if ((len = smartlist_len(unrecognized))) {
830 for (i=0; i < len-1; ++i)
831 connection_printf_to_buf(conn,
832 "552-Unrecognized configuration key \"%s\"\r\n",
833 (char*)smartlist_get(unrecognized, i));
834 connection_printf_to_buf(conn,
835 "552 Unrecognized configuration key \"%s\"\r\n",
836 (char*)smartlist_get(unrecognized, len-1));
837 } else if ((len = smartlist_len(answers))) {
838 char *tmp = smartlist_get(answers, len-1);
839 tor_assert(strlen(tmp)>4);
840 tmp[3] = ' ';
841 msg = smartlist_join_strings(answers, "", 0, &msg_len);
842 connection_write_to_buf(msg, msg_len, TO_CONN(conn));
843 } else {
844 connection_write_str_to_buf("250 OK\r\n", conn);
847 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
848 smartlist_free(answers);
849 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
850 smartlist_free(questions);
851 smartlist_free(unrecognized);
853 tor_free(msg);
855 return 0;
858 /** Called when we get a +LOADCONF message. */
859 static int
860 handle_control_loadconf(control_connection_t *conn, uint32_t len,
861 const char *body)
863 setopt_err_t retval;
864 char *errstring = NULL;
865 const char *msg = NULL;
866 (void) len;
868 retval = options_init_from_string(NULL, body, CMD_RUN_TOR, NULL, &errstring);
870 if (retval != SETOPT_OK)
871 log_warn(LD_CONTROL,
872 "Controller gave us config file that didn't validate: %s",
873 errstring);
875 switch (retval) {
876 case SETOPT_ERR_PARSE:
877 msg = "552 Invalid config file";
878 break;
879 case SETOPT_ERR_TRANSITION:
880 msg = "553 Transition not allowed";
881 break;
882 case SETOPT_ERR_SETTING:
883 msg = "553 Unable to set option";
884 break;
885 case SETOPT_ERR_MISC:
886 default:
887 msg = "550 Unable to load config";
888 break;
889 case SETOPT_OK:
890 break;
892 if (msg) {
893 if (errstring)
894 connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
895 else
896 connection_printf_to_buf(conn, "%s\r\n", msg);
897 } else {
898 send_control_done(conn);
900 tor_free(errstring);
901 return 0;
904 /** Helper structure: maps event values to their names. */
905 struct control_event_t {
906 uint16_t event_code;
907 const char *event_name;
909 /** Table mapping event values to their names. Used to implement SETEVENTS
910 * and GETINFO events/names, and to keep they in sync. */
911 static const struct control_event_t control_event_table[] = {
912 { EVENT_CIRCUIT_STATUS, "CIRC" },
913 { EVENT_CIRCUIT_STATUS_MINOR, "CIRC_MINOR" },
914 { EVENT_STREAM_STATUS, "STREAM" },
915 { EVENT_OR_CONN_STATUS, "ORCONN" },
916 { EVENT_BANDWIDTH_USED, "BW" },
917 { EVENT_DEBUG_MSG, "DEBUG" },
918 { EVENT_INFO_MSG, "INFO" },
919 { EVENT_NOTICE_MSG, "NOTICE" },
920 { EVENT_WARN_MSG, "WARN" },
921 { EVENT_ERR_MSG, "ERR" },
922 { EVENT_NEW_DESC, "NEWDESC" },
923 { EVENT_ADDRMAP, "ADDRMAP" },
924 { EVENT_AUTHDIR_NEWDESCS, "AUTHDIR_NEWDESCS" },
925 { EVENT_DESCCHANGED, "DESCCHANGED" },
926 { EVENT_NS, "NS" },
927 { EVENT_STATUS_GENERAL, "STATUS_GENERAL" },
928 { EVENT_STATUS_CLIENT, "STATUS_CLIENT" },
929 { EVENT_STATUS_SERVER, "STATUS_SERVER" },
930 { EVENT_GUARD, "GUARD" },
931 { EVENT_STREAM_BANDWIDTH_USED, "STREAM_BW" },
932 { EVENT_CLIENTS_SEEN, "CLIENTS_SEEN" },
933 { EVENT_NEWCONSENSUS, "NEWCONSENSUS" },
934 { EVENT_BUILDTIMEOUT_SET, "BUILDTIMEOUT_SET" },
935 { EVENT_SIGNAL, "SIGNAL" },
936 { EVENT_CONF_CHANGED, "CONF_CHANGED"},
937 { EVENT_CONN_BW, "CONN_BW" },
938 { EVENT_CELL_STATS, "CELL_STATS" },
939 { EVENT_TB_EMPTY, "TB_EMPTY" },
940 { EVENT_CIRC_BANDWIDTH_USED, "CIRC_BW" },
941 { EVENT_TRANSPORT_LAUNCHED, "TRANSPORT_LAUNCHED" },
942 { EVENT_HS_DESC, "HS_DESC" },
943 { 0, NULL },
946 /** Called when we get a SETEVENTS message: update conn->event_mask,
947 * and reply with DONE or ERROR. */
948 static int
949 handle_control_setevents(control_connection_t *conn, uint32_t len,
950 const char *body)
952 int event_code = -1;
953 uint32_t event_mask = 0;
954 smartlist_t *events = smartlist_new();
956 (void) len;
958 smartlist_split_string(events, body, " ",
959 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
960 SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
962 if (!strcasecmp(ev, "EXTENDED")) {
963 continue;
964 } else {
965 int i;
966 for (i = 0; control_event_table[i].event_name != NULL; ++i) {
967 if (!strcasecmp(ev, control_event_table[i].event_name)) {
968 event_code = control_event_table[i].event_code;
969 break;
973 if (event_code == -1) {
974 connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
975 ev);
976 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
977 smartlist_free(events);
978 return 0;
981 event_mask |= (1 << event_code);
983 SMARTLIST_FOREACH_END(ev);
984 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
985 smartlist_free(events);
987 conn->event_mask = event_mask;
989 control_update_global_event_mask();
990 send_control_done(conn);
991 return 0;
994 /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
995 * Return a smartlist of acceptable passwords (unterminated strings of
996 * length S2K_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on failure.
998 smartlist_t *
999 decode_hashed_passwords(config_line_t *passwords)
1001 char decoded[64];
1002 config_line_t *cl;
1003 smartlist_t *sl = smartlist_new();
1005 tor_assert(passwords);
1007 for (cl = passwords; cl; cl = cl->next) {
1008 const char *hashed = cl->value;
1010 if (!strcmpstart(hashed, "16:")) {
1011 if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
1012 || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
1013 goto err;
1015 } else {
1016 if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
1017 != S2K_SPECIFIER_LEN+DIGEST_LEN) {
1018 goto err;
1021 smartlist_add(sl, tor_memdup(decoded, S2K_SPECIFIER_LEN+DIGEST_LEN));
1024 return sl;
1026 err:
1027 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
1028 smartlist_free(sl);
1029 return NULL;
1032 /** Called when we get an AUTHENTICATE message. Check whether the
1033 * authentication is valid, and if so, update the connection's state to
1034 * OPEN. Reply with DONE or ERROR.
1036 static int
1037 handle_control_authenticate(control_connection_t *conn, uint32_t len,
1038 const char *body)
1040 int used_quoted_string = 0;
1041 const or_options_t *options = get_options();
1042 const char *errstr = NULL;
1043 char *password;
1044 size_t password_len;
1045 const char *cp;
1046 int i;
1047 int bad_cookie=0, bad_password=0;
1048 smartlist_t *sl = NULL;
1050 if (!len) {
1051 password = tor_strdup("");
1052 password_len = 0;
1053 } else if (TOR_ISXDIGIT(body[0])) {
1054 cp = body;
1055 while (TOR_ISXDIGIT(*cp))
1056 ++cp;
1057 i = (int)(cp - body);
1058 tor_assert(i>0);
1059 password_len = i/2;
1060 password = tor_malloc(password_len + 1);
1061 if (base16_decode(password, password_len+1, body, i)<0) {
1062 connection_write_str_to_buf(
1063 "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1064 "password? If so, the standard requires that you put it in "
1065 "double quotes.\r\n", conn);
1066 connection_mark_for_close(TO_CONN(conn));
1067 tor_free(password);
1068 return 0;
1070 } else {
1071 if (!decode_escaped_string(body, len, &password, &password_len)) {
1072 connection_write_str_to_buf("551 Invalid quoted string. You need "
1073 "to put the password in double quotes.\r\n", conn);
1074 connection_mark_for_close(TO_CONN(conn));
1075 return 0;
1077 used_quoted_string = 1;
1080 if (conn->safecookie_client_hash != NULL) {
1081 /* The controller has chosen safe cookie authentication; the only
1082 * acceptable authentication value is the controller-to-server
1083 * response. */
1085 tor_assert(authentication_cookie_is_set);
1087 if (password_len != DIGEST256_LEN) {
1088 log_warn(LD_CONTROL,
1089 "Got safe cookie authentication response with wrong length "
1090 "(%d)", (int)password_len);
1091 errstr = "Wrong length for safe cookie response.";
1092 goto err;
1095 if (tor_memneq(conn->safecookie_client_hash, password, DIGEST256_LEN)) {
1096 log_warn(LD_CONTROL,
1097 "Got incorrect safe cookie authentication response");
1098 errstr = "Safe cookie response did not match expected value.";
1099 goto err;
1102 tor_free(conn->safecookie_client_hash);
1103 goto ok;
1106 if (!options->CookieAuthentication && !options->HashedControlPassword &&
1107 !options->HashedControlSessionPassword) {
1108 /* if Tor doesn't demand any stronger authentication, then
1109 * the controller can get in with anything. */
1110 goto ok;
1113 if (options->CookieAuthentication) {
1114 int also_password = options->HashedControlPassword != NULL ||
1115 options->HashedControlSessionPassword != NULL;
1116 if (password_len != AUTHENTICATION_COOKIE_LEN) {
1117 if (!also_password) {
1118 log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
1119 "(%d)", (int)password_len);
1120 errstr = "Wrong length on authentication cookie.";
1121 goto err;
1123 bad_cookie = 1;
1124 } else if (tor_memneq(authentication_cookie, password, password_len)) {
1125 if (!also_password) {
1126 log_warn(LD_CONTROL, "Got mismatched authentication cookie");
1127 errstr = "Authentication cookie did not match expected value.";
1128 goto err;
1130 bad_cookie = 1;
1131 } else {
1132 goto ok;
1136 if (options->HashedControlPassword ||
1137 options->HashedControlSessionPassword) {
1138 int bad = 0;
1139 smartlist_t *sl_tmp;
1140 char received[DIGEST_LEN];
1141 int also_cookie = options->CookieAuthentication;
1142 sl = smartlist_new();
1143 if (options->HashedControlPassword) {
1144 sl_tmp = decode_hashed_passwords(options->HashedControlPassword);
1145 if (!sl_tmp)
1146 bad = 1;
1147 else {
1148 smartlist_add_all(sl, sl_tmp);
1149 smartlist_free(sl_tmp);
1152 if (options->HashedControlSessionPassword) {
1153 sl_tmp = decode_hashed_passwords(options->HashedControlSessionPassword);
1154 if (!sl_tmp)
1155 bad = 1;
1156 else {
1157 smartlist_add_all(sl, sl_tmp);
1158 smartlist_free(sl_tmp);
1161 if (bad) {
1162 if (!also_cookie) {
1163 log_warn(LD_CONTROL,
1164 "Couldn't decode HashedControlPassword: invalid base16");
1165 errstr="Couldn't decode HashedControlPassword value in configuration.";
1167 bad_password = 1;
1168 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1169 smartlist_free(sl);
1170 } else {
1171 SMARTLIST_FOREACH(sl, char *, expected,
1173 secret_to_key(received,DIGEST_LEN,password,password_len,expected);
1174 if (tor_memeq(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
1175 goto ok;
1177 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1178 smartlist_free(sl);
1180 if (used_quoted_string)
1181 errstr = "Password did not match HashedControlPassword value from "
1182 "configuration";
1183 else
1184 errstr = "Password did not match HashedControlPassword value from "
1185 "configuration. Maybe you tried a plain text password? "
1186 "If so, the standard requires that you put it in double quotes.";
1187 bad_password = 1;
1188 if (!also_cookie)
1189 goto err;
1193 /** We only get here if both kinds of authentication failed. */
1194 tor_assert(bad_password && bad_cookie);
1195 log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
1196 errstr = "Password did not match HashedControlPassword *or* authentication "
1197 "cookie.";
1199 err:
1200 tor_free(password);
1201 connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n",
1202 errstr ? errstr : "Unknown reason.");
1203 connection_mark_for_close(TO_CONN(conn));
1204 return 0;
1206 log_info(LD_CONTROL, "Authenticated control connection ("TOR_SOCKET_T_FORMAT
1207 ")", conn->base_.s);
1208 send_control_done(conn);
1209 conn->base_.state = CONTROL_CONN_STATE_OPEN;
1210 tor_free(password);
1211 if (sl) { /* clean up */
1212 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1213 smartlist_free(sl);
1215 return 0;
1218 /** Called when we get a SAVECONF command. Try to flush the current options to
1219 * disk, and report success or failure. */
1220 static int
1221 handle_control_saveconf(control_connection_t *conn, uint32_t len,
1222 const char *body)
1224 (void) len;
1225 (void) body;
1226 if (options_save_current()<0) {
1227 connection_write_str_to_buf(
1228 "551 Unable to write configuration to disk.\r\n", conn);
1229 } else {
1230 send_control_done(conn);
1232 return 0;
1235 struct signal_t {
1236 int sig;
1237 const char *signal_name;
1240 static const struct signal_t signal_table[] = {
1241 { SIGHUP, "RELOAD" },
1242 { SIGHUP, "HUP" },
1243 { SIGINT, "SHUTDOWN" },
1244 { SIGUSR1, "DUMP" },
1245 { SIGUSR1, "USR1" },
1246 { SIGUSR2, "DEBUG" },
1247 { SIGUSR2, "USR2" },
1248 { SIGTERM, "HALT" },
1249 { SIGTERM, "TERM" },
1250 { SIGTERM, "INT" },
1251 { SIGNEWNYM, "NEWNYM" },
1252 { SIGCLEARDNSCACHE, "CLEARDNSCACHE"},
1253 { 0, NULL },
1256 /** Called when we get a SIGNAL command. React to the provided signal, and
1257 * report success or failure. (If the signal results in a shutdown, success
1258 * may not be reported.) */
1259 static int
1260 handle_control_signal(control_connection_t *conn, uint32_t len,
1261 const char *body)
1263 int sig = -1;
1264 int i;
1265 int n = 0;
1266 char *s;
1268 (void) len;
1270 while (body[n] && ! TOR_ISSPACE(body[n]))
1271 ++n;
1272 s = tor_strndup(body, n);
1274 for (i = 0; signal_table[i].signal_name != NULL; ++i) {
1275 if (!strcasecmp(s, signal_table[i].signal_name)) {
1276 sig = signal_table[i].sig;
1277 break;
1281 if (sig < 0)
1282 connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
1284 tor_free(s);
1285 if (sig < 0)
1286 return 0;
1288 send_control_done(conn);
1289 /* Flush the "done" first if the signal might make us shut down. */
1290 if (sig == SIGTERM || sig == SIGINT)
1291 connection_flush(TO_CONN(conn));
1293 process_signal(sig);
1295 return 0;
1298 /** Called when we get a TAKEOWNERSHIP command. Mark this connection
1299 * as an owning connection, so that we will exit if the connection
1300 * closes. */
1301 static int
1302 handle_control_takeownership(control_connection_t *conn, uint32_t len,
1303 const char *body)
1305 (void)len;
1306 (void)body;
1308 conn->is_owning_control_connection = 1;
1310 log_info(LD_CONTROL, "Control connection %d has taken ownership of this "
1311 "Tor instance.",
1312 (int)(conn->base_.s));
1314 send_control_done(conn);
1315 return 0;
1318 /** Return true iff <b>addr</b> is unusable as a mapaddress target because of
1319 * containing funny characters. */
1320 static int
1321 address_is_invalid_mapaddress_target(const char *addr)
1323 if (!strcmpstart(addr, "*."))
1324 return address_is_invalid_destination(addr+2, 1);
1325 else
1326 return address_is_invalid_destination(addr, 1);
1329 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
1330 * and report success or failure. */
1331 static int
1332 handle_control_mapaddress(control_connection_t *conn, uint32_t len,
1333 const char *body)
1335 smartlist_t *elts;
1336 smartlist_t *lines;
1337 smartlist_t *reply;
1338 char *r;
1339 size_t sz;
1340 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
1342 lines = smartlist_new();
1343 elts = smartlist_new();
1344 reply = smartlist_new();
1345 smartlist_split_string(lines, body, " ",
1346 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1347 SMARTLIST_FOREACH_BEGIN(lines, char *, line) {
1348 tor_strlower(line);
1349 smartlist_split_string(elts, line, "=", 0, 2);
1350 if (smartlist_len(elts) == 2) {
1351 const char *from = smartlist_get(elts,0);
1352 const char *to = smartlist_get(elts,1);
1353 if (address_is_invalid_mapaddress_target(to)) {
1354 smartlist_add_asprintf(reply,
1355 "512-syntax error: invalid address '%s'", to);
1356 log_warn(LD_CONTROL,
1357 "Skipping invalid argument '%s' in MapAddress msg", to);
1358 } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0") ||
1359 !strcmp(from, "::")) {
1360 const char type =
1361 !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME :
1362 (!strcmp(from, "0.0.0.0") ? RESOLVED_TYPE_IPV4 : RESOLVED_TYPE_IPV6);
1363 const char *address = addressmap_register_virtual_address(
1364 type, tor_strdup(to));
1365 if (!address) {
1366 smartlist_add_asprintf(reply,
1367 "451-resource exhausted: skipping '%s'", line);
1368 log_warn(LD_CONTROL,
1369 "Unable to allocate address for '%s' in MapAddress msg",
1370 safe_str_client(line));
1371 } else {
1372 smartlist_add_asprintf(reply, "250-%s=%s", address, to);
1374 } else {
1375 const char *msg;
1376 if (addressmap_register_auto(from, to, 1,
1377 ADDRMAPSRC_CONTROLLER, &msg) < 0) {
1378 smartlist_add_asprintf(reply,
1379 "512-syntax error: invalid address mapping "
1380 " '%s': %s", line, msg);
1381 log_warn(LD_CONTROL,
1382 "Skipping invalid argument '%s' in MapAddress msg: %s",
1383 line, msg);
1384 } else {
1385 smartlist_add_asprintf(reply, "250-%s", line);
1388 } else {
1389 smartlist_add_asprintf(reply, "512-syntax error: mapping '%s' is "
1390 "not of expected form 'foo=bar'.", line);
1391 log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
1392 "number of items.",
1393 safe_str_client(line));
1395 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
1396 smartlist_clear(elts);
1397 } SMARTLIST_FOREACH_END(line);
1398 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1399 smartlist_free(lines);
1400 smartlist_free(elts);
1402 if (smartlist_len(reply)) {
1403 ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
1404 r = smartlist_join_strings(reply, "\r\n", 1, &sz);
1405 connection_write_to_buf(r, sz, TO_CONN(conn));
1406 tor_free(r);
1407 } else {
1408 const char *response =
1409 "512 syntax error: not enough arguments to mapaddress.\r\n";
1410 connection_write_to_buf(response, strlen(response), TO_CONN(conn));
1413 SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
1414 smartlist_free(reply);
1415 return 0;
1418 /** Implementation helper for GETINFO: knows the answers for various
1419 * trivial-to-implement questions. */
1420 static int
1421 getinfo_helper_misc(control_connection_t *conn, const char *question,
1422 char **answer, const char **errmsg)
1424 (void) conn;
1425 if (!strcmp(question, "version")) {
1426 *answer = tor_strdup(get_version());
1427 } else if (!strcmp(question, "config-file")) {
1428 *answer = tor_strdup(get_torrc_fname(0));
1429 } else if (!strcmp(question, "config-defaults-file")) {
1430 *answer = tor_strdup(get_torrc_fname(1));
1431 } else if (!strcmp(question, "config-text")) {
1432 *answer = options_dump(get_options(), OPTIONS_DUMP_MINIMAL);
1433 } else if (!strcmp(question, "info/names")) {
1434 *answer = list_getinfo_options();
1435 } else if (!strcmp(question, "dormant")) {
1436 int dormant = rep_hist_circbuilding_dormant(time(NULL));
1437 *answer = tor_strdup(dormant ? "1" : "0");
1438 } else if (!strcmp(question, "events/names")) {
1439 int i;
1440 smartlist_t *event_names = smartlist_new();
1442 for (i = 0; control_event_table[i].event_name != NULL; ++i) {
1443 smartlist_add(event_names, (char *)control_event_table[i].event_name);
1446 *answer = smartlist_join_strings(event_names, " ", 0, NULL);
1448 smartlist_free(event_names);
1449 } else if (!strcmp(question, "signal/names")) {
1450 smartlist_t *signal_names = smartlist_new();
1451 int j;
1452 for (j = 0; signal_table[j].signal_name != NULL; ++j) {
1453 smartlist_add(signal_names, (char*)signal_table[j].signal_name);
1456 *answer = smartlist_join_strings(signal_names, " ", 0, NULL);
1458 smartlist_free(signal_names);
1459 } else if (!strcmp(question, "features/names")) {
1460 *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1461 } else if (!strcmp(question, "address")) {
1462 uint32_t addr;
1463 if (router_pick_published_address(get_options(), &addr) < 0) {
1464 *errmsg = "Address unknown";
1465 return -1;
1467 *answer = tor_dup_ip(addr);
1468 } else if (!strcmp(question, "traffic/read")) {
1469 tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_read()));
1470 } else if (!strcmp(question, "traffic/written")) {
1471 tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_written()));
1472 } else if (!strcmp(question, "process/pid")) {
1473 int myPid = -1;
1475 #ifdef _WIN32
1476 myPid = _getpid();
1477 #else
1478 myPid = getpid();
1479 #endif
1481 tor_asprintf(answer, "%d", myPid);
1482 } else if (!strcmp(question, "process/uid")) {
1483 #ifdef _WIN32
1484 *answer = tor_strdup("-1");
1485 #else
1486 int myUid = geteuid();
1487 tor_asprintf(answer, "%d", myUid);
1488 #endif
1489 } else if (!strcmp(question, "process/user")) {
1490 #ifdef _WIN32
1491 *answer = tor_strdup("");
1492 #else
1493 int myUid = geteuid();
1494 const struct passwd *myPwEntry = tor_getpwuid(myUid);
1496 if (myPwEntry) {
1497 *answer = tor_strdup(myPwEntry->pw_name);
1498 } else {
1499 *answer = tor_strdup("");
1501 #endif
1502 } else if (!strcmp(question, "process/descriptor-limit")) {
1503 int max_fds=-1;
1504 set_max_file_descriptors(0, &max_fds);
1505 tor_asprintf(answer, "%d", max_fds);
1506 } else if (!strcmp(question, "limits/max-mem-in-queues")) {
1507 tor_asprintf(answer, U64_FORMAT,
1508 U64_PRINTF_ARG(get_options()->MaxMemInQueues));
1509 } else if (!strcmp(question, "dir-usage")) {
1510 *answer = directory_dump_request_log();
1511 } else if (!strcmp(question, "fingerprint")) {
1512 crypto_pk_t *server_key;
1513 if (!server_mode(get_options())) {
1514 *errmsg = "Not running in server mode";
1515 return -1;
1517 server_key = get_server_identity_key();
1518 *answer = tor_malloc(HEX_DIGEST_LEN+1);
1519 crypto_pk_get_fingerprint(server_key, *answer, 0);
1521 return 0;
1524 /** Awful hack: return a newly allocated string based on a routerinfo and
1525 * (possibly) an extrainfo, sticking the read-history and write-history from
1526 * <b>ei</b> into the resulting string. The thing you get back won't
1527 * necessarily have a valid signature.
1529 * New code should never use this; it's for backward compatibility.
1531 * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
1532 * not be NUL-terminated. */
1533 static char *
1534 munge_extrainfo_into_routerinfo(const char *ri_body,
1535 const signed_descriptor_t *ri,
1536 const signed_descriptor_t *ei)
1538 char *out = NULL, *outp;
1539 int i;
1540 const char *router_sig;
1541 const char *ei_body = signed_descriptor_get_body(ei);
1542 size_t ri_len = ri->signed_descriptor_len;
1543 size_t ei_len = ei->signed_descriptor_len;
1544 if (!ei_body)
1545 goto bail;
1547 outp = out = tor_malloc(ri_len+ei_len+1);
1548 if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
1549 goto bail;
1550 ++router_sig;
1551 memcpy(out, ri_body, router_sig-ri_body);
1552 outp += router_sig-ri_body;
1554 for (i=0; i < 2; ++i) {
1555 const char *kwd = i ? "\nwrite-history " : "\nread-history ";
1556 const char *cp, *eol;
1557 if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
1558 continue;
1559 ++cp;
1560 if (!(eol = memchr(cp, '\n', ei_len - (cp-ei_body))))
1561 continue;
1562 memcpy(outp, cp, eol-cp+1);
1563 outp += eol-cp+1;
1565 memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
1566 *outp++ = '\0';
1567 tor_assert(outp-out < (int)(ri_len+ei_len+1));
1569 return out;
1570 bail:
1571 tor_free(out);
1572 return tor_strndup(ri_body, ri->signed_descriptor_len);
1575 /** Implementation helper for GETINFO: answers requests for information about
1576 * which ports are bound. */
1577 static int
1578 getinfo_helper_listeners(control_connection_t *control_conn,
1579 const char *question,
1580 char **answer, const char **errmsg)
1582 int type;
1583 smartlist_t *res;
1585 (void)control_conn;
1586 (void)errmsg;
1588 if (!strcmp(question, "net/listeners/or"))
1589 type = CONN_TYPE_OR_LISTENER;
1590 else if (!strcmp(question, "net/listeners/dir"))
1591 type = CONN_TYPE_DIR_LISTENER;
1592 else if (!strcmp(question, "net/listeners/socks"))
1593 type = CONN_TYPE_AP_LISTENER;
1594 else if (!strcmp(question, "net/listeners/trans"))
1595 type = CONN_TYPE_AP_TRANS_LISTENER;
1596 else if (!strcmp(question, "net/listeners/natd"))
1597 type = CONN_TYPE_AP_NATD_LISTENER;
1598 else if (!strcmp(question, "net/listeners/dns"))
1599 type = CONN_TYPE_AP_DNS_LISTENER;
1600 else if (!strcmp(question, "net/listeners/control"))
1601 type = CONN_TYPE_CONTROL_LISTENER;
1602 else
1603 return 0; /* unknown key */
1605 res = smartlist_new();
1606 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
1607 struct sockaddr_storage ss;
1608 socklen_t ss_len = sizeof(ss);
1610 if (conn->type != type || conn->marked_for_close || !SOCKET_OK(conn->s))
1611 continue;
1613 if (getsockname(conn->s, (struct sockaddr *)&ss, &ss_len) < 0) {
1614 smartlist_add_asprintf(res, "%s:%d", conn->address, (int)conn->port);
1615 } else {
1616 char *tmp = tor_sockaddr_to_str((struct sockaddr *)&ss);
1617 smartlist_add(res, esc_for_log(tmp));
1618 tor_free(tmp);
1621 } SMARTLIST_FOREACH_END(conn);
1623 *answer = smartlist_join_strings(res, " ", 0, NULL);
1625 SMARTLIST_FOREACH(res, char *, cp, tor_free(cp));
1626 smartlist_free(res);
1627 return 0;
1630 /** Implementation helper for GETINFO: knows the answers for questions about
1631 * directory information. */
1632 static int
1633 getinfo_helper_dir(control_connection_t *control_conn,
1634 const char *question, char **answer,
1635 const char **errmsg)
1637 const node_t *node;
1638 const routerinfo_t *ri = NULL;
1639 (void) control_conn;
1640 if (!strcmpstart(question, "desc/id/")) {
1641 node = node_get_by_hex_id(question+strlen("desc/id/"));
1642 if (node)
1643 ri = node->ri;
1644 if (ri) {
1645 const char *body = signed_descriptor_get_body(&ri->cache_info);
1646 if (body)
1647 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1649 } else if (!strcmpstart(question, "desc/name/")) {
1650 /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
1651 * warning goes to the user, not to the controller. */
1652 node = node_get_by_nickname(question+strlen("desc/name/"), 1);
1653 if (node)
1654 ri = node->ri;
1655 if (ri) {
1656 const char *body = signed_descriptor_get_body(&ri->cache_info);
1657 if (body)
1658 *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
1660 } else if (!strcmp(question, "desc/all-recent")) {
1661 routerlist_t *routerlist = router_get_routerlist();
1662 smartlist_t *sl = smartlist_new();
1663 if (routerlist && routerlist->routers) {
1664 SMARTLIST_FOREACH(routerlist->routers, const routerinfo_t *, ri,
1666 const char *body = signed_descriptor_get_body(&ri->cache_info);
1667 if (body)
1668 smartlist_add(sl,
1669 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1672 *answer = smartlist_join_strings(sl, "", 0, NULL);
1673 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1674 smartlist_free(sl);
1675 } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
1676 /* XXXX Remove this once Torstat asks for extrainfos. */
1677 routerlist_t *routerlist = router_get_routerlist();
1678 smartlist_t *sl = smartlist_new();
1679 if (routerlist && routerlist->routers) {
1680 SMARTLIST_FOREACH_BEGIN(routerlist->routers, const routerinfo_t *, ri) {
1681 const char *body = signed_descriptor_get_body(&ri->cache_info);
1682 signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
1683 ri->cache_info.extra_info_digest);
1684 if (ei && body) {
1685 smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
1686 &ri->cache_info, ei));
1687 } else if (body) {
1688 smartlist_add(sl,
1689 tor_strndup(body, ri->cache_info.signed_descriptor_len));
1691 } SMARTLIST_FOREACH_END(ri);
1693 *answer = smartlist_join_strings(sl, "", 0, NULL);
1694 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1695 smartlist_free(sl);
1696 } else if (!strcmpstart(question, "md/id/")) {
1697 const node_t *node = node_get_by_hex_id(question+strlen("md/id/"));
1698 const microdesc_t *md = NULL;
1699 if (node) md = node->md;
1700 if (md && md->body) {
1701 *answer = tor_strndup(md->body, md->bodylen);
1703 } else if (!strcmpstart(question, "md/name/")) {
1704 /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
1705 * warning goes to the user, not to the controller. */
1706 const node_t *node = node_get_by_nickname(question+strlen("md/name/"), 1);
1707 /* XXXX duplicated code */
1708 const microdesc_t *md = NULL;
1709 if (node) md = node->md;
1710 if (md && md->body) {
1711 *answer = tor_strndup(md->body, md->bodylen);
1713 } else if (!strcmpstart(question, "desc-annotations/id/")) {
1714 node = node_get_by_hex_id(question+strlen("desc-annotations/id/"));
1715 if (node)
1716 ri = node->ri;
1717 if (ri) {
1718 const char *annotations =
1719 signed_descriptor_get_annotations(&ri->cache_info);
1720 if (annotations)
1721 *answer = tor_strndup(annotations,
1722 ri->cache_info.annotations_len);
1724 } else if (!strcmpstart(question, "dir/server/")) {
1725 size_t answer_len = 0;
1726 char *url = NULL;
1727 smartlist_t *descs = smartlist_new();
1728 const char *msg;
1729 int res;
1730 char *cp;
1731 tor_asprintf(&url, "/tor/%s", question+4);
1732 res = dirserv_get_routerdescs(descs, url, &msg);
1733 if (res) {
1734 log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
1735 smartlist_free(descs);
1736 tor_free(url);
1737 *errmsg = msg;
1738 return -1;
1740 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1741 answer_len += sd->signed_descriptor_len);
1742 cp = *answer = tor_malloc(answer_len+1);
1743 SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
1745 memcpy(cp, signed_descriptor_get_body(sd),
1746 sd->signed_descriptor_len);
1747 cp += sd->signed_descriptor_len;
1749 *cp = '\0';
1750 tor_free(url);
1751 smartlist_free(descs);
1752 } else if (!strcmpstart(question, "dir/status/")) {
1753 *answer = tor_strdup("");
1754 } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
1755 if (directory_caches_dir_info(get_options())) {
1756 const cached_dir_t *consensus = dirserv_get_consensus("ns");
1757 if (consensus)
1758 *answer = tor_strdup(consensus->dir);
1760 if (!*answer) { /* try loading it from disk */
1761 char *filename = get_datadir_fname("cached-consensus");
1762 *answer = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
1763 tor_free(filename);
1765 } else if (!strcmp(question, "network-status")) { /* v1 */
1766 routerlist_t *routerlist = router_get_routerlist();
1767 if (!routerlist || !routerlist->routers ||
1768 list_server_status_v1(routerlist->routers, answer, 1) < 0) {
1769 return -1;
1771 } else if (!strcmpstart(question, "extra-info/digest/")) {
1772 question += strlen("extra-info/digest/");
1773 if (strlen(question) == HEX_DIGEST_LEN) {
1774 char d[DIGEST_LEN];
1775 signed_descriptor_t *sd = NULL;
1776 if (base16_decode(d, sizeof(d), question, strlen(question))==0) {
1777 /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
1778 * but I don't want to risk affecting other parts of the code,
1779 * especially since the rules for using our own extrainfo (including
1780 * when it might be freed) are different from those for using one
1781 * we have downloaded. */
1782 if (router_extrainfo_digest_is_me(d))
1783 sd = &(router_get_my_extrainfo()->cache_info);
1784 else
1785 sd = extrainfo_get_by_descriptor_digest(d);
1787 if (sd) {
1788 const char *body = signed_descriptor_get_body(sd);
1789 if (body)
1790 *answer = tor_strndup(body, sd->signed_descriptor_len);
1795 return 0;
1798 /** Allocate and return a description of <b>circ</b>'s current status,
1799 * including its path (if any). */
1800 static char *
1801 circuit_describe_status_for_controller(origin_circuit_t *circ)
1803 char *rv;
1804 smartlist_t *descparts = smartlist_new();
1807 char *vpath = circuit_list_path_for_controller(circ);
1808 if (*vpath) {
1809 smartlist_add(descparts, vpath);
1810 } else {
1811 tor_free(vpath); /* empty path; don't put an extra space in the result */
1816 cpath_build_state_t *build_state = circ->build_state;
1817 smartlist_t *flaglist = smartlist_new();
1818 char *flaglist_joined;
1820 if (build_state->onehop_tunnel)
1821 smartlist_add(flaglist, (void *)"ONEHOP_TUNNEL");
1822 if (build_state->is_internal)
1823 smartlist_add(flaglist, (void *)"IS_INTERNAL");
1824 if (build_state->need_capacity)
1825 smartlist_add(flaglist, (void *)"NEED_CAPACITY");
1826 if (build_state->need_uptime)
1827 smartlist_add(flaglist, (void *)"NEED_UPTIME");
1829 /* Only emit a BUILD_FLAGS argument if it will have a non-empty value. */
1830 if (smartlist_len(flaglist)) {
1831 flaglist_joined = smartlist_join_strings(flaglist, ",", 0, NULL);
1833 smartlist_add_asprintf(descparts, "BUILD_FLAGS=%s", flaglist_joined);
1835 tor_free(flaglist_joined);
1838 smartlist_free(flaglist);
1841 smartlist_add_asprintf(descparts, "PURPOSE=%s",
1842 circuit_purpose_to_controller_string(circ->base_.purpose));
1845 const char *hs_state =
1846 circuit_purpose_to_controller_hs_state_string(circ->base_.purpose);
1848 if (hs_state != NULL) {
1849 smartlist_add_asprintf(descparts, "HS_STATE=%s", hs_state);
1853 if (circ->rend_data != NULL) {
1854 smartlist_add_asprintf(descparts, "REND_QUERY=%s",
1855 circ->rend_data->onion_address);
1859 char tbuf[ISO_TIME_USEC_LEN+1];
1860 format_iso_time_nospace_usec(tbuf, &circ->base_.timestamp_created);
1862 smartlist_add_asprintf(descparts, "TIME_CREATED=%s", tbuf);
1865 rv = smartlist_join_strings(descparts, " ", 0, NULL);
1867 SMARTLIST_FOREACH(descparts, char *, cp, tor_free(cp));
1868 smartlist_free(descparts);
1870 return rv;
1873 /** Implementation helper for GETINFO: knows how to generate summaries of the
1874 * current states of things we send events about. */
1875 static int
1876 getinfo_helper_events(control_connection_t *control_conn,
1877 const char *question, char **answer,
1878 const char **errmsg)
1880 (void) control_conn;
1881 if (!strcmp(question, "circuit-status")) {
1882 circuit_t *circ_;
1883 smartlist_t *status = smartlist_new();
1884 TOR_LIST_FOREACH(circ_, circuit_get_global_list(), head) {
1885 origin_circuit_t *circ;
1886 char *circdesc;
1887 const char *state;
1888 if (! CIRCUIT_IS_ORIGIN(circ_) || circ_->marked_for_close)
1889 continue;
1890 circ = TO_ORIGIN_CIRCUIT(circ_);
1892 if (circ->base_.state == CIRCUIT_STATE_OPEN)
1893 state = "BUILT";
1894 else if (circ->cpath)
1895 state = "EXTENDED";
1896 else
1897 state = "LAUNCHED";
1899 circdesc = circuit_describe_status_for_controller(circ);
1901 smartlist_add_asprintf(status, "%lu %s%s%s",
1902 (unsigned long)circ->global_identifier,
1903 state, *circdesc ? " " : "", circdesc);
1904 tor_free(circdesc);
1906 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1907 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1908 smartlist_free(status);
1909 } else if (!strcmp(question, "stream-status")) {
1910 smartlist_t *conns = get_connection_array();
1911 smartlist_t *status = smartlist_new();
1912 char buf[256];
1913 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1914 const char *state;
1915 entry_connection_t *conn;
1916 circuit_t *circ;
1917 origin_circuit_t *origin_circ = NULL;
1918 if (base_conn->type != CONN_TYPE_AP ||
1919 base_conn->marked_for_close ||
1920 base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
1921 base_conn->state == AP_CONN_STATE_NATD_WAIT)
1922 continue;
1923 conn = TO_ENTRY_CONN(base_conn);
1924 switch (base_conn->state)
1926 case AP_CONN_STATE_CONTROLLER_WAIT:
1927 case AP_CONN_STATE_CIRCUIT_WAIT:
1928 if (conn->socks_request &&
1929 SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
1930 state = "NEWRESOLVE";
1931 else
1932 state = "NEW";
1933 break;
1934 case AP_CONN_STATE_RENDDESC_WAIT:
1935 case AP_CONN_STATE_CONNECT_WAIT:
1936 state = "SENTCONNECT"; break;
1937 case AP_CONN_STATE_RESOLVE_WAIT:
1938 state = "SENTRESOLVE"; break;
1939 case AP_CONN_STATE_OPEN:
1940 state = "SUCCEEDED"; break;
1941 default:
1942 log_warn(LD_BUG, "Asked for stream in unknown state %d",
1943 base_conn->state);
1944 continue;
1946 circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
1947 if (circ && CIRCUIT_IS_ORIGIN(circ))
1948 origin_circ = TO_ORIGIN_CIRCUIT(circ);
1949 write_stream_target_to_buf(conn, buf, sizeof(buf));
1950 smartlist_add_asprintf(status, "%lu %s %lu %s",
1951 (unsigned long) base_conn->global_identifier,state,
1952 origin_circ?
1953 (unsigned long)origin_circ->global_identifier : 0ul,
1954 buf);
1955 } SMARTLIST_FOREACH_END(base_conn);
1956 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1957 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1958 smartlist_free(status);
1959 } else if (!strcmp(question, "orconn-status")) {
1960 smartlist_t *conns = get_connection_array();
1961 smartlist_t *status = smartlist_new();
1962 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1963 const char *state;
1964 char name[128];
1965 or_connection_t *conn;
1966 if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
1967 continue;
1968 conn = TO_OR_CONN(base_conn);
1969 if (conn->base_.state == OR_CONN_STATE_OPEN)
1970 state = "CONNECTED";
1971 else if (conn->nickname)
1972 state = "LAUNCHED";
1973 else
1974 state = "NEW";
1975 orconn_target_get_name(name, sizeof(name), conn);
1976 smartlist_add_asprintf(status, "%s %s", name, state);
1977 } SMARTLIST_FOREACH_END(base_conn);
1978 *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
1979 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1980 smartlist_free(status);
1981 } else if (!strcmpstart(question, "address-mappings/")) {
1982 time_t min_e, max_e;
1983 smartlist_t *mappings;
1984 question += strlen("address-mappings/");
1985 if (!strcmp(question, "all")) {
1986 min_e = 0; max_e = TIME_MAX;
1987 } else if (!strcmp(question, "cache")) {
1988 min_e = 2; max_e = TIME_MAX;
1989 } else if (!strcmp(question, "config")) {
1990 min_e = 0; max_e = 0;
1991 } else if (!strcmp(question, "control")) {
1992 min_e = 1; max_e = 1;
1993 } else {
1994 return 0;
1996 mappings = smartlist_new();
1997 addressmap_get_mappings(mappings, min_e, max_e, 1);
1998 *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
1999 SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
2000 smartlist_free(mappings);
2001 } else if (!strcmpstart(question, "status/")) {
2002 /* Note that status/ is not a catch-all for events; there's only supposed
2003 * to be a status GETINFO if there's a corresponding STATUS event. */
2004 if (!strcmp(question, "status/circuit-established")) {
2005 *answer = tor_strdup(can_complete_circuit ? "1" : "0");
2006 } else if (!strcmp(question, "status/enough-dir-info")) {
2007 *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
2008 } else if (!strcmp(question, "status/good-server-descriptor") ||
2009 !strcmp(question, "status/accepted-server-descriptor")) {
2010 /* They're equivalent for now, until we can figure out how to make
2011 * good-server-descriptor be what we want. See comment in
2012 * control-spec.txt. */
2013 *answer = tor_strdup(directories_have_accepted_server_descriptor()
2014 ? "1" : "0");
2015 } else if (!strcmp(question, "status/reachability-succeeded/or")) {
2016 *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
2017 } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
2018 *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
2019 } else if (!strcmp(question, "status/reachability-succeeded")) {
2020 tor_asprintf(answer, "OR=%d DIR=%d",
2021 check_whether_orport_reachable() ? 1 : 0,
2022 check_whether_dirport_reachable() ? 1 : 0);
2023 } else if (!strcmp(question, "status/bootstrap-phase")) {
2024 *answer = tor_strdup(last_sent_bootstrap_message);
2025 } else if (!strcmpstart(question, "status/version/")) {
2026 int is_server = server_mode(get_options());
2027 networkstatus_t *c = networkstatus_get_latest_consensus();
2028 version_status_t status;
2029 const char *recommended;
2030 if (c) {
2031 recommended = is_server ? c->server_versions : c->client_versions;
2032 status = tor_version_is_obsolete(VERSION, recommended);
2033 } else {
2034 recommended = "?";
2035 status = VS_UNKNOWN;
2038 if (!strcmp(question, "status/version/recommended")) {
2039 *answer = tor_strdup(recommended);
2040 return 0;
2042 if (!strcmp(question, "status/version/current")) {
2043 switch (status)
2045 case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
2046 case VS_OLD: *answer = tor_strdup("obsolete"); break;
2047 case VS_NEW: *answer = tor_strdup("new"); break;
2048 case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
2049 case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
2050 case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
2051 case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
2052 default: tor_fragile_assert();
2054 } else if (!strcmp(question, "status/version/num-versioning") ||
2055 !strcmp(question, "status/version/num-concurring")) {
2056 tor_asprintf(answer, "%d", get_n_authorities(V3_DIRINFO));
2057 log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
2058 "information", question);
2060 } else if (!strcmp(question, "status/clients-seen")) {
2061 char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
2062 if (!bridge_stats) {
2063 *errmsg = "No bridge-client stats available";
2064 return -1;
2066 *answer = bridge_stats;
2067 } else {
2068 return 0;
2071 return 0;
2074 /** Callback function for GETINFO: on a given control connection, try to
2075 * answer the question <b>q</b> and store the newly-allocated answer in
2076 * *<b>a</b>. If an internal error occurs, return -1 and optionally set
2077 * *<b>error_out</b> to point to an error message to be delivered to the
2078 * controller. On success, _or if the key is not recognized_, return 0. Do not
2079 * set <b>a</b> if the key is not recognized.
2081 typedef int (*getinfo_helper_t)(control_connection_t *,
2082 const char *q, char **a,
2083 const char **error_out);
2085 /** A single item for the GETINFO question-to-answer-function table. */
2086 typedef struct getinfo_item_t {
2087 const char *varname; /**< The value (or prefix) of the question. */
2088 getinfo_helper_t fn; /**< The function that knows the answer: NULL if
2089 * this entry is documentation-only. */
2090 const char *desc; /**< Description of the variable. */
2091 int is_prefix; /** Must varname match exactly, or must it be a prefix? */
2092 } getinfo_item_t;
2094 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
2095 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
2096 #define DOC(name, desc) { name, NULL, desc, 0 }
2098 /** Table mapping questions accepted by GETINFO to the functions that know how
2099 * to answer them. */
2100 static const getinfo_item_t getinfo_items[] = {
2101 ITEM("version", misc, "The current version of Tor."),
2102 ITEM("config-file", misc, "Current location of the \"torrc\" file."),
2103 ITEM("config-defaults-file", misc, "Current location of the defaults file."),
2104 ITEM("config-text", misc,
2105 "Return the string that would be written by a saveconf command."),
2106 ITEM("accounting/bytes", accounting,
2107 "Number of bytes read/written so far in the accounting interval."),
2108 ITEM("accounting/bytes-left", accounting,
2109 "Number of bytes left to write/read so far in the accounting interval."),
2110 ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
2111 ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
2112 ITEM("accounting/interval-start", accounting,
2113 "Time when the accounting period starts."),
2114 ITEM("accounting/interval-end", accounting,
2115 "Time when the accounting period ends."),
2116 ITEM("accounting/interval-wake", accounting,
2117 "Time to wake up in this accounting period."),
2118 ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
2119 ITEM("entry-guards", entry_guards,
2120 "Which nodes are we using as entry guards?"),
2121 ITEM("fingerprint", misc, NULL),
2122 PREFIX("config/", config, "Current configuration values."),
2123 DOC("config/names",
2124 "List of configuration options, types, and documentation."),
2125 DOC("config/defaults",
2126 "List of default values for configuration options. "
2127 "See also config/names"),
2128 ITEM("info/names", misc,
2129 "List of GETINFO options, types, and documentation."),
2130 ITEM("events/names", misc,
2131 "Events that the controller can ask for with SETEVENTS."),
2132 ITEM("signal/names", misc, "Signal names recognized by the SIGNAL command"),
2133 ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
2134 PREFIX("desc/id/", dir, "Router descriptors by ID."),
2135 PREFIX("desc/name/", dir, "Router descriptors by nickname."),
2136 ITEM("desc/all-recent", dir,
2137 "All non-expired, non-superseded router descriptors."),
2138 ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
2139 PREFIX("md/id/", dir, "Microdescriptors by ID"),
2140 PREFIX("md/name/", dir, "Microdescriptors by name"),
2141 PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
2142 PREFIX("net/listeners/", listeners, "Bound addresses by type"),
2143 ITEM("ns/all", networkstatus,
2144 "Brief summary of router status (v2 directory format)"),
2145 PREFIX("ns/id/", networkstatus,
2146 "Brief summary of router status by ID (v2 directory format)."),
2147 PREFIX("ns/name/", networkstatus,
2148 "Brief summary of router status by nickname (v2 directory format)."),
2149 PREFIX("ns/purpose/", networkstatus,
2150 "Brief summary of router status by purpose (v2 directory format)."),
2151 ITEM("network-status", dir,
2152 "Brief summary of router status (v1 directory format)"),
2153 ITEM("circuit-status", events, "List of current circuits originating here."),
2154 ITEM("stream-status", events,"List of current streams."),
2155 ITEM("orconn-status", events, "A list of current OR connections."),
2156 ITEM("dormant", misc,
2157 "Is Tor dormant (not building circuits because it's idle)?"),
2158 PREFIX("address-mappings/", events, NULL),
2159 DOC("address-mappings/all", "Current address mappings."),
2160 DOC("address-mappings/cache", "Current cached DNS replies."),
2161 DOC("address-mappings/config",
2162 "Current address mappings from configuration."),
2163 DOC("address-mappings/control", "Current address mappings from controller."),
2164 PREFIX("status/", events, NULL),
2165 DOC("status/circuit-established",
2166 "Whether we think client functionality is working."),
2167 DOC("status/enough-dir-info",
2168 "Whether we have enough up-to-date directory information to build "
2169 "circuits."),
2170 DOC("status/bootstrap-phase",
2171 "The last bootstrap phase status event that Tor sent."),
2172 DOC("status/clients-seen",
2173 "Breakdown of client countries seen by a bridge."),
2174 DOC("status/version/recommended", "List of currently recommended versions."),
2175 DOC("status/version/current", "Status of the current version."),
2176 DOC("status/version/num-versioning", "Number of versioning authorities."),
2177 DOC("status/version/num-concurring",
2178 "Number of versioning authorities agreeing on the status of the "
2179 "current version"),
2180 ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
2181 ITEM("traffic/read", misc,"Bytes read since the process was started."),
2182 ITEM("traffic/written", misc,
2183 "Bytes written since the process was started."),
2184 ITEM("process/pid", misc, "Process id belonging to the main tor process."),
2185 ITEM("process/uid", misc, "User id running the tor process."),
2186 ITEM("process/user", misc,
2187 "Username under which the tor process is running."),
2188 ITEM("process/descriptor-limit", misc, "File descriptor limit."),
2189 ITEM("limits/max-mem-in-queues", misc, "Actual limit on memory in queues"),
2190 ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
2191 PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
2192 PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
2193 PREFIX("dir/status/", dir,
2194 "v2 networkstatus docs as retrieved from a DirPort."),
2195 ITEM("dir/status-vote/current/consensus", dir,
2196 "v3 Networkstatus consensus as retrieved from a DirPort."),
2197 ITEM("exit-policy/default", policies,
2198 "The default value appended to the configured exit policy."),
2199 ITEM("exit-policy/full", policies, "The entire exit policy of onion router"),
2200 ITEM("exit-policy/ipv4", policies, "IPv4 parts of exit policy"),
2201 ITEM("exit-policy/ipv6", policies, "IPv6 parts of exit policy"),
2202 PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
2203 { NULL, NULL, NULL, 0 }
2206 /** Allocate and return a list of recognized GETINFO options. */
2207 static char *
2208 list_getinfo_options(void)
2210 int i;
2211 smartlist_t *lines = smartlist_new();
2212 char *ans;
2213 for (i = 0; getinfo_items[i].varname; ++i) {
2214 if (!getinfo_items[i].desc)
2215 continue;
2217 smartlist_add_asprintf(lines, "%s%s -- %s\n",
2218 getinfo_items[i].varname,
2219 getinfo_items[i].is_prefix ? "*" : "",
2220 getinfo_items[i].desc);
2222 smartlist_sort_strings(lines);
2224 ans = smartlist_join_strings(lines, "", 0, NULL);
2225 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
2226 smartlist_free(lines);
2228 return ans;
2231 /** Lookup the 'getinfo' entry <b>question</b>, and return
2232 * the answer in <b>*answer</b> (or NULL if key not recognized).
2233 * Return 0 if success or unrecognized, or -1 if recognized but
2234 * internal error. */
2235 static int
2236 handle_getinfo_helper(control_connection_t *control_conn,
2237 const char *question, char **answer,
2238 const char **err_out)
2240 int i;
2241 *answer = NULL; /* unrecognized key by default */
2243 for (i = 0; getinfo_items[i].varname; ++i) {
2244 int match;
2245 if (getinfo_items[i].is_prefix)
2246 match = !strcmpstart(question, getinfo_items[i].varname);
2247 else
2248 match = !strcmp(question, getinfo_items[i].varname);
2249 if (match) {
2250 tor_assert(getinfo_items[i].fn);
2251 return getinfo_items[i].fn(control_conn, question, answer, err_out);
2255 return 0; /* unrecognized */
2258 /** Called when we receive a GETINFO command. Try to fetch all requested
2259 * information, and reply with information or error message. */
2260 static int
2261 handle_control_getinfo(control_connection_t *conn, uint32_t len,
2262 const char *body)
2264 smartlist_t *questions = smartlist_new();
2265 smartlist_t *answers = smartlist_new();
2266 smartlist_t *unrecognized = smartlist_new();
2267 char *msg = NULL, *ans = NULL;
2268 int i;
2269 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
2271 smartlist_split_string(questions, body, " ",
2272 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2273 SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
2274 const char *errmsg = NULL;
2275 if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
2276 if (!errmsg)
2277 errmsg = "Internal error";
2278 connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
2279 goto done;
2281 if (!ans) {
2282 smartlist_add(unrecognized, (char*)q);
2283 } else {
2284 smartlist_add(answers, tor_strdup(q));
2285 smartlist_add(answers, ans);
2287 } SMARTLIST_FOREACH_END(q);
2288 if (smartlist_len(unrecognized)) {
2289 for (i=0; i < smartlist_len(unrecognized)-1; ++i)
2290 connection_printf_to_buf(conn,
2291 "552-Unrecognized key \"%s\"\r\n",
2292 (char*)smartlist_get(unrecognized, i));
2293 connection_printf_to_buf(conn,
2294 "552 Unrecognized key \"%s\"\r\n",
2295 (char*)smartlist_get(unrecognized, i));
2296 goto done;
2299 for (i = 0; i < smartlist_len(answers); i += 2) {
2300 char *k = smartlist_get(answers, i);
2301 char *v = smartlist_get(answers, i+1);
2302 if (!strchr(v, '\n') && !strchr(v, '\r')) {
2303 connection_printf_to_buf(conn, "250-%s=", k);
2304 connection_write_str_to_buf(v, conn);
2305 connection_write_str_to_buf("\r\n", conn);
2306 } else {
2307 char *esc = NULL;
2308 size_t esc_len;
2309 esc_len = write_escaped_data(v, strlen(v), &esc);
2310 connection_printf_to_buf(conn, "250+%s=\r\n", k);
2311 connection_write_to_buf(esc, esc_len, TO_CONN(conn));
2312 tor_free(esc);
2315 connection_write_str_to_buf("250 OK\r\n", conn);
2317 done:
2318 SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
2319 smartlist_free(answers);
2320 SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
2321 smartlist_free(questions);
2322 smartlist_free(unrecognized);
2323 tor_free(msg);
2325 return 0;
2328 /** Given a string, convert it to a circuit purpose. */
2329 static uint8_t
2330 circuit_purpose_from_string(const char *string)
2332 if (!strcasecmpstart(string, "purpose="))
2333 string += strlen("purpose=");
2335 if (!strcasecmp(string, "general"))
2336 return CIRCUIT_PURPOSE_C_GENERAL;
2337 else if (!strcasecmp(string, "controller"))
2338 return CIRCUIT_PURPOSE_CONTROLLER;
2339 else
2340 return CIRCUIT_PURPOSE_UNKNOWN;
2343 /** Return a newly allocated smartlist containing the arguments to the command
2344 * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
2345 * or if <b>max_args</b> is nonnegative and there are more than
2346 * <b>max_args</b> arguments, send a 512 error to the controller, using
2347 * <b>command</b> as the command name in the error message. */
2348 static smartlist_t *
2349 getargs_helper(const char *command, control_connection_t *conn,
2350 const char *body, int min_args, int max_args)
2352 smartlist_t *args = smartlist_new();
2353 smartlist_split_string(args, body, " ",
2354 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2355 if (smartlist_len(args) < min_args) {
2356 connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
2357 goto err;
2358 } else if (max_args >= 0 && smartlist_len(args) > max_args) {
2359 connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
2360 goto err;
2362 return args;
2363 err:
2364 SMARTLIST_FOREACH(args, char *, s, tor_free(s));
2365 smartlist_free(args);
2366 return NULL;
2369 /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
2370 * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
2371 * such element exists. */
2372 static const char *
2373 find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
2375 int i;
2376 for (i = start_at; i < smartlist_len(sl); ++i) {
2377 const char *elt = smartlist_get(sl, i);
2378 if (!strcasecmpstart(elt, prefix))
2379 return elt;
2381 return NULL;
2384 /** Helper. Return true iff s is an argument that we should treat as a
2385 * key-value pair. */
2386 static int
2387 is_keyval_pair(const char *s)
2389 /* An argument is a key-value pair if it has an =, and it isn't of the form
2390 * $fingeprint=name */
2391 return strchr(s, '=') && s[0] != '$';
2394 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
2395 * circuit, and report success or failure. */
2396 static int
2397 handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
2398 const char *body)
2400 smartlist_t *router_nicknames=NULL, *nodes=NULL;
2401 origin_circuit_t *circ = NULL;
2402 int zero_circ;
2403 uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
2404 smartlist_t *args;
2405 (void) len;
2407 router_nicknames = smartlist_new();
2409 args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
2410 if (!args)
2411 goto done;
2413 zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
2415 if (zero_circ) {
2416 const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
2418 if (purp) {
2419 intended_purpose = circuit_purpose_from_string(purp);
2420 if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
2421 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
2422 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2423 smartlist_free(args);
2424 goto done;
2428 if ((smartlist_len(args) == 1) ||
2429 (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
2430 // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
2431 circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
2432 if (!circ) {
2433 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
2434 } else {
2435 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
2436 (unsigned long)circ->global_identifier);
2438 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2439 smartlist_free(args);
2440 goto done;
2442 // "EXTENDCIRCUIT 0 router1,router2" ||
2443 // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
2446 if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
2447 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2448 (char*)smartlist_get(args, 0));
2449 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2450 smartlist_free(args);
2451 goto done;
2454 smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
2456 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2457 smartlist_free(args);
2459 nodes = smartlist_new();
2460 SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
2461 const node_t *node = node_get_by_nickname(n, 1);
2462 if (!node) {
2463 connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
2464 goto done;
2466 if (!node_has_descriptor(node)) {
2467 connection_printf_to_buf(conn, "552 No descriptor for \"%s\"\r\n", n);
2468 goto done;
2470 smartlist_add(nodes, (void*)node);
2471 } SMARTLIST_FOREACH_END(n);
2472 if (!smartlist_len(nodes)) {
2473 connection_write_str_to_buf("512 No router names provided\r\n", conn);
2474 goto done;
2477 if (zero_circ) {
2478 /* start a new circuit */
2479 circ = origin_circuit_init(intended_purpose, 0);
2482 /* now circ refers to something that is ready to be extended */
2483 SMARTLIST_FOREACH(nodes, const node_t *, node,
2485 extend_info_t *info = extend_info_from_node(node, 0);
2486 tor_assert(info); /* True, since node_has_descriptor(node) == true */
2487 circuit_append_new_exit(circ, info);
2488 extend_info_free(info);
2491 /* now that we've populated the cpath, start extending */
2492 if (zero_circ) {
2493 int err_reason = 0;
2494 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
2495 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2496 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
2497 goto done;
2499 } else {
2500 if (circ->base_.state == CIRCUIT_STATE_OPEN) {
2501 int err_reason = 0;
2502 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
2503 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
2504 log_info(LD_CONTROL,
2505 "send_next_onion_skin failed; circuit marked for closing.");
2506 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2507 connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
2508 goto done;
2513 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
2514 (unsigned long)circ->global_identifier);
2515 if (zero_circ) /* send a 'launched' event, for completeness */
2516 control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
2517 done:
2518 SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
2519 smartlist_free(router_nicknames);
2520 smartlist_free(nodes);
2521 return 0;
2524 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
2525 * circuit and it's a valid purpose, change it. */
2526 static int
2527 handle_control_setcircuitpurpose(control_connection_t *conn,
2528 uint32_t len, const char *body)
2530 origin_circuit_t *circ = NULL;
2531 uint8_t new_purpose;
2532 smartlist_t *args;
2533 (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
2535 args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
2536 if (!args)
2537 goto done;
2539 if (!(circ = get_circ(smartlist_get(args,0)))) {
2540 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2541 (char*)smartlist_get(args, 0));
2542 goto done;
2546 const char *purp = find_element_starting_with(args,1,"PURPOSE=");
2547 if (!purp) {
2548 connection_write_str_to_buf("552 No purpose given\r\n", conn);
2549 goto done;
2551 new_purpose = circuit_purpose_from_string(purp);
2552 if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
2553 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
2554 goto done;
2558 circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
2559 connection_write_str_to_buf("250 OK\r\n", conn);
2561 done:
2562 if (args) {
2563 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2564 smartlist_free(args);
2566 return 0;
2569 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
2570 * stream, and report success or failure. */
2571 static int
2572 handle_control_attachstream(control_connection_t *conn, uint32_t len,
2573 const char *body)
2575 entry_connection_t *ap_conn = NULL;
2576 origin_circuit_t *circ = NULL;
2577 int zero_circ;
2578 smartlist_t *args;
2579 crypt_path_t *cpath=NULL;
2580 int hop=0, hop_line_ok=1;
2581 (void) len;
2583 args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
2584 if (!args)
2585 return 0;
2587 zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
2589 if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
2590 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2591 (char*)smartlist_get(args, 0));
2592 } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
2593 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2594 (char*)smartlist_get(args, 1));
2595 } else if (circ) {
2596 const char *hopstring = find_element_starting_with(args,2,"HOP=");
2597 if (hopstring) {
2598 hopstring += strlen("HOP=");
2599 hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
2600 &hop_line_ok, NULL);
2601 if (!hop_line_ok) { /* broken hop line */
2602 connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
2606 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2607 smartlist_free(args);
2608 if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
2609 return 0;
2611 if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
2612 ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
2613 ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
2614 connection_write_str_to_buf(
2615 "555 Connection is not managed by controller.\r\n",
2616 conn);
2617 return 0;
2620 /* Do we need to detach it first? */
2621 if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
2622 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
2623 circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
2624 connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
2625 /* Un-mark it as ending, since we're going to reuse it. */
2626 edge_conn->edge_has_sent_end = 0;
2627 edge_conn->end_reason = 0;
2628 if (tmpcirc)
2629 circuit_detach_stream(tmpcirc, edge_conn);
2630 TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
2633 if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
2634 connection_write_str_to_buf(
2635 "551 Can't attach stream to non-open origin circuit\r\n",
2636 conn);
2637 return 0;
2639 /* Is this a single hop circuit? */
2640 if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
2641 const node_t *node = NULL;
2642 char *exit_digest = NULL;
2643 if (circ->build_state &&
2644 circ->build_state->chosen_exit &&
2645 !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
2646 exit_digest = circ->build_state->chosen_exit->identity_digest;
2647 node = node_get_by_id(exit_digest);
2649 /* Do both the client and relay allow one-hop exit circuits? */
2650 if (!node ||
2651 !node_allows_single_hop_exits(node) ||
2652 !get_options()->AllowSingleHopCircuits) {
2653 connection_write_str_to_buf(
2654 "551 Can't attach stream to this one-hop circuit.\r\n", conn);
2655 return 0;
2657 tor_assert(exit_digest);
2658 ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
2661 if (circ && hop>0) {
2662 /* find this hop in the circuit, and set cpath */
2663 cpath = circuit_get_cpath_hop(circ, hop);
2664 if (!cpath) {
2665 connection_printf_to_buf(conn,
2666 "551 Circuit doesn't have %d hops.\r\n", hop);
2667 return 0;
2670 if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
2671 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
2672 return 0;
2674 send_control_done(conn);
2675 return 0;
2678 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
2679 * descriptor, and report success or failure. */
2680 static int
2681 handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
2682 const char *body)
2684 char *desc;
2685 const char *msg=NULL;
2686 uint8_t purpose = ROUTER_PURPOSE_GENERAL;
2687 int cache = 0; /* eventually, we may switch this to 1 */
2689 char *cp = memchr(body, '\n', len);
2690 smartlist_t *args = smartlist_new();
2691 tor_assert(cp);
2692 *cp++ = '\0';
2694 smartlist_split_string(args, body, " ",
2695 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2696 SMARTLIST_FOREACH_BEGIN(args, char *, option) {
2697 if (!strcasecmpstart(option, "purpose=")) {
2698 option += strlen("purpose=");
2699 purpose = router_purpose_from_string(option);
2700 if (purpose == ROUTER_PURPOSE_UNKNOWN) {
2701 connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
2702 option);
2703 goto done;
2705 } else if (!strcasecmpstart(option, "cache=")) {
2706 option += strlen("cache=");
2707 if (!strcasecmp(option, "no"))
2708 cache = 0;
2709 else if (!strcasecmp(option, "yes"))
2710 cache = 1;
2711 else {
2712 connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
2713 option);
2714 goto done;
2716 } else { /* unrecognized argument? */
2717 connection_printf_to_buf(conn,
2718 "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
2719 goto done;
2721 } SMARTLIST_FOREACH_END(option);
2723 read_escaped_data(cp, len-(cp-body), &desc);
2725 switch (router_load_single_router(desc, purpose, cache, &msg)) {
2726 case -1:
2727 if (!msg) msg = "Could not parse descriptor";
2728 connection_printf_to_buf(conn, "554 %s\r\n", msg);
2729 break;
2730 case 0:
2731 if (!msg) msg = "Descriptor not added";
2732 connection_printf_to_buf(conn, "251 %s\r\n",msg);
2733 break;
2734 case 1:
2735 send_control_done(conn);
2736 break;
2739 tor_free(desc);
2740 done:
2741 SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
2742 smartlist_free(args);
2743 return 0;
2746 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
2747 * address of the named AP stream, and report success or failure. */
2748 static int
2749 handle_control_redirectstream(control_connection_t *conn, uint32_t len,
2750 const char *body)
2752 entry_connection_t *ap_conn = NULL;
2753 char *new_addr = NULL;
2754 uint16_t new_port = 0;
2755 smartlist_t *args;
2756 (void) len;
2758 args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
2759 if (!args)
2760 return 0;
2762 if (!(ap_conn = get_stream(smartlist_get(args, 0)))
2763 || !ap_conn->socks_request) {
2764 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2765 (char*)smartlist_get(args, 0));
2766 } else {
2767 int ok = 1;
2768 if (smartlist_len(args) > 2) { /* they included a port too */
2769 new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
2770 10, 1, 65535, &ok, NULL);
2772 if (!ok) {
2773 connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
2774 (char*)smartlist_get(args, 2));
2775 } else {
2776 new_addr = tor_strdup(smartlist_get(args, 1));
2780 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2781 smartlist_free(args);
2782 if (!new_addr)
2783 return 0;
2785 strlcpy(ap_conn->socks_request->address, new_addr,
2786 sizeof(ap_conn->socks_request->address));
2787 if (new_port)
2788 ap_conn->socks_request->port = new_port;
2789 tor_free(new_addr);
2790 send_control_done(conn);
2791 return 0;
2794 /** Called when we get a CLOSESTREAM command; try to close the named stream
2795 * and report success or failure. */
2796 static int
2797 handle_control_closestream(control_connection_t *conn, uint32_t len,
2798 const char *body)
2800 entry_connection_t *ap_conn=NULL;
2801 uint8_t reason=0;
2802 smartlist_t *args;
2803 int ok;
2804 (void) len;
2806 args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
2807 if (!args)
2808 return 0;
2810 else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
2811 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
2812 (char*)smartlist_get(args, 0));
2813 else {
2814 reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
2815 &ok, NULL);
2816 if (!ok) {
2817 connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
2818 (char*)smartlist_get(args, 1));
2819 ap_conn = NULL;
2822 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2823 smartlist_free(args);
2824 if (!ap_conn)
2825 return 0;
2827 connection_mark_unattached_ap(ap_conn, reason);
2828 send_control_done(conn);
2829 return 0;
2832 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
2833 * and report success or failure. */
2834 static int
2835 handle_control_closecircuit(control_connection_t *conn, uint32_t len,
2836 const char *body)
2838 origin_circuit_t *circ = NULL;
2839 int safe = 0;
2840 smartlist_t *args;
2841 (void) len;
2843 args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
2844 if (!args)
2845 return 0;
2847 if (!(circ=get_circ(smartlist_get(args, 0))))
2848 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
2849 (char*)smartlist_get(args, 0));
2850 else {
2851 int i;
2852 for (i=1; i < smartlist_len(args); ++i) {
2853 if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
2854 safe = 1;
2855 else
2856 log_info(LD_CONTROL, "Skipping unknown option %s",
2857 (char*)smartlist_get(args,i));
2860 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2861 smartlist_free(args);
2862 if (!circ)
2863 return 0;
2865 if (!safe || !circ->p_streams) {
2866 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
2869 send_control_done(conn);
2870 return 0;
2873 /** Called when we get a RESOLVE command: start trying to resolve
2874 * the listed addresses. */
2875 static int
2876 handle_control_resolve(control_connection_t *conn, uint32_t len,
2877 const char *body)
2879 smartlist_t *args, *failed;
2880 int is_reverse = 0;
2881 (void) len; /* body is nul-terminated; it's safe to ignore the length */
2883 if (!(conn->event_mask & ((uint32_t)1L<<EVENT_ADDRMAP))) {
2884 log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
2885 "isn't listening for ADDRMAP events. It probably won't see "
2886 "the answer.");
2888 args = smartlist_new();
2889 smartlist_split_string(args, body, " ",
2890 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2892 const char *modearg = find_element_starting_with(args, 0, "mode=");
2893 if (modearg && !strcasecmp(modearg, "mode=reverse"))
2894 is_reverse = 1;
2896 failed = smartlist_new();
2897 SMARTLIST_FOREACH(args, const char *, arg, {
2898 if (!is_keyval_pair(arg)) {
2899 if (dnsserv_launch_request(arg, is_reverse, conn)<0)
2900 smartlist_add(failed, (char*)arg);
2904 send_control_done(conn);
2905 SMARTLIST_FOREACH(failed, const char *, arg, {
2906 control_event_address_mapped(arg, arg, time(NULL),
2907 "internal", 0);
2910 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2911 smartlist_free(args);
2912 smartlist_free(failed);
2913 return 0;
2916 /** Called when we get a PROTOCOLINFO command: send back a reply. */
2917 static int
2918 handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
2919 const char *body)
2921 const char *bad_arg = NULL;
2922 smartlist_t *args;
2923 (void)len;
2925 conn->have_sent_protocolinfo = 1;
2926 args = smartlist_new();
2927 smartlist_split_string(args, body, " ",
2928 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2929 SMARTLIST_FOREACH(args, const char *, arg, {
2930 int ok;
2931 tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
2932 if (!ok) {
2933 bad_arg = arg;
2934 break;
2937 if (bad_arg) {
2938 connection_printf_to_buf(conn, "513 No such version %s\r\n",
2939 escaped(bad_arg));
2940 /* Don't tolerate bad arguments when not authenticated. */
2941 if (!STATE_IS_OPEN(TO_CONN(conn)->state))
2942 connection_mark_for_close(TO_CONN(conn));
2943 goto done;
2944 } else {
2945 const or_options_t *options = get_options();
2946 int cookies = options->CookieAuthentication;
2947 char *cfile = get_controller_cookie_file_name();
2948 char *abs_cfile;
2949 char *esc_cfile;
2950 char *methods;
2951 abs_cfile = make_path_absolute(cfile);
2952 esc_cfile = esc_for_log(abs_cfile);
2954 int passwd = (options->HashedControlPassword != NULL ||
2955 options->HashedControlSessionPassword != NULL);
2956 smartlist_t *mlist = smartlist_new();
2957 if (cookies) {
2958 smartlist_add(mlist, (char*)"COOKIE");
2959 smartlist_add(mlist, (char*)"SAFECOOKIE");
2961 if (passwd)
2962 smartlist_add(mlist, (char*)"HASHEDPASSWORD");
2963 if (!cookies && !passwd)
2964 smartlist_add(mlist, (char*)"NULL");
2965 methods = smartlist_join_strings(mlist, ",", 0, NULL);
2966 smartlist_free(mlist);
2969 connection_printf_to_buf(conn,
2970 "250-PROTOCOLINFO 1\r\n"
2971 "250-AUTH METHODS=%s%s%s\r\n"
2972 "250-VERSION Tor=%s\r\n"
2973 "250 OK\r\n",
2974 methods,
2975 cookies?" COOKIEFILE=":"",
2976 cookies?esc_cfile:"",
2977 escaped(VERSION));
2978 tor_free(methods);
2979 tor_free(cfile);
2980 tor_free(abs_cfile);
2981 tor_free(esc_cfile);
2983 done:
2984 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
2985 smartlist_free(args);
2986 return 0;
2989 /** Called when we get an AUTHCHALLENGE command. */
2990 static int
2991 handle_control_authchallenge(control_connection_t *conn, uint32_t len,
2992 const char *body)
2994 const char *cp = body;
2995 char *client_nonce;
2996 size_t client_nonce_len;
2997 char server_hash[DIGEST256_LEN];
2998 char server_hash_encoded[HEX_DIGEST256_LEN+1];
2999 char server_nonce[SAFECOOKIE_SERVER_NONCE_LEN];
3000 char server_nonce_encoded[(2*SAFECOOKIE_SERVER_NONCE_LEN) + 1];
3002 cp += strspn(cp, " \t\n\r");
3003 if (!strcasecmpstart(cp, "SAFECOOKIE")) {
3004 cp += strlen("SAFECOOKIE");
3005 } else {
3006 connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
3007 "authentication\r\n", conn);
3008 connection_mark_for_close(TO_CONN(conn));
3009 return -1;
3012 if (!authentication_cookie_is_set) {
3013 connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
3014 conn);
3015 connection_mark_for_close(TO_CONN(conn));
3016 return -1;
3019 cp += strspn(cp, " \t\n\r");
3020 if (*cp == '"') {
3021 const char *newcp =
3022 decode_escaped_string(cp, len - (cp - body),
3023 &client_nonce, &client_nonce_len);
3024 if (newcp == NULL) {
3025 connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
3026 conn);
3027 connection_mark_for_close(TO_CONN(conn));
3028 return -1;
3030 cp = newcp;
3031 } else {
3032 size_t client_nonce_encoded_len = strspn(cp, "0123456789ABCDEFabcdef");
3034 client_nonce_len = client_nonce_encoded_len / 2;
3035 client_nonce = tor_malloc_zero(client_nonce_len);
3037 if (base16_decode(client_nonce, client_nonce_len,
3038 cp, client_nonce_encoded_len) < 0) {
3039 connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
3040 conn);
3041 connection_mark_for_close(TO_CONN(conn));
3042 tor_free(client_nonce);
3043 return -1;
3046 cp += client_nonce_encoded_len;
3049 cp += strspn(cp, " \t\n\r");
3050 if (*cp != '\0' ||
3051 cp != body + len) {
3052 connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
3053 conn);
3054 connection_mark_for_close(TO_CONN(conn));
3055 tor_free(client_nonce);
3056 return -1;
3059 tor_assert(!crypto_rand(server_nonce, SAFECOOKIE_SERVER_NONCE_LEN));
3061 /* Now compute and send the server-to-controller response, and the
3062 * server's nonce. */
3063 tor_assert(authentication_cookie != NULL);
3066 size_t tmp_len = (AUTHENTICATION_COOKIE_LEN +
3067 client_nonce_len +
3068 SAFECOOKIE_SERVER_NONCE_LEN);
3069 char *tmp = tor_malloc_zero(tmp_len);
3070 char *client_hash = tor_malloc_zero(DIGEST256_LEN);
3071 memcpy(tmp, authentication_cookie, AUTHENTICATION_COOKIE_LEN);
3072 memcpy(tmp + AUTHENTICATION_COOKIE_LEN, client_nonce, client_nonce_len);
3073 memcpy(tmp + AUTHENTICATION_COOKIE_LEN + client_nonce_len,
3074 server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
3076 crypto_hmac_sha256(server_hash,
3077 SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT,
3078 strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT),
3079 tmp,
3080 tmp_len);
3082 crypto_hmac_sha256(client_hash,
3083 SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT,
3084 strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT),
3085 tmp,
3086 tmp_len);
3088 conn->safecookie_client_hash = client_hash;
3090 tor_free(tmp);
3093 base16_encode(server_hash_encoded, sizeof(server_hash_encoded),
3094 server_hash, sizeof(server_hash));
3095 base16_encode(server_nonce_encoded, sizeof(server_nonce_encoded),
3096 server_nonce, sizeof(server_nonce));
3098 connection_printf_to_buf(conn,
3099 "250 AUTHCHALLENGE SERVERHASH=%s "
3100 "SERVERNONCE=%s\r\n",
3101 server_hash_encoded,
3102 server_nonce_encoded);
3104 tor_free(client_nonce);
3105 return 0;
3108 /** Called when we get a USEFEATURE command: parse the feature list, and
3109 * set up the control_connection's options properly. */
3110 static int
3111 handle_control_usefeature(control_connection_t *conn,
3112 uint32_t len,
3113 const char *body)
3115 smartlist_t *args;
3116 int bad = 0;
3117 (void) len; /* body is nul-terminated; it's safe to ignore the length */
3118 args = smartlist_new();
3119 smartlist_split_string(args, body, " ",
3120 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3121 SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
3122 if (!strcasecmp(arg, "VERBOSE_NAMES"))
3124 else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
3126 else {
3127 connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
3128 arg);
3129 bad = 1;
3130 break;
3132 } SMARTLIST_FOREACH_END(arg);
3134 if (!bad) {
3135 send_control_done(conn);
3138 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3139 smartlist_free(args);
3140 return 0;
3143 /** Implementation for the DROPGUARDS command. */
3144 static int
3145 handle_control_dropguards(control_connection_t *conn,
3146 uint32_t len,
3147 const char *body)
3149 smartlist_t *args;
3150 (void) len; /* body is nul-terminated; it's safe to ignore the length */
3151 args = smartlist_new();
3152 smartlist_split_string(args, body, " ",
3153 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3155 if (smartlist_len(args)) {
3156 connection_printf_to_buf(conn, "512 Too many arguments to DROPGUARDS\r\n");
3157 } else {
3158 remove_all_entry_guards();
3159 send_control_done(conn);
3162 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3163 smartlist_free(args);
3164 return 0;
3167 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
3169 connection_control_finished_flushing(control_connection_t *conn)
3171 tor_assert(conn);
3172 return 0;
3175 /** Called when <b>conn</b> has gotten its socket closed. */
3177 connection_control_reached_eof(control_connection_t *conn)
3179 tor_assert(conn);
3181 log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
3182 connection_mark_for_close(TO_CONN(conn));
3183 return 0;
3186 static void lost_owning_controller(const char *owner_type,
3187 const char *loss_manner)
3188 ATTR_NORETURN;
3190 /** Shut down this Tor instance in the same way that SIGINT would, but
3191 * with a log message appropriate for the loss of an owning controller. */
3192 static void
3193 lost_owning_controller(const char *owner_type, const char *loss_manner)
3195 log_notice(LD_CONTROL, "Owning controller %s has %s -- exiting now.",
3196 owner_type, loss_manner);
3198 /* XXXX Perhaps this chunk of code should be a separate function,
3199 * called here and by process_signal(SIGINT). */
3200 tor_cleanup();
3201 exit(0);
3204 /** Called when <b>conn</b> is being freed. */
3205 void
3206 connection_control_closed(control_connection_t *conn)
3208 tor_assert(conn);
3210 conn->event_mask = 0;
3211 control_update_global_event_mask();
3213 if (conn->is_owning_control_connection) {
3214 lost_owning_controller("connection", "closed");
3218 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
3219 * stage of the protocol. */
3220 static int
3221 is_valid_initial_command(control_connection_t *conn, const char *cmd)
3223 if (conn->base_.state == CONTROL_CONN_STATE_OPEN)
3224 return 1;
3225 if (!strcasecmp(cmd, "PROTOCOLINFO"))
3226 return (!conn->have_sent_protocolinfo &&
3227 conn->safecookie_client_hash == NULL);
3228 if (!strcasecmp(cmd, "AUTHCHALLENGE"))
3229 return (conn->safecookie_client_hash == NULL);
3230 if (!strcasecmp(cmd, "AUTHENTICATE") ||
3231 !strcasecmp(cmd, "QUIT"))
3232 return 1;
3233 return 0;
3236 /** Do not accept any control command of more than 1MB in length. Anything
3237 * that needs to be anywhere near this long probably means that one of our
3238 * interfaces is broken. */
3239 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
3241 /** Wrapper around peek_(evbuffer|buf)_has_control0 command: presents the same
3242 * interface as those underlying functions, but takes a connection_t intead of
3243 * an evbuffer or a buf_t.
3245 static int
3246 peek_connection_has_control0_command(connection_t *conn)
3248 IF_HAS_BUFFEREVENT(conn, {
3249 struct evbuffer *input = bufferevent_get_input(conn->bufev);
3250 return peek_evbuffer_has_control0_command(input);
3251 }) ELSE_IF_NO_BUFFEREVENT {
3252 return peek_buf_has_control0_command(conn->inbuf);
3256 /** Called when data has arrived on a v1 control connection: Try to fetch
3257 * commands from conn->inbuf, and execute them.
3260 connection_control_process_inbuf(control_connection_t *conn)
3262 size_t data_len;
3263 uint32_t cmd_data_len;
3264 int cmd_len;
3265 char *args;
3267 tor_assert(conn);
3268 tor_assert(conn->base_.state == CONTROL_CONN_STATE_OPEN ||
3269 conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH);
3271 if (!conn->incoming_cmd) {
3272 conn->incoming_cmd = tor_malloc(1024);
3273 conn->incoming_cmd_len = 1024;
3274 conn->incoming_cmd_cur_len = 0;
3277 if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
3278 peek_connection_has_control0_command(TO_CONN(conn))) {
3279 /* Detect v0 commands and send a "no more v0" message. */
3280 size_t body_len;
3281 char buf[128];
3282 set_uint16(buf+2, htons(0x0000)); /* type == error */
3283 set_uint16(buf+4, htons(0x0001)); /* code == internal error */
3284 strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
3285 "and later; upgrade your controller.",
3286 sizeof(buf)-6);
3287 body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
3288 set_uint16(buf+0, htons(body_len));
3289 connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
3291 connection_mark_and_flush(TO_CONN(conn));
3292 return 0;
3295 again:
3296 while (1) {
3297 size_t last_idx;
3298 int r;
3299 /* First, fetch a line. */
3300 do {
3301 data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
3302 r = connection_fetch_from_buf_line(TO_CONN(conn),
3303 conn->incoming_cmd+conn->incoming_cmd_cur_len,
3304 &data_len);
3305 if (r == 0)
3306 /* Line not all here yet. Wait. */
3307 return 0;
3308 else if (r == -1) {
3309 if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
3310 connection_write_str_to_buf("500 Line too long.\r\n", conn);
3311 connection_stop_reading(TO_CONN(conn));
3312 connection_mark_and_flush(TO_CONN(conn));
3314 while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
3315 conn->incoming_cmd_len *= 2;
3316 conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
3317 conn->incoming_cmd_len);
3319 } while (r != 1);
3321 tor_assert(data_len);
3323 last_idx = conn->incoming_cmd_cur_len;
3324 conn->incoming_cmd_cur_len += (int)data_len;
3326 /* We have appended a line to incoming_cmd. Is the command done? */
3327 if (last_idx == 0 && *conn->incoming_cmd != '+')
3328 /* One line command, didn't start with '+'. */
3329 break;
3330 /* XXXX this code duplication is kind of dumb. */
3331 if (last_idx+3 == conn->incoming_cmd_cur_len &&
3332 tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
3333 /* Just appended ".\r\n"; we're done. Remove it. */
3334 conn->incoming_cmd[last_idx] = '\0';
3335 conn->incoming_cmd_cur_len -= 3;
3336 break;
3337 } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
3338 tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
3339 /* Just appended ".\n"; we're done. Remove it. */
3340 conn->incoming_cmd[last_idx] = '\0';
3341 conn->incoming_cmd_cur_len -= 2;
3342 break;
3344 /* Otherwise, read another line. */
3346 data_len = conn->incoming_cmd_cur_len;
3347 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
3348 * recognize it.
3350 cmd_len = 0;
3351 while ((size_t)cmd_len < data_len
3352 && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
3353 ++cmd_len;
3355 conn->incoming_cmd[cmd_len]='\0';
3356 args = conn->incoming_cmd+cmd_len+1;
3357 tor_assert(data_len>(size_t)cmd_len);
3358 data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
3359 while (TOR_ISSPACE(*args)) {
3360 ++args;
3361 --data_len;
3364 /* If the connection is already closing, ignore further commands */
3365 if (TO_CONN(conn)->marked_for_close) {
3366 return 0;
3369 /* Otherwise, Quit is always valid. */
3370 if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
3371 connection_write_str_to_buf("250 closing connection\r\n", conn);
3372 connection_mark_and_flush(TO_CONN(conn));
3373 return 0;
3376 if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
3377 !is_valid_initial_command(conn, conn->incoming_cmd)) {
3378 connection_write_str_to_buf("514 Authentication required.\r\n", conn);
3379 connection_mark_for_close(TO_CONN(conn));
3380 return 0;
3383 if (data_len >= UINT32_MAX) {
3384 connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
3385 connection_mark_for_close(TO_CONN(conn));
3386 return 0;
3389 /* XXXX Why is this not implemented as a table like the GETINFO
3390 * items are? Even handling the plus signs at the beginnings of
3391 * commands wouldn't be very hard with proper macros. */
3392 cmd_data_len = (uint32_t)data_len;
3393 if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
3394 if (handle_control_setconf(conn, cmd_data_len, args))
3395 return -1;
3396 } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
3397 if (handle_control_resetconf(conn, cmd_data_len, args))
3398 return -1;
3399 } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
3400 if (handle_control_getconf(conn, cmd_data_len, args))
3401 return -1;
3402 } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
3403 if (handle_control_loadconf(conn, cmd_data_len, args))
3404 return -1;
3405 } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
3406 if (handle_control_setevents(conn, cmd_data_len, args))
3407 return -1;
3408 } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
3409 if (handle_control_authenticate(conn, cmd_data_len, args))
3410 return -1;
3411 } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
3412 if (handle_control_saveconf(conn, cmd_data_len, args))
3413 return -1;
3414 } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
3415 if (handle_control_signal(conn, cmd_data_len, args))
3416 return -1;
3417 } else if (!strcasecmp(conn->incoming_cmd, "TAKEOWNERSHIP")) {
3418 if (handle_control_takeownership(conn, cmd_data_len, args))
3419 return -1;
3420 } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
3421 if (handle_control_mapaddress(conn, cmd_data_len, args))
3422 return -1;
3423 } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
3424 if (handle_control_getinfo(conn, cmd_data_len, args))
3425 return -1;
3426 } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
3427 if (handle_control_extendcircuit(conn, cmd_data_len, args))
3428 return -1;
3429 } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
3430 if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
3431 return -1;
3432 } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
3433 connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
3434 } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
3435 if (handle_control_attachstream(conn, cmd_data_len, args))
3436 return -1;
3437 } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
3438 if (handle_control_postdescriptor(conn, cmd_data_len, args))
3439 return -1;
3440 } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
3441 if (handle_control_redirectstream(conn, cmd_data_len, args))
3442 return -1;
3443 } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
3444 if (handle_control_closestream(conn, cmd_data_len, args))
3445 return -1;
3446 } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
3447 if (handle_control_closecircuit(conn, cmd_data_len, args))
3448 return -1;
3449 } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
3450 if (handle_control_usefeature(conn, cmd_data_len, args))
3451 return -1;
3452 } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
3453 if (handle_control_resolve(conn, cmd_data_len, args))
3454 return -1;
3455 } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
3456 if (handle_control_protocolinfo(conn, cmd_data_len, args))
3457 return -1;
3458 } else if (!strcasecmp(conn->incoming_cmd, "AUTHCHALLENGE")) {
3459 if (handle_control_authchallenge(conn, cmd_data_len, args))
3460 return -1;
3461 } else if (!strcasecmp(conn->incoming_cmd, "DROPGUARDS")) {
3462 if (handle_control_dropguards(conn, cmd_data_len, args))
3463 return -1;
3464 } else {
3465 connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
3466 conn->incoming_cmd);
3469 conn->incoming_cmd_cur_len = 0;
3470 goto again;
3473 /** Something major has happened to circuit <b>circ</b>: tell any
3474 * interested control connections. */
3476 control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
3477 int reason_code)
3479 const char *status;
3480 char reasons[64] = "";
3481 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
3482 return 0;
3483 tor_assert(circ);
3485 switch (tp)
3487 case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
3488 case CIRC_EVENT_BUILT: status = "BUILT"; break;
3489 case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
3490 case CIRC_EVENT_FAILED: status = "FAILED"; break;
3491 case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
3492 default:
3493 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3494 tor_fragile_assert();
3495 return 0;
3498 if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
3499 const char *reason_str = circuit_end_reason_to_control_string(reason_code);
3500 char unk_reason_buf[16];
3501 if (!reason_str) {
3502 tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
3503 reason_str = unk_reason_buf;
3505 if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
3506 tor_snprintf(reasons, sizeof(reasons),
3507 " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
3508 } else {
3509 tor_snprintf(reasons, sizeof(reasons),
3510 " REASON=%s", reason_str);
3515 char *circdesc = circuit_describe_status_for_controller(circ);
3516 const char *sp = strlen(circdesc) ? " " : "";
3517 send_control_event(EVENT_CIRCUIT_STATUS, ALL_FORMATS,
3518 "650 CIRC %lu %s%s%s%s\r\n",
3519 (unsigned long)circ->global_identifier,
3520 status, sp,
3521 circdesc,
3522 reasons);
3523 tor_free(circdesc);
3526 return 0;
3529 /** Something minor has happened to circuit <b>circ</b>: tell any
3530 * interested control connections. */
3531 static int
3532 control_event_circuit_status_minor(origin_circuit_t *circ,
3533 circuit_status_minor_event_t e,
3534 int purpose, const struct timeval *tv)
3536 const char *event_desc;
3537 char event_tail[160] = "";
3538 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
3539 return 0;
3540 tor_assert(circ);
3542 switch (e)
3544 case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
3545 event_desc = "PURPOSE_CHANGED";
3548 /* event_tail can currently be up to 68 chars long */
3549 const char *hs_state_str =
3550 circuit_purpose_to_controller_hs_state_string(purpose);
3551 tor_snprintf(event_tail, sizeof(event_tail),
3552 " OLD_PURPOSE=%s%s%s",
3553 circuit_purpose_to_controller_string(purpose),
3554 (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
3555 (hs_state_str != NULL) ? hs_state_str : "");
3558 break;
3559 case CIRC_MINOR_EVENT_CANNIBALIZED:
3560 event_desc = "CANNIBALIZED";
3563 /* event_tail can currently be up to 130 chars long */
3564 const char *hs_state_str =
3565 circuit_purpose_to_controller_hs_state_string(purpose);
3566 const struct timeval *old_timestamp_began = tv;
3567 char tbuf[ISO_TIME_USEC_LEN+1];
3568 format_iso_time_nospace_usec(tbuf, old_timestamp_began);
3570 tor_snprintf(event_tail, sizeof(event_tail),
3571 " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
3572 circuit_purpose_to_controller_string(purpose),
3573 (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
3574 (hs_state_str != NULL) ? hs_state_str : "",
3575 tbuf);
3578 break;
3579 default:
3580 log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
3581 tor_fragile_assert();
3582 return 0;
3586 char *circdesc = circuit_describe_status_for_controller(circ);
3587 const char *sp = strlen(circdesc) ? " " : "";
3588 send_control_event(EVENT_CIRCUIT_STATUS_MINOR, ALL_FORMATS,
3589 "650 CIRC_MINOR %lu %s%s%s%s\r\n",
3590 (unsigned long)circ->global_identifier,
3591 event_desc, sp,
3592 circdesc,
3593 event_tail);
3594 tor_free(circdesc);
3597 return 0;
3601 * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
3602 * interested controllers.
3605 control_event_circuit_purpose_changed(origin_circuit_t *circ,
3606 int old_purpose)
3608 return control_event_circuit_status_minor(circ,
3609 CIRC_MINOR_EVENT_PURPOSE_CHANGED,
3610 old_purpose,
3611 NULL);
3615 * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
3616 * created-time from <b>old_tv_created</b>: tell any interested controllers.
3619 control_event_circuit_cannibalized(origin_circuit_t *circ,
3620 int old_purpose,
3621 const struct timeval *old_tv_created)
3623 return control_event_circuit_status_minor(circ,
3624 CIRC_MINOR_EVENT_CANNIBALIZED,
3625 old_purpose,
3626 old_tv_created);
3629 /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
3630 * <b>buf</b>, determine the address:port combination requested on
3631 * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
3632 * failure. */
3633 static int
3634 write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
3636 char buf2[256];
3637 if (conn->chosen_exit_name)
3638 if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
3639 return -1;
3640 if (!conn->socks_request)
3641 return -1;
3642 if (tor_snprintf(buf, len, "%s%s%s:%d",
3643 conn->socks_request->address,
3644 conn->chosen_exit_name ? buf2 : "",
3645 !conn->chosen_exit_name && connection_edge_is_rendezvous_stream(
3646 ENTRY_TO_EDGE_CONN(conn)) ? ".onion" : "",
3647 conn->socks_request->port)<0)
3648 return -1;
3649 return 0;
3652 /** Something has happened to the stream associated with AP connection
3653 * <b>conn</b>: tell any interested control connections. */
3655 control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
3656 int reason_code)
3658 char reason_buf[64];
3659 char addrport_buf[64];
3660 const char *status;
3661 circuit_t *circ;
3662 origin_circuit_t *origin_circ = NULL;
3663 char buf[256];
3664 const char *purpose = "";
3665 tor_assert(conn->socks_request);
3667 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
3668 return 0;
3670 if (tp == STREAM_EVENT_CLOSED &&
3671 (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
3672 return 0;
3674 write_stream_target_to_buf(conn, buf, sizeof(buf));
3676 reason_buf[0] = '\0';
3677 switch (tp)
3679 case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
3680 case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
3681 case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
3682 case STREAM_EVENT_FAILED: status = "FAILED"; break;
3683 case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
3684 case STREAM_EVENT_NEW: status = "NEW"; break;
3685 case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
3686 case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
3687 case STREAM_EVENT_REMAP: status = "REMAP"; break;
3688 default:
3689 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3690 return 0;
3692 if (reason_code && (tp == STREAM_EVENT_FAILED ||
3693 tp == STREAM_EVENT_CLOSED ||
3694 tp == STREAM_EVENT_FAILED_RETRIABLE)) {
3695 const char *reason_str = stream_end_reason_to_control_string(reason_code);
3696 char *r = NULL;
3697 if (!reason_str) {
3698 tor_asprintf(&r, " UNKNOWN_%d", reason_code);
3699 reason_str = r;
3701 if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
3702 tor_snprintf(reason_buf, sizeof(reason_buf),
3703 " REASON=END REMOTE_REASON=%s", reason_str);
3704 else
3705 tor_snprintf(reason_buf, sizeof(reason_buf),
3706 " REASON=%s", reason_str);
3707 tor_free(r);
3708 } else if (reason_code && tp == STREAM_EVENT_REMAP) {
3709 switch (reason_code) {
3710 case REMAP_STREAM_SOURCE_CACHE:
3711 strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
3712 break;
3713 case REMAP_STREAM_SOURCE_EXIT:
3714 strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
3715 break;
3716 default:
3717 tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
3718 reason_code);
3719 /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
3720 break;
3724 if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
3726 * When the control conn is an AF_UNIX socket and we have no address,
3727 * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
3728 * dnsserv.c.
3730 if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
3731 tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
3732 ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
3733 } else {
3735 * else leave it blank so control on AF_UNIX doesn't need to make
3736 * something up.
3738 addrport_buf[0] = '\0';
3740 } else {
3741 addrport_buf[0] = '\0';
3744 if (tp == STREAM_EVENT_NEW_RESOLVE) {
3745 purpose = " PURPOSE=DNS_REQUEST";
3746 } else if (tp == STREAM_EVENT_NEW) {
3747 if (conn->use_begindir) {
3748 connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
3749 int linked_dir_purpose = -1;
3750 if (linked && linked->type == CONN_TYPE_DIR)
3751 linked_dir_purpose = linked->purpose;
3752 if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
3753 purpose = " PURPOSE=DIR_UPLOAD";
3754 else
3755 purpose = " PURPOSE=DIR_FETCH";
3756 } else
3757 purpose = " PURPOSE=USER";
3760 circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
3761 if (circ && CIRCUIT_IS_ORIGIN(circ))
3762 origin_circ = TO_ORIGIN_CIRCUIT(circ);
3763 send_control_event(EVENT_STREAM_STATUS, ALL_FORMATS,
3764 "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
3765 U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
3766 status,
3767 origin_circ?
3768 (unsigned long)origin_circ->global_identifier : 0ul,
3769 buf, reason_buf, addrport_buf, purpose);
3771 /* XXX need to specify its intended exit, etc? */
3773 return 0;
3776 /** Figure out the best name for the target router of an OR connection
3777 * <b>conn</b>, and write it into the <b>len</b>-character buffer
3778 * <b>name</b>. */
3779 static void
3780 orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
3782 const node_t *node = node_get_by_id(conn->identity_digest);
3783 if (node) {
3784 tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
3785 node_get_verbose_nickname(node, name);
3786 } else if (! tor_digest_is_zero(conn->identity_digest)) {
3787 name[0] = '$';
3788 base16_encode(name+1, len-1, conn->identity_digest,
3789 DIGEST_LEN);
3790 } else {
3791 tor_snprintf(name, len, "%s:%d",
3792 conn->base_.address, conn->base_.port);
3796 /** Called when the status of an OR connection <b>conn</b> changes: tell any
3797 * interested control connections. <b>tp</b> is the new status for the
3798 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
3799 * may be the reason why.
3802 control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
3803 int reason)
3805 int ncircs = 0;
3806 const char *status;
3807 char name[128];
3808 char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
3810 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
3811 return 0;
3813 switch (tp)
3815 case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
3816 case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
3817 case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
3818 case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
3819 case OR_CONN_EVENT_NEW: status = "NEW"; break;
3820 default:
3821 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
3822 return 0;
3824 if (conn->chan) {
3825 ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
3826 } else {
3827 ncircs = 0;
3829 ncircs += connection_or_get_num_circuits(conn);
3830 if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
3831 tor_snprintf(ncircs_buf, sizeof(ncircs_buf), " NCIRCS=%d", ncircs);
3834 orconn_target_get_name(name, sizeof(name), conn);
3835 send_control_event(EVENT_OR_CONN_STATUS, ALL_FORMATS,
3836 "650 ORCONN %s %s%s%s%s ID="U64_FORMAT"\r\n",
3837 name, status,
3838 reason ? " REASON=" : "",
3839 orconn_end_reason_to_control_string(reason),
3840 ncircs_buf,
3841 U64_PRINTF_ARG(conn->base_.global_identifier));
3843 return 0;
3847 * Print out STREAM_BW event for a single conn
3850 control_event_stream_bandwidth(edge_connection_t *edge_conn)
3852 circuit_t *circ;
3853 origin_circuit_t *ocirc;
3854 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
3855 if (!edge_conn->n_read && !edge_conn->n_written)
3856 return 0;
3858 send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
3859 "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
3860 U64_PRINTF_ARG(edge_conn->base_.global_identifier),
3861 (unsigned long)edge_conn->n_read,
3862 (unsigned long)edge_conn->n_written);
3864 circ = circuit_get_by_edge_conn(edge_conn);
3865 if (circ && CIRCUIT_IS_ORIGIN(circ)) {
3866 ocirc = TO_ORIGIN_CIRCUIT(circ);
3867 ocirc->n_read_circ_bw += edge_conn->n_read;
3868 ocirc->n_written_circ_bw += edge_conn->n_written;
3870 edge_conn->n_written = edge_conn->n_read = 0;
3873 return 0;
3876 /** A second or more has elapsed: tell any interested control
3877 * connections how much bandwidth streams have used. */
3879 control_event_stream_bandwidth_used(void)
3881 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
3882 smartlist_t *conns = get_connection_array();
3883 edge_connection_t *edge_conn;
3885 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
3887 if (conn->type != CONN_TYPE_AP)
3888 continue;
3889 edge_conn = TO_EDGE_CONN(conn);
3890 if (!edge_conn->n_read && !edge_conn->n_written)
3891 continue;
3893 send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
3894 "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
3895 U64_PRINTF_ARG(edge_conn->base_.global_identifier),
3896 (unsigned long)edge_conn->n_read,
3897 (unsigned long)edge_conn->n_written);
3899 edge_conn->n_written = edge_conn->n_read = 0;
3901 SMARTLIST_FOREACH_END(conn);
3904 return 0;
3907 /** A second or more has elapsed: tell any interested control connections
3908 * how much bandwidth origin circuits have used. */
3910 control_event_circ_bandwidth_used(void)
3912 circuit_t *circ;
3913 origin_circuit_t *ocirc;
3914 if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
3915 return 0;
3917 TOR_LIST_FOREACH(circ, circuit_get_global_list(), head) {
3918 if (!CIRCUIT_IS_ORIGIN(circ))
3919 continue;
3920 ocirc = TO_ORIGIN_CIRCUIT(circ);
3921 if (!ocirc->n_read_circ_bw && !ocirc->n_written_circ_bw)
3922 continue;
3923 send_control_event(EVENT_CIRC_BANDWIDTH_USED, ALL_FORMATS,
3924 "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu\r\n",
3925 ocirc->global_identifier,
3926 (unsigned long)ocirc->n_read_circ_bw,
3927 (unsigned long)ocirc->n_written_circ_bw);
3928 ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
3931 return 0;
3934 /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
3935 * bandwidth counters. */
3937 control_event_conn_bandwidth(connection_t *conn)
3939 const char *conn_type_str;
3940 if (!get_options()->TestingEnableConnBwEvent ||
3941 !EVENT_IS_INTERESTING(EVENT_CONN_BW))
3942 return 0;
3943 if (!conn->n_read_conn_bw && !conn->n_written_conn_bw)
3944 return 0;
3945 switch (conn->type) {
3946 case CONN_TYPE_OR:
3947 conn_type_str = "OR";
3948 break;
3949 case CONN_TYPE_DIR:
3950 conn_type_str = "DIR";
3951 break;
3952 case CONN_TYPE_EXIT:
3953 conn_type_str = "EXIT";
3954 break;
3955 default:
3956 return 0;
3958 send_control_event(EVENT_CONN_BW, ALL_FORMATS,
3959 "650 CONN_BW ID="U64_FORMAT" TYPE=%s "
3960 "READ=%lu WRITTEN=%lu\r\n",
3961 U64_PRINTF_ARG(conn->global_identifier),
3962 conn_type_str,
3963 (unsigned long)conn->n_read_conn_bw,
3964 (unsigned long)conn->n_written_conn_bw);
3965 conn->n_written_conn_bw = conn->n_read_conn_bw = 0;
3966 return 0;
3969 /** A second or more has elapsed: tell any interested control
3970 * connections how much bandwidth connections have used. */
3972 control_event_conn_bandwidth_used(void)
3974 if (get_options()->TestingEnableConnBwEvent &&
3975 EVENT_IS_INTERESTING(EVENT_CONN_BW)) {
3976 SMARTLIST_FOREACH(get_connection_array(), connection_t *, conn,
3977 control_event_conn_bandwidth(conn));
3979 return 0;
3982 /** Helper: iterate over cell statistics of <b>circ</b> and sum up added
3983 * cells, removed cells, and waiting times by cell command and direction.
3984 * Store results in <b>cell_stats</b>. Free cell statistics of the
3985 * circuit afterwards. */
3986 void
3987 sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
3989 memset(cell_stats, 0, sizeof(cell_stats_t));
3990 SMARTLIST_FOREACH_BEGIN(circ->testing_cell_stats,
3991 testing_cell_stats_entry_t *, ent) {
3992 tor_assert(ent->command <= CELL_COMMAND_MAX_);
3993 if (!ent->removed && !ent->exitward) {
3994 cell_stats->added_cells_appward[ent->command] += 1;
3995 } else if (!ent->removed && ent->exitward) {
3996 cell_stats->added_cells_exitward[ent->command] += 1;
3997 } else if (!ent->exitward) {
3998 cell_stats->removed_cells_appward[ent->command] += 1;
3999 cell_stats->total_time_appward[ent->command] += ent->waiting_time * 10;
4000 } else {
4001 cell_stats->removed_cells_exitward[ent->command] += 1;
4002 cell_stats->total_time_exitward[ent->command] += ent->waiting_time * 10;
4004 tor_free(ent);
4005 } SMARTLIST_FOREACH_END(ent);
4006 smartlist_free(circ->testing_cell_stats);
4007 circ->testing_cell_stats = NULL;
4010 /** Helper: append a cell statistics string to <code>event_parts</code>,
4011 * prefixed with <code>key</code>=. Statistics consist of comma-separated
4012 * key:value pairs with lower-case command strings as keys and cell
4013 * numbers or total waiting times as values. A key:value pair is included
4014 * if the entry in <code>include_if_non_zero</code> is not zero, but with
4015 * the (possibly zero) entry from <code>number_to_include</code>. Both
4016 * arrays are expected to have a length of CELL_COMMAND_MAX_ + 1. If no
4017 * entry in <code>include_if_non_zero</code> is positive, no string will
4018 * be added to <code>event_parts</code>. */
4019 void
4020 append_cell_stats_by_command(smartlist_t *event_parts, const char *key,
4021 const uint64_t *include_if_non_zero,
4022 const uint64_t *number_to_include)
4024 smartlist_t *key_value_strings = smartlist_new();
4025 int i;
4026 for (i = 0; i <= CELL_COMMAND_MAX_; i++) {
4027 if (include_if_non_zero[i] > 0) {
4028 smartlist_add_asprintf(key_value_strings, "%s:"U64_FORMAT,
4029 cell_command_to_string(i),
4030 U64_PRINTF_ARG(number_to_include[i]));
4033 if (smartlist_len(key_value_strings) > 0) {
4034 char *joined = smartlist_join_strings(key_value_strings, ",", 0, NULL);
4035 smartlist_add_asprintf(event_parts, "%s=%s", key, joined);
4036 SMARTLIST_FOREACH(key_value_strings, char *, cp, tor_free(cp));
4037 tor_free(joined);
4039 smartlist_free(key_value_strings);
4042 /** Helper: format <b>cell_stats</b> for <b>circ</b> for inclusion in a
4043 * CELL_STATS event and write result string to <b>event_string</b>. */
4044 void
4045 format_cell_stats(char **event_string, circuit_t *circ,
4046 cell_stats_t *cell_stats)
4048 smartlist_t *event_parts = smartlist_new();
4049 if (CIRCUIT_IS_ORIGIN(circ)) {
4050 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
4051 smartlist_add_asprintf(event_parts, "ID=%lu",
4052 (unsigned long)ocirc->global_identifier);
4053 } else if (TO_OR_CIRCUIT(circ)->p_chan) {
4054 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
4055 smartlist_add_asprintf(event_parts, "InboundQueue=%lu",
4056 (unsigned long)or_circ->p_circ_id);
4057 smartlist_add_asprintf(event_parts, "InboundConn="U64_FORMAT,
4058 U64_PRINTF_ARG(or_circ->p_chan->global_identifier));
4059 append_cell_stats_by_command(event_parts, "InboundAdded",
4060 cell_stats->added_cells_appward,
4061 cell_stats->added_cells_appward);
4062 append_cell_stats_by_command(event_parts, "InboundRemoved",
4063 cell_stats->removed_cells_appward,
4064 cell_stats->removed_cells_appward);
4065 append_cell_stats_by_command(event_parts, "InboundTime",
4066 cell_stats->removed_cells_appward,
4067 cell_stats->total_time_appward);
4069 if (circ->n_chan) {
4070 smartlist_add_asprintf(event_parts, "OutboundQueue=%lu",
4071 (unsigned long)circ->n_circ_id);
4072 smartlist_add_asprintf(event_parts, "OutboundConn="U64_FORMAT,
4073 U64_PRINTF_ARG(circ->n_chan->global_identifier));
4074 append_cell_stats_by_command(event_parts, "OutboundAdded",
4075 cell_stats->added_cells_exitward,
4076 cell_stats->added_cells_exitward);
4077 append_cell_stats_by_command(event_parts, "OutboundRemoved",
4078 cell_stats->removed_cells_exitward,
4079 cell_stats->removed_cells_exitward);
4080 append_cell_stats_by_command(event_parts, "OutboundTime",
4081 cell_stats->removed_cells_exitward,
4082 cell_stats->total_time_exitward);
4084 *event_string = smartlist_join_strings(event_parts, " ", 0, NULL);
4085 SMARTLIST_FOREACH(event_parts, char *, cp, tor_free(cp));
4086 smartlist_free(event_parts);
4089 /** A second or more has elapsed: tell any interested control connection
4090 * how many cells have been processed for a given circuit. */
4092 control_event_circuit_cell_stats(void)
4094 circuit_t *circ;
4095 cell_stats_t *cell_stats;
4096 char *event_string;
4097 if (!get_options()->TestingEnableCellStatsEvent ||
4098 !EVENT_IS_INTERESTING(EVENT_CELL_STATS))
4099 return 0;
4100 cell_stats = tor_malloc(sizeof(cell_stats_t));;
4101 TOR_LIST_FOREACH(circ, circuit_get_global_list(), head) {
4102 if (!circ->testing_cell_stats)
4103 continue;
4104 sum_up_cell_stats_by_command(circ, cell_stats);
4105 format_cell_stats(&event_string, circ, cell_stats);
4106 send_control_event(EVENT_CELL_STATS, ALL_FORMATS,
4107 "650 CELL_STATS %s\r\n", event_string);
4108 tor_free(event_string);
4110 tor_free(cell_stats);
4111 return 0;
4114 /** Tokens in <b>bucket</b> have been refilled: the read bucket was empty
4115 * for <b>read_empty_time</b> millis, the write bucket was empty for
4116 * <b>write_empty_time</b> millis, and buckets were last refilled
4117 * <b>milliseconds_elapsed</b> millis ago. Only emit TB_EMPTY event if
4118 * either read or write bucket have been empty before. */
4120 control_event_tb_empty(const char *bucket, uint32_t read_empty_time,
4121 uint32_t write_empty_time,
4122 int milliseconds_elapsed)
4124 if (get_options()->TestingEnableTbEmptyEvent &&
4125 EVENT_IS_INTERESTING(EVENT_TB_EMPTY) &&
4126 (read_empty_time > 0 || write_empty_time > 0)) {
4127 send_control_event(EVENT_TB_EMPTY, ALL_FORMATS,
4128 "650 TB_EMPTY %s READ=%d WRITTEN=%d "
4129 "LAST=%d\r\n",
4130 bucket, read_empty_time, write_empty_time,
4131 milliseconds_elapsed);
4133 return 0;
4136 /** A second or more has elapsed: tell any interested control
4137 * connections how much bandwidth we used. */
4139 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
4141 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
4142 send_control_event(EVENT_BANDWIDTH_USED, ALL_FORMATS,
4143 "650 BW %lu %lu\r\n",
4144 (unsigned long)n_read,
4145 (unsigned long)n_written);
4148 return 0;
4151 /** Called when we are sending a log message to the controllers: suspend
4152 * sending further log messages to the controllers until we're done. Used by
4153 * CONN_LOG_PROTECT. */
4154 void
4155 disable_control_logging(void)
4157 ++disable_log_messages;
4160 /** We're done sending a log message to the controllers: re-enable controller
4161 * logging. Used by CONN_LOG_PROTECT. */
4162 void
4163 enable_control_logging(void)
4165 if (--disable_log_messages < 0)
4166 tor_assert(0);
4169 /** We got a log message: tell any interested control connections. */
4170 void
4171 control_event_logmsg(int severity, uint32_t domain, const char *msg)
4173 int event;
4175 /* Don't even think of trying to add stuff to a buffer from a cpuworker
4176 * thread. */
4177 if (! in_main_thread())
4178 return;
4180 if (disable_log_messages)
4181 return;
4183 if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
4184 severity <= LOG_NOTICE) {
4185 char *esc = esc_for_log(msg);
4186 ++disable_log_messages;
4187 control_event_general_status(severity, "BUG REASON=%s", esc);
4188 --disable_log_messages;
4189 tor_free(esc);
4192 event = log_severity_to_event(severity);
4193 if (event >= 0 && EVENT_IS_INTERESTING(event)) {
4194 char *b = NULL;
4195 const char *s;
4196 if (strchr(msg, '\n')) {
4197 char *cp;
4198 b = tor_strdup(msg);
4199 for (cp = b; *cp; ++cp)
4200 if (*cp == '\r' || *cp == '\n')
4201 *cp = ' ';
4203 switch (severity) {
4204 case LOG_DEBUG: s = "DEBUG"; break;
4205 case LOG_INFO: s = "INFO"; break;
4206 case LOG_NOTICE: s = "NOTICE"; break;
4207 case LOG_WARN: s = "WARN"; break;
4208 case LOG_ERR: s = "ERR"; break;
4209 default: s = "UnknownLogSeverity"; break;
4211 ++disable_log_messages;
4212 send_control_event(event, ALL_FORMATS, "650 %s %s\r\n", s, b?b:msg);
4213 --disable_log_messages;
4214 tor_free(b);
4218 /** Called whenever we receive new router descriptors: tell any
4219 * interested control connections. <b>routers</b> is a list of
4220 * routerinfo_t's.
4223 control_event_descriptors_changed(smartlist_t *routers)
4225 char *msg;
4227 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
4228 return 0;
4231 smartlist_t *names = smartlist_new();
4232 char *ids;
4233 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
4234 char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
4235 router_get_verbose_nickname(b, ri);
4236 smartlist_add(names, b);
4238 ids = smartlist_join_strings(names, " ", 0, NULL);
4239 tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
4240 send_control_event_string(EVENT_NEW_DESC, ALL_FORMATS, msg);
4241 tor_free(ids);
4242 tor_free(msg);
4243 SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
4244 smartlist_free(names);
4246 return 0;
4249 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
4250 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
4251 * <b>error</b> is non-NULL, it is an error code describing the failure
4252 * mode of the mapping.
4255 control_event_address_mapped(const char *from, const char *to, time_t expires,
4256 const char *error, const int cached)
4258 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
4259 return 0;
4261 if (expires < 3 || expires == TIME_MAX)
4262 send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
4263 "650 ADDRMAP %s %s NEVER %s%s"
4264 "CACHED=\"%s\"\r\n",
4265 from, to, error?error:"", error?" ":"",
4266 cached?"YES":"NO");
4267 else {
4268 char buf[ISO_TIME_LEN+1];
4269 char buf2[ISO_TIME_LEN+1];
4270 format_local_iso_time(buf,expires);
4271 format_iso_time(buf2,expires);
4272 send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
4273 "650 ADDRMAP %s %s \"%s\""
4274 " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
4275 from, to, buf,
4276 error?error:"", error?" ":"",
4277 buf2, cached?"YES":"NO");
4280 return 0;
4283 /** The authoritative dirserver has received a new descriptor that
4284 * has passed basic syntax checks and is properly self-signed.
4286 * Notify any interested party of the new descriptor and what has
4287 * been done with it, and also optionally give an explanation/reason. */
4289 control_event_or_authdir_new_descriptor(const char *action,
4290 const char *desc, size_t desclen,
4291 const char *msg)
4293 char firstline[1024];
4294 char *buf;
4295 size_t totallen;
4296 char *esc = NULL;
4297 size_t esclen;
4299 if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
4300 return 0;
4302 tor_snprintf(firstline, sizeof(firstline),
4303 "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
4304 action,
4305 msg ? msg : "");
4307 /* Escape the server descriptor properly */
4308 esclen = write_escaped_data(desc, desclen, &esc);
4310 totallen = strlen(firstline) + esclen + 1;
4311 buf = tor_malloc(totallen);
4312 strlcpy(buf, firstline, totallen);
4313 strlcpy(buf+strlen(firstline), esc, totallen);
4314 send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
4315 buf);
4316 send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
4317 "650 OK\r\n");
4318 tor_free(esc);
4319 tor_free(buf);
4321 return 0;
4324 /** Helper function for NS-style events. Constructs and sends an event
4325 * of type <b>event</b> with string <b>event_string</b> out of the set of
4326 * networkstatuses <b>statuses</b>. Currently it is used for NS events
4327 * and NEWCONSENSUS events. */
4328 static int
4329 control_event_networkstatus_changed_helper(smartlist_t *statuses,
4330 uint16_t event,
4331 const char *event_string)
4333 smartlist_t *strs;
4334 char *s, *esc = NULL;
4335 if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
4336 return 0;
4338 strs = smartlist_new();
4339 smartlist_add(strs, tor_strdup("650+"));
4340 smartlist_add(strs, tor_strdup(event_string));
4341 smartlist_add(strs, tor_strdup("\r\n"));
4342 SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
4344 s = networkstatus_getinfo_helper_single(rs);
4345 if (!s) continue;
4346 smartlist_add(strs, s);
4349 s = smartlist_join_strings(strs, "", 0, NULL);
4350 write_escaped_data(s, strlen(s), &esc);
4351 SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
4352 smartlist_free(strs);
4353 tor_free(s);
4354 send_control_event_string(event, ALL_FORMATS, esc);
4355 send_control_event_string(event, ALL_FORMATS,
4356 "650 OK\r\n");
4358 tor_free(esc);
4359 return 0;
4362 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
4363 * an NS event to any controller that cares. */
4365 control_event_networkstatus_changed(smartlist_t *statuses)
4367 return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
4370 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
4371 * event consisting of an NS-style line for each relay in the consensus. */
4373 control_event_newconsensus(const networkstatus_t *consensus)
4375 if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
4376 return 0;
4377 return control_event_networkstatus_changed_helper(
4378 consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
4381 /** Called when we compute a new circuitbuildtimeout */
4383 control_event_buildtimeout_set(buildtimeout_set_event_t type,
4384 const char *args)
4386 const char *type_string = NULL;
4388 if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
4389 return 0;
4391 switch (type) {
4392 case BUILDTIMEOUT_SET_EVENT_COMPUTED:
4393 type_string = "COMPUTED";
4394 break;
4395 case BUILDTIMEOUT_SET_EVENT_RESET:
4396 type_string = "RESET";
4397 break;
4398 case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
4399 type_string = "SUSPENDED";
4400 break;
4401 case BUILDTIMEOUT_SET_EVENT_DISCARD:
4402 type_string = "DISCARD";
4403 break;
4404 case BUILDTIMEOUT_SET_EVENT_RESUME:
4405 type_string = "RESUME";
4406 break;
4407 default:
4408 type_string = "UNKNOWN";
4409 break;
4412 send_control_event(EVENT_BUILDTIMEOUT_SET, ALL_FORMATS,
4413 "650 BUILDTIMEOUT_SET %s %s\r\n",
4414 type_string, args);
4416 return 0;
4419 /** Called when a signal has been processed from signal_callback */
4421 control_event_signal(uintptr_t signal)
4423 const char *signal_string = NULL;
4425 if (!control_event_is_interesting(EVENT_SIGNAL))
4426 return 0;
4428 switch (signal) {
4429 case SIGHUP:
4430 signal_string = "RELOAD";
4431 break;
4432 case SIGUSR1:
4433 signal_string = "DUMP";
4434 break;
4435 case SIGUSR2:
4436 signal_string = "DEBUG";
4437 break;
4438 case SIGNEWNYM:
4439 signal_string = "NEWNYM";
4440 break;
4441 case SIGCLEARDNSCACHE:
4442 signal_string = "CLEARDNSCACHE";
4443 break;
4444 default:
4445 log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
4446 (unsigned long)signal);
4447 return -1;
4450 send_control_event(EVENT_SIGNAL, ALL_FORMATS, "650 SIGNAL %s\r\n",
4451 signal_string);
4452 return 0;
4455 /** Called when a single local_routerstatus_t has changed: Sends an NS event
4456 * to any controller that cares. */
4458 control_event_networkstatus_changed_single(const routerstatus_t *rs)
4460 smartlist_t *statuses;
4461 int r;
4463 if (!EVENT_IS_INTERESTING(EVENT_NS))
4464 return 0;
4466 statuses = smartlist_new();
4467 smartlist_add(statuses, (void*)rs);
4468 r = control_event_networkstatus_changed(statuses);
4469 smartlist_free(statuses);
4470 return r;
4473 /** Our own router descriptor has changed; tell any controllers that care.
4476 control_event_my_descriptor_changed(void)
4478 send_control_event(EVENT_DESCCHANGED, ALL_FORMATS, "650 DESCCHANGED\r\n");
4479 return 0;
4482 /** Helper: sends a status event where <b>type</b> is one of
4483 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
4484 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
4485 * string corresponding to <b>args</b>. */
4486 static int
4487 control_event_status(int type, int severity, const char *format, va_list args)
4489 char *user_buf = NULL;
4490 char format_buf[160];
4491 const char *status, *sev;
4493 switch (type) {
4494 case EVENT_STATUS_GENERAL:
4495 status = "STATUS_GENERAL";
4496 break;
4497 case EVENT_STATUS_CLIENT:
4498 status = "STATUS_CLIENT";
4499 break;
4500 case EVENT_STATUS_SERVER:
4501 status = "STATUS_SERVER";
4502 break;
4503 default:
4504 log_warn(LD_BUG, "Unrecognized status type %d", type);
4505 return -1;
4507 switch (severity) {
4508 case LOG_NOTICE:
4509 sev = "NOTICE";
4510 break;
4511 case LOG_WARN:
4512 sev = "WARN";
4513 break;
4514 case LOG_ERR:
4515 sev = "ERR";
4516 break;
4517 default:
4518 log_warn(LD_BUG, "Unrecognized status severity %d", severity);
4519 return -1;
4521 if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
4522 status, sev)<0) {
4523 log_warn(LD_BUG, "Format string too long.");
4524 return -1;
4526 tor_vasprintf(&user_buf, format, args);
4528 send_control_event(type, ALL_FORMATS, "%s %s\r\n", format_buf, user_buf);
4529 tor_free(user_buf);
4530 return 0;
4533 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
4534 * by formatting the arguments using the printf-style <b>format</b>. */
4536 control_event_general_status(int severity, const char *format, ...)
4538 va_list ap;
4539 int r;
4540 if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
4541 return 0;
4543 va_start(ap, format);
4544 r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
4545 va_end(ap);
4546 return r;
4549 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
4550 * by formatting the arguments using the printf-style <b>format</b>. */
4552 control_event_client_status(int severity, const char *format, ...)
4554 va_list ap;
4555 int r;
4556 if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
4557 return 0;
4559 va_start(ap, format);
4560 r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
4561 va_end(ap);
4562 return r;
4565 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
4566 * by formatting the arguments using the printf-style <b>format</b>. */
4568 control_event_server_status(int severity, const char *format, ...)
4570 va_list ap;
4571 int r;
4572 if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
4573 return 0;
4575 va_start(ap, format);
4576 r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
4577 va_end(ap);
4578 return r;
4581 /** Called when the status of an entry guard with the given <b>nickname</b>
4582 * and identity <b>digest</b> has changed to <b>status</b>: tells any
4583 * controllers that care. */
4585 control_event_guard(const char *nickname, const char *digest,
4586 const char *status)
4588 char hbuf[HEX_DIGEST_LEN+1];
4589 base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
4590 if (!EVENT_IS_INTERESTING(EVENT_GUARD))
4591 return 0;
4594 char buf[MAX_VERBOSE_NICKNAME_LEN+1];
4595 const node_t *node = node_get_by_id(digest);
4596 if (node) {
4597 node_get_verbose_nickname(node, buf);
4598 } else {
4599 tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
4601 send_control_event(EVENT_GUARD, ALL_FORMATS,
4602 "650 GUARD ENTRY %s %s\r\n", buf, status);
4604 return 0;
4607 /** Called when a configuration option changes. This is generally triggered
4608 * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
4609 * a smartlist_t containing (key, value, ...) pairs in sequence.
4610 * <b>value</b> can be NULL. */
4612 control_event_conf_changed(const smartlist_t *elements)
4614 int i;
4615 char *result;
4616 smartlist_t *lines;
4617 if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) ||
4618 smartlist_len(elements) == 0) {
4619 return 0;
4621 lines = smartlist_new();
4622 for (i = 0; i < smartlist_len(elements); i += 2) {
4623 char *k = smartlist_get(elements, i);
4624 char *v = smartlist_get(elements, i+1);
4625 if (v == NULL) {
4626 smartlist_add_asprintf(lines, "650-%s", k);
4627 } else {
4628 smartlist_add_asprintf(lines, "650-%s=%s", k, v);
4631 result = smartlist_join_strings(lines, "\r\n", 0, NULL);
4632 send_control_event(EVENT_CONF_CHANGED, 0,
4633 "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
4634 tor_free(result);
4635 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
4636 smartlist_free(lines);
4637 return 0;
4640 /** Helper: Return a newly allocated string containing a path to the
4641 * file where we store our authentication cookie. */
4642 char *
4643 get_controller_cookie_file_name(void)
4645 const or_options_t *options = get_options();
4646 if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
4647 return tor_strdup(options->CookieAuthFile);
4648 } else {
4649 return get_datadir_fname("control_auth_cookie");
4653 /* Initialize the cookie-based authentication system of the
4654 * ControlPort. If <b>enabled</b> is 0, then disable the cookie
4655 * authentication system. */
4657 init_control_cookie_authentication(int enabled)
4659 char *fname = NULL;
4660 int retval;
4662 if (!enabled) {
4663 authentication_cookie_is_set = 0;
4664 return 0;
4667 fname = get_controller_cookie_file_name();
4668 retval = init_cookie_authentication(fname, "", /* no header */
4669 AUTHENTICATION_COOKIE_LEN,
4670 get_options()->CookieAuthFileGroupReadable,
4671 &authentication_cookie,
4672 &authentication_cookie_is_set);
4673 tor_free(fname);
4674 return retval;
4677 /** A copy of the process specifier of Tor's owning controller, or
4678 * NULL if this Tor instance is not currently owned by a process. */
4679 static char *owning_controller_process_spec = NULL;
4681 /** A process-termination monitor for Tor's owning controller, or NULL
4682 * if this Tor instance is not currently owned by a process. */
4683 static tor_process_monitor_t *owning_controller_process_monitor = NULL;
4685 static void owning_controller_procmon_cb(void *unused) ATTR_NORETURN;
4687 /** Process-termination monitor callback for Tor's owning controller
4688 * process. */
4689 static void
4690 owning_controller_procmon_cb(void *unused)
4692 (void)unused;
4694 lost_owning_controller("process", "vanished");
4697 /** Set <b>process_spec</b> as Tor's owning controller process.
4698 * Exit on failure. */
4699 void
4700 monitor_owning_controller_process(const char *process_spec)
4702 const char *msg;
4704 tor_assert((owning_controller_process_spec == NULL) ==
4705 (owning_controller_process_monitor == NULL));
4707 if (owning_controller_process_spec != NULL) {
4708 if ((process_spec != NULL) && !strcmp(process_spec,
4709 owning_controller_process_spec)) {
4710 /* Same process -- return now, instead of disposing of and
4711 * recreating the process-termination monitor. */
4712 return;
4715 /* We are currently owned by a process, and we should no longer be
4716 * owned by it. Free the process-termination monitor. */
4717 tor_process_monitor_free(owning_controller_process_monitor);
4718 owning_controller_process_monitor = NULL;
4720 tor_free(owning_controller_process_spec);
4721 owning_controller_process_spec = NULL;
4724 tor_assert((owning_controller_process_spec == NULL) &&
4725 (owning_controller_process_monitor == NULL));
4727 if (process_spec == NULL)
4728 return;
4730 owning_controller_process_spec = tor_strdup(process_spec);
4731 owning_controller_process_monitor =
4732 tor_process_monitor_new(tor_libevent_get_base(),
4733 owning_controller_process_spec,
4734 LD_CONTROL,
4735 owning_controller_procmon_cb, NULL,
4736 &msg);
4738 if (owning_controller_process_monitor == NULL) {
4739 log_err(LD_BUG, "Couldn't create process-termination monitor for "
4740 "owning controller: %s. Exiting.",
4741 msg);
4742 owning_controller_process_spec = NULL;
4743 tor_cleanup();
4744 exit(0);
4748 /** Convert the name of a bootstrapping phase <b>s</b> into strings
4749 * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
4750 static int
4751 bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
4752 const char **summary)
4754 switch (s) {
4755 case BOOTSTRAP_STATUS_UNDEF:
4756 *tag = "undef";
4757 *summary = "Undefined";
4758 break;
4759 case BOOTSTRAP_STATUS_STARTING:
4760 *tag = "starting";
4761 *summary = "Starting";
4762 break;
4763 case BOOTSTRAP_STATUS_CONN_DIR:
4764 *tag = "conn_dir";
4765 *summary = "Connecting to directory server";
4766 break;
4767 case BOOTSTRAP_STATUS_HANDSHAKE:
4768 *tag = "status_handshake";
4769 *summary = "Finishing handshake";
4770 break;
4771 case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
4772 *tag = "handshake_dir";
4773 *summary = "Finishing handshake with directory server";
4774 break;
4775 case BOOTSTRAP_STATUS_ONEHOP_CREATE:
4776 *tag = "onehop_create";
4777 *summary = "Establishing an encrypted directory connection";
4778 break;
4779 case BOOTSTRAP_STATUS_REQUESTING_STATUS:
4780 *tag = "requesting_status";
4781 *summary = "Asking for networkstatus consensus";
4782 break;
4783 case BOOTSTRAP_STATUS_LOADING_STATUS:
4784 *tag = "loading_status";
4785 *summary = "Loading networkstatus consensus";
4786 break;
4787 case BOOTSTRAP_STATUS_LOADING_KEYS:
4788 *tag = "loading_keys";
4789 *summary = "Loading authority key certs";
4790 break;
4791 case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
4792 *tag = "requesting_descriptors";
4793 *summary = "Asking for relay descriptors";
4794 break;
4795 case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
4796 *tag = "loading_descriptors";
4797 *summary = "Loading relay descriptors";
4798 break;
4799 case BOOTSTRAP_STATUS_CONN_OR:
4800 *tag = "conn_or";
4801 *summary = "Connecting to the Tor network";
4802 break;
4803 case BOOTSTRAP_STATUS_HANDSHAKE_OR:
4804 *tag = "handshake_or";
4805 *summary = "Finishing handshake with first hop";
4806 break;
4807 case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
4808 *tag = "circuit_create";
4809 *summary = "Establishing a Tor circuit";
4810 break;
4811 case BOOTSTRAP_STATUS_DONE:
4812 *tag = "done";
4813 *summary = "Done";
4814 break;
4815 default:
4816 // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
4817 *tag = *summary = "unknown";
4818 return -1;
4820 return 0;
4823 /** What percentage through the bootstrap process are we? We remember
4824 * this so we can avoid sending redundant bootstrap status events, and
4825 * so we can guess context for the bootstrap messages which are
4826 * ambiguous. It starts at 'undef', but gets set to 'starting' while
4827 * Tor initializes. */
4828 static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
4830 /** As bootstrap_percent, but holds the bootstrapping level at which we last
4831 * logged a NOTICE-level message. We use this, plus BOOTSTRAP_PCT_INCREMENT,
4832 * to avoid flooding the log with a new message every time we get a few more
4833 * microdescriptors */
4834 static int notice_bootstrap_percent = 0;
4836 /** How many problems have we had getting to the next bootstrapping phase?
4837 * These include failure to establish a connection to a Tor relay,
4838 * failures to finish the TLS handshake, failures to validate the
4839 * consensus document, etc. */
4840 static int bootstrap_problems = 0;
4842 /** We only tell the controller once we've hit a threshold of problems
4843 * for the current phase. */
4844 #define BOOTSTRAP_PROBLEM_THRESHOLD 10
4846 /** When our bootstrapping progress level changes, but our bootstrapping
4847 * status has not advanced, we only log at NOTICE when we have made at least
4848 * this much progress.
4850 #define BOOTSTRAP_PCT_INCREMENT 5
4852 /** Called when Tor has made progress at bootstrapping its directory
4853 * information and initial circuits.
4855 * <b>status</b> is the new status, that is, what task we will be doing
4856 * next. <b>progress</b> is zero if we just started this task, else it
4857 * represents progress on the task. */
4858 void
4859 control_event_bootstrap(bootstrap_status_t status, int progress)
4861 const char *tag, *summary;
4862 char buf[BOOTSTRAP_MSG_LEN];
4864 if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
4865 return; /* already bootstrapped; nothing to be done here. */
4867 /* special case for handshaking status, since our TLS handshaking code
4868 * can't distinguish what the connection is going to be for. */
4869 if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
4870 if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
4871 status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
4872 } else {
4873 status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
4877 if (status > bootstrap_percent ||
4878 (progress && progress > bootstrap_percent)) {
4879 int loglevel = LOG_NOTICE;
4880 bootstrap_status_to_string(status, &tag, &summary);
4882 if (status <= bootstrap_percent &&
4883 (progress < notice_bootstrap_percent + BOOTSTRAP_PCT_INCREMENT)) {
4884 /* We log the message at info if the status hasn't advanced, and if less
4885 * than BOOTSTRAP_PCT_INCREMENT progress has been made.
4887 loglevel = LOG_INFO;
4890 tor_log(loglevel, LD_CONTROL,
4891 "Bootstrapped %d%%: %s", progress ? progress : status, summary);
4892 tor_snprintf(buf, sizeof(buf),
4893 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
4894 progress ? progress : status, tag, summary);
4895 tor_snprintf(last_sent_bootstrap_message,
4896 sizeof(last_sent_bootstrap_message),
4897 "NOTICE %s", buf);
4898 control_event_client_status(LOG_NOTICE, "%s", buf);
4899 if (status > bootstrap_percent) {
4900 bootstrap_percent = status; /* new milestone reached */
4902 if (progress > bootstrap_percent) {
4903 /* incremental progress within a milestone */
4904 bootstrap_percent = progress;
4905 bootstrap_problems = 0; /* Progress! Reset our problem counter. */
4907 if (loglevel == LOG_NOTICE &&
4908 bootstrap_percent > notice_bootstrap_percent) {
4909 /* Remember that we gave a notice at this level. */
4910 notice_bootstrap_percent = bootstrap_percent;
4915 /** Called when Tor has failed to make bootstrapping progress in a way
4916 * that indicates a problem. <b>warn</b> gives a hint as to why, and
4917 * <b>reason</b> provides an "or_conn_end_reason" tag. <b>or_conn</b>
4918 * is the connection that caused this problem.
4920 MOCK_IMPL(void,
4921 control_event_bootstrap_problem, (const char *warn, int reason,
4922 or_connection_t *or_conn))
4924 int status = bootstrap_percent;
4925 const char *tag = "", *summary = "";
4926 char buf[BOOTSTRAP_MSG_LEN];
4927 const char *recommendation = "ignore";
4928 int severity;
4930 /* bootstrap_percent must not be in "undefined" state here. */
4931 tor_assert(status >= 0);
4933 if (or_conn->have_noted_bootstrap_problem)
4934 return;
4936 or_conn->have_noted_bootstrap_problem = 1;
4938 if (bootstrap_percent == 100)
4939 return; /* already bootstrapped; nothing to be done here. */
4941 bootstrap_problems++;
4943 if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
4944 recommendation = "warn";
4946 if (reason == END_OR_CONN_REASON_NO_ROUTE)
4947 recommendation = "warn";
4949 /* If we are using bridges and all our OR connections are now
4950 closed, it means that we totally failed to connect to our
4951 bridges. Throw a warning. */
4952 if (get_options()->UseBridges && !any_other_active_or_conns(or_conn))
4953 recommendation = "warn";
4955 if (we_are_hibernating())
4956 recommendation = "ignore";
4958 while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
4959 status--; /* find a recognized status string based on current progress */
4960 status = bootstrap_percent; /* set status back to the actual number */
4962 severity = !strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO;
4964 log_fn(severity,
4965 LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
4966 "count %d; recommendation %s)",
4967 status, summary, warn,
4968 orconn_end_reason_to_control_string(reason),
4969 bootstrap_problems, recommendation);
4971 connection_or_report_broken_states(severity, LD_HANDSHAKE);
4973 tor_snprintf(buf, sizeof(buf),
4974 "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
4975 "COUNT=%d RECOMMENDATION=%s",
4976 bootstrap_percent, tag, summary, warn,
4977 orconn_end_reason_to_control_string(reason), bootstrap_problems,
4978 recommendation);
4979 tor_snprintf(last_sent_bootstrap_message,
4980 sizeof(last_sent_bootstrap_message),
4981 "WARN %s", buf);
4982 control_event_client_status(LOG_WARN, "%s", buf);
4985 /** We just generated a new summary of which countries we've seen clients
4986 * from recently. Send a copy to the controller in case it wants to
4987 * display it for the user. */
4988 void
4989 control_event_clients_seen(const char *controller_str)
4991 send_control_event(EVENT_CLIENTS_SEEN, 0,
4992 "650 CLIENTS_SEEN %s\r\n", controller_str);
4995 /** A new pluggable transport called <b>transport_name</b> was
4996 * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
4997 * "server" or "client" depending on the mode of the pluggable
4998 * transport.
4999 * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
5001 void
5002 control_event_transport_launched(const char *mode, const char *transport_name,
5003 tor_addr_t *addr, uint16_t port)
5005 send_control_event(EVENT_TRANSPORT_LAUNCHED, ALL_FORMATS,
5006 "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
5007 mode, transport_name, fmt_addr(addr), port);
5010 /** Convert rendezvous auth type to string for HS_DESC control events
5012 const char *
5013 rend_auth_type_to_string(rend_auth_type_t auth_type)
5015 const char *str;
5017 switch (auth_type) {
5018 case REND_NO_AUTH:
5019 str = "NO_AUTH";
5020 break;
5021 case REND_BASIC_AUTH:
5022 str = "BASIC_AUTH";
5023 break;
5024 case REND_STEALTH_AUTH:
5025 str = "STEALTH_AUTH";
5026 break;
5027 default:
5028 str = "UNKNOWN";
5031 return str;
5034 /** Return a longname the node whose identity is <b>id_digest</b>. If
5035 * node_get_by_id() returns NULL, base 16 encoding of <b>id_digest</b> is
5036 * returned instead.
5038 * This function is not thread-safe. Each call to this function invalidates
5039 * previous values returned by this function.
5041 MOCK_IMPL(const char *,
5042 node_describe_longname_by_id,(const char *id_digest))
5044 static char longname[MAX_VERBOSE_NICKNAME_LEN+1];
5045 node_get_verbose_nickname_by_id(id_digest, longname);
5046 return longname;
5049 /** send HS_DESC requested event.
5051 * <b>rend_query</b> is used to fetch requested onion address and auth type.
5052 * <b>hs_dir</b> is the description of contacting hs directory.
5053 * <b>desc_id_base32</b> is the ID of requested hs descriptor.
5055 void
5056 control_event_hs_descriptor_requested(const rend_data_t *rend_query,
5057 const char *id_digest,
5058 const char *desc_id_base32)
5060 if (!id_digest || !rend_query || !desc_id_base32) {
5061 log_warn(LD_BUG, "Called with rend_query==%p, "
5062 "id_digest==%p, desc_id_base32==%p",
5063 rend_query, id_digest, desc_id_base32);
5064 return;
5067 send_control_event(EVENT_HS_DESC, ALL_FORMATS,
5068 "650 HS_DESC REQUESTED %s %s %s %s\r\n",
5069 rend_query->onion_address,
5070 rend_auth_type_to_string(rend_query->auth_type),
5071 node_describe_longname_by_id(id_digest),
5072 desc_id_base32);
5075 /** send HS_DESC event after got response from hs directory.
5077 * NOTE: this is an internal function used by following functions:
5078 * control_event_hs_descriptor_received
5079 * control_event_hs_descriptor_failed
5081 * So do not call this function directly.
5083 void
5084 control_event_hs_descriptor_receive_end(const char *action,
5085 const rend_data_t *rend_query,
5086 const char *id_digest)
5088 if (!action || !rend_query || !id_digest) {
5089 log_warn(LD_BUG, "Called with action==%p, rend_query==%p, "
5090 "id_digest==%p", action, rend_query, id_digest);
5091 return;
5094 send_control_event(EVENT_HS_DESC, ALL_FORMATS,
5095 "650 HS_DESC %s %s %s %s\r\n",
5096 action,
5097 rend_query->onion_address,
5098 rend_auth_type_to_string(rend_query->auth_type),
5099 node_describe_longname_by_id(id_digest));
5102 /** send HS_DESC RECEIVED event
5104 * called when a we successfully received a hidden service descriptor.
5106 void
5107 control_event_hs_descriptor_received(const rend_data_t *rend_query,
5108 const char *id_digest)
5110 if (!rend_query || !id_digest) {
5111 log_warn(LD_BUG, "Called with rend_query==%p, id_digest==%p",
5112 rend_query, id_digest);
5113 return;
5115 control_event_hs_descriptor_receive_end("RECEIVED", rend_query, id_digest);
5118 /** send HS_DESC FAILED event
5120 * called when request for hidden service descriptor returned failure.
5122 void
5123 control_event_hs_descriptor_failed(const rend_data_t *rend_query,
5124 const char *id_digest)
5126 if (!rend_query || !id_digest) {
5127 log_warn(LD_BUG, "Called with rend_query==%p, id_digest==%p",
5128 rend_query, id_digest);
5129 return;
5131 control_event_hs_descriptor_receive_end("FAILED", rend_query, id_digest);
5134 /** Free any leftover allocated memory of the control.c subsystem. */
5135 void
5136 control_free_all(void)
5138 if (authentication_cookie) /* Free the auth cookie */
5139 tor_free(authentication_cookie);
5142 #ifdef TOR_UNIT_TESTS
5143 /* For testing: change the value of global_event_mask */
5144 void
5145 control_testing_set_global_event_mask(uint64_t mask)
5147 global_event_mask = mask;
5149 #endif