aboutsummaryrefslogtreecommitdiff
path: root/src/feature/control/control_events.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/feature/control/control_events.c')
-rw-r--r--src/feature/control/control_events.c2314
1 files changed, 2314 insertions, 0 deletions
diff --git a/src/feature/control/control_events.c b/src/feature/control/control_events.c
new file mode 100644
index 0000000000..916ccea875
--- /dev/null
+++ b/src/feature/control/control_events.c
@@ -0,0 +1,2314 @@
+/* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2020, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+/**
+ * \file control_events.c
+ * \brief Implement the event-reporting part of the controller API.
+ **/
+
+#define CONTROL_MODULE_PRIVATE
+#define CONTROL_EVENTS_PRIVATE
+#define OCIRC_EVENT_PRIVATE
+
+#include "core/or/or.h"
+#include "app/config/config.h"
+#include "core/mainloop/connection.h"
+#include "core/mainloop/mainloop.h"
+#include "core/or/channeltls.h"
+#include "core/or/circuitlist.h"
+#include "core/or/command.h"
+#include "core/or/connection_edge.h"
+#include "core/or/connection_or.h"
+#include "core/or/reasons.h"
+#include "feature/control/control.h"
+#include "feature/control/control_events.h"
+#include "feature/control/control_fmt.h"
+#include "feature/control/control_proto.h"
+#include "feature/dircommon/directory.h"
+#include "feature/nodelist/describe.h"
+#include "feature/nodelist/networkstatus.h"
+#include "feature/nodelist/nodelist.h"
+
+#include "feature/control/control_connection_st.h"
+#include "core/or/entry_connection_st.h"
+#include "feature/nodelist/networkstatus_st.h"
+#include "core/or/or_connection_st.h"
+#include "core/or/or_circuit_st.h"
+#include "core/or/origin_circuit_st.h"
+
+#include "lib/evloop/compat_libevent.h"
+#include "lib/encoding/confline.h"
+
+static void flush_queued_events_cb(mainloop_event_t *event, void *arg);
+static void control_get_bytes_rw_last_sec(uint64_t *r, uint64_t *w);
+
+/** Yield true iff <b>s</b> is the state of a control_connection_t that has
+ * finished authentication and is accepting commands. */
+#define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
+
+/** An event mask of all the events that any controller is interested in
+ * receiving. */
+static event_mask_t global_event_mask = 0;
+
+/** True iff we have disabled log messages from being sent to the controller */
+static int disable_log_messages = 0;
+
+/** Macro: true if any control connection is interested in events of type
+ * <b>e</b>. */
+#define EVENT_IS_INTERESTING(e) \
+ (!! (global_event_mask & EVENT_MASK_(e)))
+
+/** Macro: true if any event from the bitfield 'e' is interesting. */
+#define ANY_EVENT_IS_INTERESTING(e) \
+ (!! (global_event_mask & (e)))
+
+static void send_control_event_impl(uint16_t event,
+ const char *format, va_list ap)
+ CHECK_PRINTF(2,0);
+static int control_event_status(int type, int severity, const char *format,
+ va_list args)
+ CHECK_PRINTF(3,0);
+
+static void send_control_event(uint16_t event,
+ const char *format, ...)
+ CHECK_PRINTF(2,3);
+
+/** Table mapping event values to their names. Used to implement SETEVENTS
+ * and GETINFO events/names, and to keep they in sync. */
+const struct control_event_t control_event_table[] = {
+ { EVENT_CIRCUIT_STATUS, "CIRC" },
+ { EVENT_CIRCUIT_STATUS_MINOR, "CIRC_MINOR" },
+ { EVENT_STREAM_STATUS, "STREAM" },
+ { EVENT_OR_CONN_STATUS, "ORCONN" },
+ { EVENT_BANDWIDTH_USED, "BW" },
+ { EVENT_DEBUG_MSG, "DEBUG" },
+ { EVENT_INFO_MSG, "INFO" },
+ { EVENT_NOTICE_MSG, "NOTICE" },
+ { EVENT_WARN_MSG, "WARN" },
+ { EVENT_ERR_MSG, "ERR" },
+ { EVENT_NEW_DESC, "NEWDESC" },
+ { EVENT_ADDRMAP, "ADDRMAP" },
+ { EVENT_DESCCHANGED, "DESCCHANGED" },
+ { EVENT_NS, "NS" },
+ { EVENT_STATUS_GENERAL, "STATUS_GENERAL" },
+ { EVENT_STATUS_CLIENT, "STATUS_CLIENT" },
+ { EVENT_STATUS_SERVER, "STATUS_SERVER" },
+ { EVENT_GUARD, "GUARD" },
+ { EVENT_STREAM_BANDWIDTH_USED, "STREAM_BW" },
+ { EVENT_CLIENTS_SEEN, "CLIENTS_SEEN" },
+ { EVENT_NEWCONSENSUS, "NEWCONSENSUS" },
+ { EVENT_BUILDTIMEOUT_SET, "BUILDTIMEOUT_SET" },
+ { EVENT_GOT_SIGNAL, "SIGNAL" },
+ { EVENT_CONF_CHANGED, "CONF_CHANGED"},
+ { EVENT_CONN_BW, "CONN_BW" },
+ { EVENT_CELL_STATS, "CELL_STATS" },
+ { EVENT_CIRC_BANDWIDTH_USED, "CIRC_BW" },
+ { EVENT_TRANSPORT_LAUNCHED, "TRANSPORT_LAUNCHED" },
+ { EVENT_HS_DESC, "HS_DESC" },
+ { EVENT_HS_DESC_CONTENT, "HS_DESC_CONTENT" },
+ { EVENT_NETWORK_LIVENESS, "NETWORK_LIVENESS" },
+ { 0, NULL },
+};
+
+/** Given a log severity, return the corresponding control event code. */
+static inline int
+log_severity_to_event(int severity)
+{
+ switch (severity) {
+ case LOG_DEBUG: return EVENT_DEBUG_MSG;
+ case LOG_INFO: return EVENT_INFO_MSG;
+ case LOG_NOTICE: return EVENT_NOTICE_MSG;
+ case LOG_WARN: return EVENT_WARN_MSG;
+ case LOG_ERR: return EVENT_ERR_MSG;
+ default: return -1;
+ }
+}
+
+/** Helper: clear bandwidth counters of all origin circuits. */
+static void
+clear_circ_bw_fields(void)
+{
+ origin_circuit_t *ocirc;
+ SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
+ if (!CIRCUIT_IS_ORIGIN(circ))
+ continue;
+ ocirc = TO_ORIGIN_CIRCUIT(circ);
+ ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
+ ocirc->n_overhead_written_circ_bw = ocirc->n_overhead_read_circ_bw = 0;
+ ocirc->n_delivered_written_circ_bw = ocirc->n_delivered_read_circ_bw = 0;
+ }
+ SMARTLIST_FOREACH_END(circ);
+}
+
+/** Set <b>global_event_mask*</b> to the bitwise OR of each live control
+ * connection's event_mask field. */
+void
+control_update_global_event_mask(void)
+{
+ smartlist_t *conns = get_connection_array();
+ event_mask_t old_mask, new_mask;
+ old_mask = global_event_mask;
+ int any_old_per_sec_events = control_any_per_second_event_enabled();
+
+ global_event_mask = 0;
+ SMARTLIST_FOREACH(conns, connection_t *, _conn,
+ {
+ if (_conn->type == CONN_TYPE_CONTROL &&
+ STATE_IS_OPEN(_conn->state)) {
+ control_connection_t *conn = TO_CONTROL_CONN(_conn);
+ global_event_mask |= conn->event_mask;
+ }
+ });
+
+ new_mask = global_event_mask;
+
+ /* Handle the aftermath. Set up the log callback to tell us only what
+ * we want to hear...*/
+ control_adjust_event_log_severity();
+
+ /* Macro: true if ev was false before and is true now. */
+#define NEWLY_ENABLED(ev) \
+ (! (old_mask & (ev)) && (new_mask & (ev)))
+
+ /* ...then, if we've started logging stream or circ bw, clear the
+ * appropriate fields. */
+ if (NEWLY_ENABLED(EVENT_STREAM_BANDWIDTH_USED)) {
+ SMARTLIST_FOREACH(conns, connection_t *, conn,
+ {
+ if (conn->type == CONN_TYPE_AP) {
+ edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
+ edge_conn->n_written = edge_conn->n_read = 0;
+ }
+ });
+ }
+ if (NEWLY_ENABLED(EVENT_CIRC_BANDWIDTH_USED)) {
+ clear_circ_bw_fields();
+ }
+ if (NEWLY_ENABLED(EVENT_BANDWIDTH_USED)) {
+ uint64_t r, w;
+ control_get_bytes_rw_last_sec(&r, &w);
+ }
+ if (any_old_per_sec_events != control_any_per_second_event_enabled()) {
+ rescan_periodic_events(get_options());
+ }
+
+#undef NEWLY_ENABLED
+}
+
+/** Given a control event code for a message event, return the corresponding
+ * log severity. */
+static inline int
+event_to_log_severity(int event)
+{
+ switch (event) {
+ case EVENT_DEBUG_MSG: return LOG_DEBUG;
+ case EVENT_INFO_MSG: return LOG_INFO;
+ case EVENT_NOTICE_MSG: return LOG_NOTICE;
+ case EVENT_WARN_MSG: return LOG_WARN;
+ case EVENT_ERR_MSG: return LOG_ERR;
+ default: return -1;
+ }
+}
+
+/** Adjust the log severities that result in control_event_logmsg being called
+ * to match the severity of log messages that any controllers are interested
+ * in. */
+void
+control_adjust_event_log_severity(void)
+{
+ int i;
+ int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
+
+ for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
+ if (EVENT_IS_INTERESTING(i)) {
+ min_log_event = i;
+ break;
+ }
+ }
+ for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
+ if (EVENT_IS_INTERESTING(i)) {
+ max_log_event = i;
+ break;
+ }
+ }
+ if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
+ if (min_log_event > EVENT_NOTICE_MSG)
+ min_log_event = EVENT_NOTICE_MSG;
+ if (max_log_event < EVENT_ERR_MSG)
+ max_log_event = EVENT_ERR_MSG;
+ }
+ if (min_log_event <= max_log_event)
+ change_callback_log_severity(event_to_log_severity(min_log_event),
+ event_to_log_severity(max_log_event),
+ control_event_logmsg);
+ else
+ change_callback_log_severity(LOG_ERR, LOG_ERR,
+ control_event_logmsg);
+}
+
+/** Return true iff the event with code <b>c</b> is being sent to any current
+ * control connection. This is useful if the amount of work needed to prepare
+ * to call the appropriate control_event_...() function is high.
+ */
+int
+control_event_is_interesting(int event)
+{
+ return EVENT_IS_INTERESTING(event);
+}
+
+/** Return true if any event that needs to fire once a second is enabled. */
+int
+control_any_per_second_event_enabled(void)
+{
+ return ANY_EVENT_IS_INTERESTING(
+ EVENT_MASK_(EVENT_BANDWIDTH_USED) |
+ EVENT_MASK_(EVENT_CELL_STATS) |
+ EVENT_MASK_(EVENT_CIRC_BANDWIDTH_USED) |
+ EVENT_MASK_(EVENT_CONN_BW) |
+ EVENT_MASK_(EVENT_STREAM_BANDWIDTH_USED)
+ );
+}
+
+/* The value of 'get_bytes_read()' the previous time that
+ * control_get_bytes_rw_last_sec() as called. */
+static uint64_t stats_prev_n_read = 0;
+/* The value of 'get_bytes_written()' the previous time that
+ * control_get_bytes_rw_last_sec() as called. */
+static uint64_t stats_prev_n_written = 0;
+
+/**
+ * Set <b>n_read</b> and <b>n_written</b> to the total number of bytes read
+ * and written by Tor since the last call to this function.
+ *
+ * Call this only from the main thread.
+ */
+static void
+control_get_bytes_rw_last_sec(uint64_t *n_read,
+ uint64_t *n_written)
+{
+ const uint64_t stats_n_bytes_read = get_bytes_read();
+ const uint64_t stats_n_bytes_written = get_bytes_written();
+
+ *n_read = stats_n_bytes_read - stats_prev_n_read;
+ *n_written = stats_n_bytes_written - stats_prev_n_written;
+ stats_prev_n_read = stats_n_bytes_read;
+ stats_prev_n_written = stats_n_bytes_written;
+}
+
+/**
+ * Run all the controller events (if any) that are scheduled to trigger once
+ * per second.
+ */
+void
+control_per_second_events(void)
+{
+ if (!control_any_per_second_event_enabled())
+ return;
+
+ uint64_t bytes_read, bytes_written;
+ control_get_bytes_rw_last_sec(&bytes_read, &bytes_written);
+ control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
+
+ control_event_stream_bandwidth_used();
+ control_event_conn_bandwidth_used();
+ control_event_circ_bandwidth_used();
+ control_event_circuit_cell_stats();
+}
+
+/** Represents an event that's queued to be sent to one or more
+ * controllers. */
+typedef struct queued_event_t {
+ uint16_t event;
+ char *msg;
+} queued_event_t;
+
+/** Pointer to int. If this is greater than 0, we don't allow new events to be
+ * queued. */
+static tor_threadlocal_t block_event_queue_flag;
+
+/** Holds a smartlist of queued_event_t objects that may need to be sent
+ * to one or more controllers */
+static smartlist_t *queued_control_events = NULL;
+
+/** True if the flush_queued_events_event is pending. */
+static int flush_queued_event_pending = 0;
+
+/** Lock to protect the above fields. */
+static tor_mutex_t *queued_control_events_lock = NULL;
+
+/** An event that should fire in order to flush the contents of
+ * queued_control_events. */
+static mainloop_event_t *flush_queued_events_event = NULL;
+
+void
+control_initialize_event_queue(void)
+{
+ if (queued_control_events == NULL) {
+ queued_control_events = smartlist_new();
+ }
+
+ if (flush_queued_events_event == NULL) {
+ struct event_base *b = tor_libevent_get_base();
+ if (b) {
+ flush_queued_events_event =
+ mainloop_event_new(flush_queued_events_cb, NULL);
+ tor_assert(flush_queued_events_event);
+ }
+ }
+
+ if (queued_control_events_lock == NULL) {
+ queued_control_events_lock = tor_mutex_new();
+ tor_threadlocal_init(&block_event_queue_flag);
+ }
+}
+
+static int *
+get_block_event_queue(void)
+{
+ int *val = tor_threadlocal_get(&block_event_queue_flag);
+ if (PREDICT_UNLIKELY(val == NULL)) {
+ val = tor_malloc_zero(sizeof(int));
+ tor_threadlocal_set(&block_event_queue_flag, val);
+ }
+ return val;
+}
+
+/** Helper: inserts an event on the list of events queued to be sent to
+ * one or more controllers, and schedules the events to be flushed if needed.
+ *
+ * This function takes ownership of <b>msg</b>, and may free it.
+ *
+ * We queue these events rather than send them immediately in order to break
+ * the dependency in our callgraph from code that generates events for the
+ * controller, and the network layer at large. Otherwise, nearly every
+ * interesting part of Tor would potentially call every other interesting part
+ * of Tor.
+ */
+MOCK_IMPL(STATIC void,
+queue_control_event_string,(uint16_t event, char *msg))
+{
+ /* This is redundant with checks done elsewhere, but it's a last-ditch
+ * attempt to avoid queueing something we shouldn't have to queue. */
+ if (PREDICT_UNLIKELY( ! EVENT_IS_INTERESTING(event) )) {
+ tor_free(msg);
+ return;
+ }
+
+ int *block_event_queue = get_block_event_queue();
+ if (*block_event_queue) {
+ tor_free(msg);
+ return;
+ }
+
+ queued_event_t *ev = tor_malloc(sizeof(*ev));
+ ev->event = event;
+ ev->msg = msg;
+
+ /* No queueing an event while queueing an event */
+ ++*block_event_queue;
+
+ tor_mutex_acquire(queued_control_events_lock);
+ tor_assert(queued_control_events);
+ smartlist_add(queued_control_events, ev);
+
+ int activate_event = 0;
+ if (! flush_queued_event_pending && in_main_thread()) {
+ activate_event = 1;
+ flush_queued_event_pending = 1;
+ }
+
+ tor_mutex_release(queued_control_events_lock);
+
+ --*block_event_queue;
+
+ /* We just put an event on the queue; mark the queue to be
+ * flushed. We only do this from the main thread for now; otherwise,
+ * we'd need to incur locking overhead in Libevent or use a socket.
+ */
+ if (activate_event) {
+ tor_assert(flush_queued_events_event);
+ mainloop_event_activate(flush_queued_events_event);
+ }
+}
+
+#define queued_event_free(ev) \
+ FREE_AND_NULL(queued_event_t, queued_event_free_, (ev))
+
+/** Release all storage held by <b>ev</b>. */
+static void
+queued_event_free_(queued_event_t *ev)
+{
+ if (ev == NULL)
+ return;
+
+ tor_free(ev->msg);
+ tor_free(ev);
+}
+
+/** Send every queued event to every controller that's interested in it,
+ * and remove the events from the queue. If <b>force</b> is true,
+ * then make all controllers send their data out immediately, since we
+ * may be about to shut down. */
+static void
+queued_events_flush_all(int force)
+{
+ /* Make sure that we get all the pending log events, if there are any. */
+ flush_pending_log_callbacks();
+
+ if (PREDICT_UNLIKELY(queued_control_events == NULL)) {
+ return;
+ }
+ smartlist_t *all_conns = get_connection_array();
+ smartlist_t *controllers = smartlist_new();
+ smartlist_t *queued_events;
+
+ int *block_event_queue = get_block_event_queue();
+ ++*block_event_queue;
+
+ tor_mutex_acquire(queued_control_events_lock);
+ /* No queueing an event while flushing events. */
+ flush_queued_event_pending = 0;
+ queued_events = queued_control_events;
+ queued_control_events = smartlist_new();
+ tor_mutex_release(queued_control_events_lock);
+
+ /* Gather all the controllers that will care... */
+ SMARTLIST_FOREACH_BEGIN(all_conns, connection_t *, conn) {
+ if (conn->type == CONN_TYPE_CONTROL &&
+ !conn->marked_for_close &&
+ conn->state == CONTROL_CONN_STATE_OPEN) {
+ control_connection_t *control_conn = TO_CONTROL_CONN(conn);
+
+ smartlist_add(controllers, control_conn);
+ }
+ } SMARTLIST_FOREACH_END(conn);
+
+ SMARTLIST_FOREACH_BEGIN(queued_events, queued_event_t *, ev) {
+ const event_mask_t bit = ((event_mask_t)1) << ev->event;
+ const size_t msg_len = strlen(ev->msg);
+ SMARTLIST_FOREACH_BEGIN(controllers, control_connection_t *,
+ control_conn) {
+ if (control_conn->event_mask & bit) {
+ connection_buf_add(ev->msg, msg_len, TO_CONN(control_conn));
+ }
+ } SMARTLIST_FOREACH_END(control_conn);
+
+ queued_event_free(ev);
+ } SMARTLIST_FOREACH_END(ev);
+
+ if (force) {
+ SMARTLIST_FOREACH_BEGIN(controllers, control_connection_t *,
+ control_conn) {
+ connection_flush(TO_CONN(control_conn));
+ } SMARTLIST_FOREACH_END(control_conn);
+ }
+
+ smartlist_free(queued_events);
+ smartlist_free(controllers);
+
+ --*block_event_queue;
+}
+
+/** Libevent callback: Flushes pending events to controllers that are
+ * interested in them. */
+static void
+flush_queued_events_cb(mainloop_event_t *event, void *arg)
+{
+ (void) event;
+ (void) arg;
+ queued_events_flush_all(0);
+}
+
+/** Send an event to all v1 controllers that are listening for code
+ * <b>event</b>. The event's body is given by <b>msg</b>.
+ *
+ * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
+ * respect to the EXTENDED_EVENTS feature. */
+MOCK_IMPL(STATIC void,
+send_control_event_string,(uint16_t event,
+ const char *msg))
+{
+ tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
+ queue_control_event_string(event, tor_strdup(msg));
+}
+
+/** Helper for send_control_event and control_event_status:
+ * Send an event to all v1 controllers that are listening for code
+ * <b>event</b>. The event's body is created by the printf-style format in
+ * <b>format</b>, and other arguments as provided. */
+static void
+send_control_event_impl(uint16_t event,
+ const char *format, va_list ap)
+{
+ char *buf = NULL;
+ int len;
+
+ len = tor_vasprintf(&buf, format, ap);
+ if (len < 0) {
+ log_warn(LD_BUG, "Unable to format event for controller.");
+ return;
+ }
+
+ queue_control_event_string(event, buf);
+}
+
+/** Send an event to all v1 controllers that are listening for code
+ * <b>event</b>. The event's body is created by the printf-style format in
+ * <b>format</b>, and other arguments as provided. */
+static void
+send_control_event(uint16_t event,
+ const char *format, ...)
+{
+ va_list ap;
+ va_start(ap, format);
+ send_control_event_impl(event, format, ap);
+ va_end(ap);
+}
+
+/** Something major has happened to circuit <b>circ</b>: tell any
+ * interested control connections. */
+int
+control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
+ int reason_code)
+{
+ const char *status;
+ char reasons[64] = "";
+
+ if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
+ return 0;
+ tor_assert(circ);
+
+ switch (tp)
+ {
+ case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
+ case CIRC_EVENT_BUILT: status = "BUILT"; break;
+ case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
+ case CIRC_EVENT_FAILED: status = "FAILED"; break;
+ case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
+ default:
+ log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
+ tor_fragile_assert();
+ return 0;
+ }
+
+ if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
+ const char *reason_str = circuit_end_reason_to_control_string(reason_code);
+ char unk_reason_buf[16];
+ if (!reason_str) {
+ tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
+ reason_str = unk_reason_buf;
+ }
+ if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
+ tor_snprintf(reasons, sizeof(reasons),
+ " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
+ } else {
+ tor_snprintf(reasons, sizeof(reasons),
+ " REASON=%s", reason_str);
+ }
+ }
+
+ {
+ char *circdesc = circuit_describe_status_for_controller(circ);
+ const char *sp = strlen(circdesc) ? " " : "";
+ send_control_event(EVENT_CIRCUIT_STATUS,
+ "650 CIRC %lu %s%s%s%s\r\n",
+ (unsigned long)circ->global_identifier,
+ status, sp,
+ circdesc,
+ reasons);
+ tor_free(circdesc);
+ }
+
+ return 0;
+}
+
+/** Something minor has happened to circuit <b>circ</b>: tell any
+ * interested control connections. */
+static int
+control_event_circuit_status_minor(origin_circuit_t *circ,
+ circuit_status_minor_event_t e,
+ int purpose, const struct timeval *tv)
+{
+ const char *event_desc;
+ char event_tail[160] = "";
+ if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
+ return 0;
+ tor_assert(circ);
+
+ switch (e)
+ {
+ case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
+ event_desc = "PURPOSE_CHANGED";
+
+ {
+ /* event_tail can currently be up to 68 chars long */
+ const char *hs_state_str =
+ circuit_purpose_to_controller_hs_state_string(purpose);
+ tor_snprintf(event_tail, sizeof(event_tail),
+ " OLD_PURPOSE=%s%s%s",
+ circuit_purpose_to_controller_string(purpose),
+ (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
+ (hs_state_str != NULL) ? hs_state_str : "");
+ }
+
+ break;
+ case CIRC_MINOR_EVENT_CANNIBALIZED:
+ event_desc = "CANNIBALIZED";
+
+ {
+ /* event_tail can currently be up to 130 chars long */
+ const char *hs_state_str =
+ circuit_purpose_to_controller_hs_state_string(purpose);
+ const struct timeval *old_timestamp_began = tv;
+ char tbuf[ISO_TIME_USEC_LEN+1];
+ format_iso_time_nospace_usec(tbuf, old_timestamp_began);
+
+ tor_snprintf(event_tail, sizeof(event_tail),
+ " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
+ circuit_purpose_to_controller_string(purpose),
+ (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
+ (hs_state_str != NULL) ? hs_state_str : "",
+ tbuf);
+ }
+
+ break;
+ default:
+ log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
+ tor_fragile_assert();
+ return 0;
+ }
+
+ {
+ char *circdesc = circuit_describe_status_for_controller(circ);
+ const char *sp = strlen(circdesc) ? " " : "";
+ send_control_event(EVENT_CIRCUIT_STATUS_MINOR,
+ "650 CIRC_MINOR %lu %s%s%s%s\r\n",
+ (unsigned long)circ->global_identifier,
+ event_desc, sp,
+ circdesc,
+ event_tail);
+ tor_free(circdesc);
+ }
+
+ return 0;
+}
+
+/**
+ * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
+ * interested controllers.
+ */
+int
+control_event_circuit_purpose_changed(origin_circuit_t *circ,
+ int old_purpose)
+{
+ return control_event_circuit_status_minor(circ,
+ CIRC_MINOR_EVENT_PURPOSE_CHANGED,
+ old_purpose,
+ NULL);
+}
+
+/**
+ * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
+ * created-time from <b>old_tv_created</b>: tell any interested controllers.
+ */
+int
+control_event_circuit_cannibalized(origin_circuit_t *circ,
+ int old_purpose,
+ const struct timeval *old_tv_created)
+{
+ return control_event_circuit_status_minor(circ,
+ CIRC_MINOR_EVENT_CANNIBALIZED,
+ old_purpose,
+ old_tv_created);
+}
+
+/** Something has happened to the stream associated with AP connection
+ * <b>conn</b>: tell any interested control connections. */
+int
+control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
+ int reason_code)
+{
+ char reason_buf[64];
+ char addrport_buf[64];
+ const char *status;
+ circuit_t *circ;
+ origin_circuit_t *origin_circ = NULL;
+ char buf[256];
+ const char *purpose = "";
+ tor_assert(conn->socks_request);
+
+ if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
+ return 0;
+
+ if (tp == STREAM_EVENT_CLOSED &&
+ (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
+ return 0;
+
+ write_stream_target_to_buf(conn, buf, sizeof(buf));
+
+ reason_buf[0] = '\0';
+ switch (tp)
+ {
+ case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
+ case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
+ case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
+ case STREAM_EVENT_FAILED: status = "FAILED"; break;
+ case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
+ case STREAM_EVENT_NEW: status = "NEW"; break;
+ case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
+ case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
+ case STREAM_EVENT_REMAP: status = "REMAP"; break;
+ default:
+ log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
+ return 0;
+ }
+ if (reason_code && (tp == STREAM_EVENT_FAILED ||
+ tp == STREAM_EVENT_CLOSED ||
+ tp == STREAM_EVENT_FAILED_RETRIABLE)) {
+ const char *reason_str = stream_end_reason_to_control_string(reason_code);
+ char *r = NULL;
+ if (!reason_str) {
+ tor_asprintf(&r, " UNKNOWN_%d", reason_code);
+ reason_str = r;
+ }
+ if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
+ tor_snprintf(reason_buf, sizeof(reason_buf),
+ " REASON=END REMOTE_REASON=%s", reason_str);
+ else
+ tor_snprintf(reason_buf, sizeof(reason_buf),
+ " REASON=%s", reason_str);
+ tor_free(r);
+ } else if (reason_code && tp == STREAM_EVENT_REMAP) {
+ switch (reason_code) {
+ case REMAP_STREAM_SOURCE_CACHE:
+ strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
+ break;
+ case REMAP_STREAM_SOURCE_EXIT:
+ strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
+ break;
+ default:
+ tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
+ reason_code);
+ /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
+ break;
+ }
+ }
+
+ if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
+ /*
+ * When the control conn is an AF_UNIX socket and we have no address,
+ * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
+ * dnsserv.c.
+ */
+ if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
+ tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
+ ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
+ } else {
+ /*
+ * else leave it blank so control on AF_UNIX doesn't need to make
+ * something up.
+ */
+ addrport_buf[0] = '\0';
+ }
+ } else {
+ addrport_buf[0] = '\0';
+ }
+
+ if (tp == STREAM_EVENT_NEW_RESOLVE) {
+ purpose = " PURPOSE=DNS_REQUEST";
+ } else if (tp == STREAM_EVENT_NEW) {
+ if (conn->use_begindir) {
+ connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
+ int linked_dir_purpose = -1;
+ if (linked && linked->type == CONN_TYPE_DIR)
+ linked_dir_purpose = linked->purpose;
+ if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
+ purpose = " PURPOSE=DIR_UPLOAD";
+ else
+ purpose = " PURPOSE=DIR_FETCH";
+ } else
+ purpose = " PURPOSE=USER";
+ }
+
+ circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
+ if (circ && CIRCUIT_IS_ORIGIN(circ))
+ origin_circ = TO_ORIGIN_CIRCUIT(circ);
+
+ {
+ char *conndesc = entry_connection_describe_status_for_controller(conn);
+ const char *sp = strlen(conndesc) ? " " : "";
+ send_control_event(EVENT_STREAM_STATUS,
+ "650 STREAM %"PRIu64" %s %lu %s%s%s%s%s%s\r\n",
+ (ENTRY_TO_CONN(conn)->global_identifier),
+ status,
+ origin_circ?
+ (unsigned long)origin_circ->global_identifier : 0ul,
+ buf, reason_buf, addrport_buf, purpose, sp, conndesc);
+ tor_free(conndesc);
+ }
+
+ /* XXX need to specify its intended exit, etc? */
+
+ return 0;
+}
+
+/** Called when the status of an OR connection <b>conn</b> changes: tell any
+ * interested control connections. <b>tp</b> is the new status for the
+ * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
+ * may be the reason why.
+ */
+int
+control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
+ int reason)
+{
+ int ncircs = 0;
+ const char *status;
+ char name[128];
+ char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
+
+ if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
+ return 0;
+
+ switch (tp)
+ {
+ case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
+ case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
+ case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
+ case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
+ case OR_CONN_EVENT_NEW: status = "NEW"; break;
+ default:
+ log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
+ return 0;
+ }
+ if (conn->chan) {
+ ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
+ } else {
+ ncircs = 0;
+ }
+ ncircs += connection_or_get_num_circuits(conn);
+ if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
+ tor_snprintf(ncircs_buf, sizeof(ncircs_buf), " NCIRCS=%d", ncircs);
+ }
+
+ orconn_target_get_name(name, sizeof(name), conn);
+ send_control_event(EVENT_OR_CONN_STATUS,
+ "650 ORCONN %s %s%s%s%s ID=%"PRIu64"\r\n",
+ name, status,
+ reason ? " REASON=" : "",
+ orconn_end_reason_to_control_string(reason),
+ ncircs_buf,
+ (conn->base_.global_identifier));
+
+ return 0;
+}
+
+/**
+ * Print out STREAM_BW event for a single conn
+ */
+int
+control_event_stream_bandwidth(edge_connection_t *edge_conn)
+{
+ struct timeval now;
+ char tbuf[ISO_TIME_USEC_LEN+1];
+ if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
+ if (!edge_conn->n_read && !edge_conn->n_written)
+ return 0;
+
+ tor_gettimeofday(&now);
+ format_iso_time_nospace_usec(tbuf, &now);
+ send_control_event(EVENT_STREAM_BANDWIDTH_USED,
+ "650 STREAM_BW %"PRIu64" %lu %lu %s\r\n",
+ (edge_conn->base_.global_identifier),
+ (unsigned long)edge_conn->n_read,
+ (unsigned long)edge_conn->n_written,
+ tbuf);
+
+ edge_conn->n_written = edge_conn->n_read = 0;
+ }
+
+ return 0;
+}
+
+/** A second or more has elapsed: tell any interested control
+ * connections how much bandwidth streams have used. */
+int
+control_event_stream_bandwidth_used(void)
+{
+ if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
+ smartlist_t *conns = get_connection_array();
+ edge_connection_t *edge_conn;
+ struct timeval now;
+ char tbuf[ISO_TIME_USEC_LEN+1];
+
+ SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
+ {
+ if (conn->type != CONN_TYPE_AP)
+ continue;
+ edge_conn = TO_EDGE_CONN(conn);
+ if (!edge_conn->n_read && !edge_conn->n_written)
+ continue;
+
+ tor_gettimeofday(&now);
+ format_iso_time_nospace_usec(tbuf, &now);
+ send_control_event(EVENT_STREAM_BANDWIDTH_USED,
+ "650 STREAM_BW %"PRIu64" %lu %lu %s\r\n",
+ (edge_conn->base_.global_identifier),
+ (unsigned long)edge_conn->n_read,
+ (unsigned long)edge_conn->n_written,
+ tbuf);
+
+ edge_conn->n_written = edge_conn->n_read = 0;
+ }
+ SMARTLIST_FOREACH_END(conn);
+ }
+
+ return 0;
+}
+
+/** A second or more has elapsed: tell any interested control connections
+ * how much bandwidth origin circuits have used. */
+int
+control_event_circ_bandwidth_used(void)
+{
+ if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
+ return 0;
+
+ SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
+ if (!CIRCUIT_IS_ORIGIN(circ))
+ continue;
+
+ control_event_circ_bandwidth_used_for_circ(TO_ORIGIN_CIRCUIT(circ));
+ }
+ SMARTLIST_FOREACH_END(circ);
+
+ return 0;
+}
+
+/**
+ * Emit a CIRC_BW event line for a specific circuit.
+ *
+ * This function sets the values it emits to 0, and does not emit
+ * an event if there is no new data to report since the last call.
+ *
+ * Therefore, it may be called at any frequency.
+ */
+int
+control_event_circ_bandwidth_used_for_circ(origin_circuit_t *ocirc)
+{
+ struct timeval now;
+ char tbuf[ISO_TIME_USEC_LEN+1];
+
+ tor_assert(ocirc);
+
+ if (!EVENT