Update copyrights to 2021, using "make update-copyright"
[tor.git] / src / feature / control / control_events.c
blobe2aca6c03eedca357f17770e2efc0a195f7176b9
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2021, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file control_events.c
7 * \brief Implement the event-reporting part of the controller API.
8 **/
10 #define CONTROL_MODULE_PRIVATE
11 #define CONTROL_EVENTS_PRIVATE
12 #define OCIRC_EVENT_PRIVATE
14 #include "core/or/or.h"
15 #include "app/config/config.h"
16 #include "core/mainloop/connection.h"
17 #include "core/mainloop/mainloop.h"
18 #include "core/or/channeltls.h"
19 #include "core/or/circuitlist.h"
20 #include "core/or/circuitstats.h"
21 #include "core/or/command.h"
22 #include "core/or/connection_edge.h"
23 #include "core/or/connection_or.h"
24 #include "core/or/reasons.h"
25 #include "feature/control/control.h"
26 #include "feature/control/control_events.h"
27 #include "feature/control/control_fmt.h"
28 #include "feature/control/control_proto.h"
29 #include "feature/dircommon/directory.h"
30 #include "feature/nodelist/describe.h"
31 #include "feature/nodelist/networkstatus.h"
32 #include "feature/nodelist/nodelist.h"
34 #include "feature/control/control_connection_st.h"
35 #include "core/or/entry_connection_st.h"
36 #include "feature/nodelist/networkstatus_st.h"
37 #include "core/or/or_connection_st.h"
38 #include "core/or/or_circuit_st.h"
39 #include "core/or/origin_circuit_st.h"
41 #include "lib/evloop/compat_libevent.h"
42 #include "lib/encoding/confline.h"
44 static void flush_queued_events_cb(mainloop_event_t *event, void *arg);
45 static void control_get_bytes_rw_last_sec(uint64_t *r, uint64_t *w);
47 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
48 * finished authentication and is accepting commands. */
49 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
51 /** An event mask of all the events that any controller is interested in
52 * receiving. */
53 static event_mask_t global_event_mask = 0;
55 /** True iff we have disabled log messages from being sent to the controller */
56 static int disable_log_messages = 0;
58 /** Macro: true if any control connection is interested in events of type
59 * <b>e</b>. */
60 #define EVENT_IS_INTERESTING(e) \
61 (!! (global_event_mask & EVENT_MASK_(e)))
63 /** Macro: true if any event from the bitfield 'e' is interesting. */
64 #define ANY_EVENT_IS_INTERESTING(e) \
65 (!! (global_event_mask & (e)))
67 static void send_control_event_impl(uint16_t event,
68 const char *format, va_list ap)
69 CHECK_PRINTF(2,0);
70 static int control_event_status(int type, int severity, const char *format,
71 va_list args)
72 CHECK_PRINTF(3,0);
74 static void send_control_event(uint16_t event,
75 const char *format, ...)
76 CHECK_PRINTF(2,3);
78 /** Table mapping event values to their names. Used to implement SETEVENTS
79 * and GETINFO events/names, and to keep they in sync. */
80 const struct control_event_t control_event_table[] = {
81 { EVENT_CIRCUIT_STATUS, "CIRC" },
82 { EVENT_CIRCUIT_STATUS_MINOR, "CIRC_MINOR" },
83 { EVENT_STREAM_STATUS, "STREAM" },
84 { EVENT_OR_CONN_STATUS, "ORCONN" },
85 { EVENT_BANDWIDTH_USED, "BW" },
86 { EVENT_DEBUG_MSG, "DEBUG" },
87 { EVENT_INFO_MSG, "INFO" },
88 { EVENT_NOTICE_MSG, "NOTICE" },
89 { EVENT_WARN_MSG, "WARN" },
90 { EVENT_ERR_MSG, "ERR" },
91 { EVENT_NEW_DESC, "NEWDESC" },
92 { EVENT_ADDRMAP, "ADDRMAP" },
93 { EVENT_DESCCHANGED, "DESCCHANGED" },
94 { EVENT_NS, "NS" },
95 { EVENT_STATUS_GENERAL, "STATUS_GENERAL" },
96 { EVENT_STATUS_CLIENT, "STATUS_CLIENT" },
97 { EVENT_STATUS_SERVER, "STATUS_SERVER" },
98 { EVENT_GUARD, "GUARD" },
99 { EVENT_STREAM_BANDWIDTH_USED, "STREAM_BW" },
100 { EVENT_CLIENTS_SEEN, "CLIENTS_SEEN" },
101 { EVENT_NEWCONSENSUS, "NEWCONSENSUS" },
102 { EVENT_BUILDTIMEOUT_SET, "BUILDTIMEOUT_SET" },
103 { EVENT_GOT_SIGNAL, "SIGNAL" },
104 { EVENT_CONF_CHANGED, "CONF_CHANGED"},
105 { EVENT_CONN_BW, "CONN_BW" },
106 { EVENT_CELL_STATS, "CELL_STATS" },
107 { EVENT_CIRC_BANDWIDTH_USED, "CIRC_BW" },
108 { EVENT_TRANSPORT_LAUNCHED, "TRANSPORT_LAUNCHED" },
109 { EVENT_HS_DESC, "HS_DESC" },
110 { EVENT_HS_DESC_CONTENT, "HS_DESC_CONTENT" },
111 { EVENT_NETWORK_LIVENESS, "NETWORK_LIVENESS" },
112 { 0, NULL },
115 /** Given a log severity, return the corresponding control event code. */
116 static inline int
117 log_severity_to_event(int severity)
119 switch (severity) {
120 case LOG_DEBUG: return EVENT_DEBUG_MSG;
121 case LOG_INFO: return EVENT_INFO_MSG;
122 case LOG_NOTICE: return EVENT_NOTICE_MSG;
123 case LOG_WARN: return EVENT_WARN_MSG;
124 case LOG_ERR: return EVENT_ERR_MSG;
125 default: return -1;
129 /** Helper: clear bandwidth counters of all origin circuits. */
130 static void
131 clear_circ_bw_fields(void)
133 origin_circuit_t *ocirc;
134 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
135 if (!CIRCUIT_IS_ORIGIN(circ))
136 continue;
137 ocirc = TO_ORIGIN_CIRCUIT(circ);
138 ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
139 ocirc->n_overhead_written_circ_bw = ocirc->n_overhead_read_circ_bw = 0;
140 ocirc->n_delivered_written_circ_bw = ocirc->n_delivered_read_circ_bw = 0;
142 SMARTLIST_FOREACH_END(circ);
145 /* Helper to emit the BUILDTIMEOUT_SET circuit build time event */
146 void
147 cbt_control_event_buildtimeout_set(const circuit_build_times_t *cbt,
148 buildtimeout_set_event_t type)
150 char *args = NULL;
151 double qnt;
152 double timeout_rate = 0.0;
153 double close_rate = 0.0;
155 switch (type) {
156 case BUILDTIMEOUT_SET_EVENT_RESET:
157 case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
158 case BUILDTIMEOUT_SET_EVENT_DISCARD:
159 qnt = 1.0;
160 break;
161 case BUILDTIMEOUT_SET_EVENT_COMPUTED:
162 case BUILDTIMEOUT_SET_EVENT_RESUME:
163 default:
164 qnt = circuit_build_times_quantile_cutoff();
165 break;
168 /* The timeout rate is the ratio of the timeout count over
169 * the total number of circuits attempted. The total number of
170 * circuits is (timeouts+succeeded), since every circuit
171 * either succeeds, or times out. "Closed" circuits are
172 * MEASURE_TIMEOUT circuits whose measurement period expired.
173 * All MEASURE_TIMEOUT circuits are counted in the timeouts stat
174 * before transitioning to MEASURE_TIMEOUT (in
175 * circuit_build_times_mark_circ_as_measurement_only()).
176 * MEASURE_TIMEOUT circuits that succeed are *not* counted as
177 * "succeeded". See circuit_build_times_handle_completed_hop().
179 * We cast the denominator
180 * to promote it to double before the addition, to avoid int32
181 * overflow. */
182 const double total_circuits =
183 ((double)cbt->num_circ_timeouts) + cbt->num_circ_succeeded;
184 if (total_circuits >= 1.0) {
185 timeout_rate = cbt->num_circ_timeouts / total_circuits;
186 close_rate = cbt->num_circ_closed / total_circuits;
189 tor_asprintf(&args, "TOTAL_TIMES=%lu "
190 "TIMEOUT_MS=%lu XM=%lu ALPHA=%f CUTOFF_QUANTILE=%f "
191 "TIMEOUT_RATE=%f CLOSE_MS=%lu CLOSE_RATE=%f",
192 (unsigned long)cbt->total_build_times,
193 (unsigned long)cbt->timeout_ms,
194 (unsigned long)cbt->Xm, cbt->alpha, qnt,
195 timeout_rate,
196 (unsigned long)cbt->close_ms,
197 close_rate);
199 control_event_buildtimeout_set(type, args);
201 tor_free(args);
203 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
204 * connection's event_mask field. */
205 void
206 control_update_global_event_mask(void)
208 smartlist_t *conns = get_connection_array();
209 event_mask_t old_mask, new_mask;
210 old_mask = global_event_mask;
211 int any_old_per_sec_events = control_any_per_second_event_enabled();
213 global_event_mask = 0;
214 SMARTLIST_FOREACH(conns, connection_t *, _conn,
216 if (_conn->type == CONN_TYPE_CONTROL &&
217 STATE_IS_OPEN(_conn->state)) {
218 control_connection_t *conn = TO_CONTROL_CONN(_conn);
219 global_event_mask |= conn->event_mask;
223 new_mask = global_event_mask;
225 /* Handle the aftermath. Set up the log callback to tell us only what
226 * we want to hear...*/
227 control_adjust_event_log_severity();
229 /* Macro: true if ev was false before and is true now. */
230 #define NEWLY_ENABLED(ev) \
231 (! (old_mask & (ev)) && (new_mask & (ev)))
233 /* ...then, if we've started logging stream or circ bw, clear the
234 * appropriate fields. */
235 if (NEWLY_ENABLED(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 (NEWLY_ENABLED(EVENT_CIRC_BANDWIDTH_USED)) {
245 clear_circ_bw_fields();
247 if (NEWLY_ENABLED(EVENT_BANDWIDTH_USED)) {
248 uint64_t r, w;
249 control_get_bytes_rw_last_sec(&r, &w);
251 if (any_old_per_sec_events != control_any_per_second_event_enabled()) {
252 rescan_periodic_events(get_options());
255 #undef NEWLY_ENABLED
258 /** Given a control event code for a message event, return the corresponding
259 * log severity. */
260 static inline int
261 event_to_log_severity(int event)
263 switch (event) {
264 case EVENT_DEBUG_MSG: return LOG_DEBUG;
265 case EVENT_INFO_MSG: return LOG_INFO;
266 case EVENT_NOTICE_MSG: return LOG_NOTICE;
267 case EVENT_WARN_MSG: return LOG_WARN;
268 case EVENT_ERR_MSG: return LOG_ERR;
269 default: return -1;
273 /** Adjust the log severities that result in control_event_logmsg being called
274 * to match the severity of log messages that any controllers are interested
275 * in. */
276 void
277 control_adjust_event_log_severity(void)
279 int i;
280 int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
282 for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
283 if (EVENT_IS_INTERESTING(i)) {
284 min_log_event = i;
285 break;
288 for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
289 if (EVENT_IS_INTERESTING(i)) {
290 max_log_event = i;
291 break;
294 if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
295 if (min_log_event > EVENT_NOTICE_MSG)
296 min_log_event = EVENT_NOTICE_MSG;
297 if (max_log_event < EVENT_ERR_MSG)
298 max_log_event = EVENT_ERR_MSG;
300 if (min_log_event <= max_log_event)
301 change_callback_log_severity(event_to_log_severity(min_log_event),
302 event_to_log_severity(max_log_event),
303 control_event_logmsg);
304 else
305 change_callback_log_severity(LOG_ERR, LOG_ERR,
306 control_event_logmsg);
309 /** Return true iff the event with code <b>c</b> is being sent to any current
310 * control connection. This is useful if the amount of work needed to prepare
311 * to call the appropriate control_event_...() function is high.
314 control_event_is_interesting(int event)
316 return EVENT_IS_INTERESTING(event);
319 /** Return true if any event that needs to fire once a second is enabled. */
321 control_any_per_second_event_enabled(void)
323 return ANY_EVENT_IS_INTERESTING(
324 EVENT_MASK_(EVENT_BANDWIDTH_USED) |
325 EVENT_MASK_(EVENT_CELL_STATS) |
326 EVENT_MASK_(EVENT_CIRC_BANDWIDTH_USED) |
327 EVENT_MASK_(EVENT_CONN_BW) |
328 EVENT_MASK_(EVENT_STREAM_BANDWIDTH_USED)
332 /* The value of 'get_bytes_read()' the previous time that
333 * control_get_bytes_rw_last_sec() as called. */
334 static uint64_t stats_prev_n_read = 0;
335 /* The value of 'get_bytes_written()' the previous time that
336 * control_get_bytes_rw_last_sec() as called. */
337 static uint64_t stats_prev_n_written = 0;
340 * Set <b>n_read</b> and <b>n_written</b> to the total number of bytes read
341 * and written by Tor since the last call to this function.
343 * Call this only from the main thread.
345 static void
346 control_get_bytes_rw_last_sec(uint64_t *n_read,
347 uint64_t *n_written)
349 const uint64_t stats_n_bytes_read = get_bytes_read();
350 const uint64_t stats_n_bytes_written = get_bytes_written();
352 *n_read = stats_n_bytes_read - stats_prev_n_read;
353 *n_written = stats_n_bytes_written - stats_prev_n_written;
354 stats_prev_n_read = stats_n_bytes_read;
355 stats_prev_n_written = stats_n_bytes_written;
359 * Run all the controller events (if any) that are scheduled to trigger once
360 * per second.
362 void
363 control_per_second_events(void)
365 if (!control_any_per_second_event_enabled())
366 return;
368 uint64_t bytes_read, bytes_written;
369 control_get_bytes_rw_last_sec(&bytes_read, &bytes_written);
370 control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
372 control_event_stream_bandwidth_used();
373 control_event_conn_bandwidth_used();
374 control_event_circ_bandwidth_used();
375 control_event_circuit_cell_stats();
378 /** Represents an event that's queued to be sent to one or more
379 * controllers. */
380 typedef struct queued_event_t {
381 uint16_t event;
382 char *msg;
383 } queued_event_t;
385 /** Pointer to int. If this is greater than 0, we don't allow new events to be
386 * queued. */
387 static tor_threadlocal_t block_event_queue_flag;
389 /** Holds a smartlist of queued_event_t objects that may need to be sent
390 * to one or more controllers */
391 static smartlist_t *queued_control_events = NULL;
393 /** True if the flush_queued_events_event is pending. */
394 static int flush_queued_event_pending = 0;
396 /** Lock to protect the above fields. */
397 static tor_mutex_t *queued_control_events_lock = NULL;
399 /** An event that should fire in order to flush the contents of
400 * queued_control_events. */
401 static mainloop_event_t *flush_queued_events_event = NULL;
403 void
404 control_initialize_event_queue(void)
406 if (queued_control_events == NULL) {
407 queued_control_events = smartlist_new();
410 if (flush_queued_events_event == NULL) {
411 struct event_base *b = tor_libevent_get_base();
412 if (b) {
413 flush_queued_events_event =
414 mainloop_event_new(flush_queued_events_cb, NULL);
415 tor_assert(flush_queued_events_event);
419 if (queued_control_events_lock == NULL) {
420 queued_control_events_lock = tor_mutex_new();
421 tor_threadlocal_init(&block_event_queue_flag);
425 static int *
426 get_block_event_queue(void)
428 int *val = tor_threadlocal_get(&block_event_queue_flag);
429 if (PREDICT_UNLIKELY(val == NULL)) {
430 val = tor_malloc_zero(sizeof(int));
431 tor_threadlocal_set(&block_event_queue_flag, val);
433 return val;
436 /** Helper: inserts an event on the list of events queued to be sent to
437 * one or more controllers, and schedules the events to be flushed if needed.
439 * This function takes ownership of <b>msg</b>, and may free it.
441 * We queue these events rather than send them immediately in order to break
442 * the dependency in our callgraph from code that generates events for the
443 * controller, and the network layer at large. Otherwise, nearly every
444 * interesting part of Tor would potentially call every other interesting part
445 * of Tor.
447 MOCK_IMPL(STATIC void,
448 queue_control_event_string,(uint16_t event, char *msg))
450 /* This is redundant with checks done elsewhere, but it's a last-ditch
451 * attempt to avoid queueing something we shouldn't have to queue. */
452 if (PREDICT_UNLIKELY( ! EVENT_IS_INTERESTING(event) )) {
453 tor_free(msg);
454 return;
457 int *block_event_queue = get_block_event_queue();
458 if (*block_event_queue) {
459 tor_free(msg);
460 return;
463 queued_event_t *ev = tor_malloc(sizeof(*ev));
464 ev->event = event;
465 ev->msg = msg;
467 /* No queueing an event while queueing an event */
468 ++*block_event_queue;
470 tor_mutex_acquire(queued_control_events_lock);
471 tor_assert(queued_control_events);
472 smartlist_add(queued_control_events, ev);
474 int activate_event = 0;
475 if (! flush_queued_event_pending && in_main_thread()) {
476 activate_event = 1;
477 flush_queued_event_pending = 1;
480 tor_mutex_release(queued_control_events_lock);
482 --*block_event_queue;
484 /* We just put an event on the queue; mark the queue to be
485 * flushed. We only do this from the main thread for now; otherwise,
486 * we'd need to incur locking overhead in Libevent or use a socket.
488 if (activate_event) {
489 tor_assert(flush_queued_events_event);
490 mainloop_event_activate(flush_queued_events_event);
494 #define queued_event_free(ev) \
495 FREE_AND_NULL(queued_event_t, queued_event_free_, (ev))
497 /** Release all storage held by <b>ev</b>. */
498 static void
499 queued_event_free_(queued_event_t *ev)
501 if (ev == NULL)
502 return;
504 tor_free(ev->msg);
505 tor_free(ev);
508 /** Send every queued event to every controller that's interested in it,
509 * and remove the events from the queue. If <b>force</b> is true,
510 * then make all controllers send their data out immediately, since we
511 * may be about to shut down. */
512 static void
513 queued_events_flush_all(int force)
515 /* Make sure that we get all the pending log events, if there are any. */
516 flush_pending_log_callbacks();
518 if (PREDICT_UNLIKELY(queued_control_events == NULL)) {
519 return;
521 smartlist_t *all_conns = get_connection_array();
522 smartlist_t *controllers = smartlist_new();
523 smartlist_t *queued_events;
525 int *block_event_queue = get_block_event_queue();
526 ++*block_event_queue;
528 tor_mutex_acquire(queued_control_events_lock);
529 /* No queueing an event while flushing events. */
530 flush_queued_event_pending = 0;
531 queued_events = queued_control_events;
532 queued_control_events = smartlist_new();
533 tor_mutex_release(queued_control_events_lock);
535 /* Gather all the controllers that will care... */
536 SMARTLIST_FOREACH_BEGIN(all_conns, connection_t *, conn) {
537 if (conn->type == CONN_TYPE_CONTROL &&
538 !conn->marked_for_close &&
539 conn->state == CONTROL_CONN_STATE_OPEN) {
540 control_connection_t *control_conn = TO_CONTROL_CONN(conn);
542 smartlist_add(controllers, control_conn);
544 } SMARTLIST_FOREACH_END(conn);
546 SMARTLIST_FOREACH_BEGIN(queued_events, queued_event_t *, ev) {
547 const event_mask_t bit = ((event_mask_t)1) << ev->event;
548 const size_t msg_len = strlen(ev->msg);
549 SMARTLIST_FOREACH_BEGIN(controllers, control_connection_t *,
550 control_conn) {
551 if (control_conn->event_mask & bit) {
552 connection_buf_add(ev->msg, msg_len, TO_CONN(control_conn));
554 } SMARTLIST_FOREACH_END(control_conn);
556 queued_event_free(ev);
557 } SMARTLIST_FOREACH_END(ev);
559 if (force) {
560 SMARTLIST_FOREACH_BEGIN(controllers, control_connection_t *,
561 control_conn) {
562 connection_flush(TO_CONN(control_conn));
563 } SMARTLIST_FOREACH_END(control_conn);
566 smartlist_free(queued_events);
567 smartlist_free(controllers);
569 --*block_event_queue;
572 /** Libevent callback: Flushes pending events to controllers that are
573 * interested in them. */
574 static void
575 flush_queued_events_cb(mainloop_event_t *event, void *arg)
577 (void) event;
578 (void) arg;
579 queued_events_flush_all(0);
582 /** Send an event to all v1 controllers that are listening for code
583 * <b>event</b>. The event's body is given by <b>msg</b>.
585 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
586 * respect to the EXTENDED_EVENTS feature. */
587 MOCK_IMPL(STATIC void,
588 send_control_event_string,(uint16_t event,
589 const char *msg))
591 tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
592 queue_control_event_string(event, tor_strdup(msg));
595 /** Helper for send_control_event and control_event_status:
596 * Send an event to all v1 controllers that are listening for code
597 * <b>event</b>. The event's body is created by the printf-style format in
598 * <b>format</b>, and other arguments as provided. */
599 static void
600 send_control_event_impl(uint16_t event,
601 const char *format, va_list ap)
603 char *buf = NULL;
604 int len;
606 len = tor_vasprintf(&buf, format, ap);
607 if (len < 0) {
608 log_warn(LD_BUG, "Unable to format event for controller.");
609 return;
612 queue_control_event_string(event, buf);
615 /** Send an event to all v1 controllers that are listening for code
616 * <b>event</b>. The event's body is created by the printf-style format in
617 * <b>format</b>, and other arguments as provided. */
618 static void
619 send_control_event(uint16_t event,
620 const char *format, ...)
622 va_list ap;
623 va_start(ap, format);
624 send_control_event_impl(event, format, ap);
625 va_end(ap);
628 /** Something major has happened to circuit <b>circ</b>: tell any
629 * interested control connections. */
631 control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
632 int reason_code)
634 const char *status;
635 char reasons[64] = "";
637 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
638 return 0;
639 tor_assert(circ);
641 switch (tp)
643 case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
644 case CIRC_EVENT_BUILT: status = "BUILT"; break;
645 case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
646 case CIRC_EVENT_FAILED: status = "FAILED"; break;
647 case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
648 default:
649 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
650 tor_fragile_assert();
651 return 0;
654 if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
655 const char *reason_str = circuit_end_reason_to_control_string(reason_code);
656 char unk_reason_buf[16];
657 if (!reason_str) {
658 tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
659 reason_str = unk_reason_buf;
661 if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
662 tor_snprintf(reasons, sizeof(reasons),
663 " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
664 } else {
665 tor_snprintf(reasons, sizeof(reasons),
666 " REASON=%s", reason_str);
671 char *circdesc = circuit_describe_status_for_controller(circ);
672 const char *sp = strlen(circdesc) ? " " : "";
673 send_control_event(EVENT_CIRCUIT_STATUS,
674 "650 CIRC %lu %s%s%s%s\r\n",
675 (unsigned long)circ->global_identifier,
676 status, sp,
677 circdesc,
678 reasons);
679 tor_free(circdesc);
682 return 0;
685 /** Something minor has happened to circuit <b>circ</b>: tell any
686 * interested control connections. */
687 static int
688 control_event_circuit_status_minor(origin_circuit_t *circ,
689 circuit_status_minor_event_t e,
690 int purpose, const struct timeval *tv)
692 const char *event_desc;
693 char event_tail[160] = "";
694 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
695 return 0;
696 tor_assert(circ);
698 switch (e)
700 case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
701 event_desc = "PURPOSE_CHANGED";
704 /* event_tail can currently be up to 68 chars long */
705 const char *hs_state_str =
706 circuit_purpose_to_controller_hs_state_string(purpose);
707 tor_snprintf(event_tail, sizeof(event_tail),
708 " OLD_PURPOSE=%s%s%s",
709 circuit_purpose_to_controller_string(purpose),
710 (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
711 (hs_state_str != NULL) ? hs_state_str : "");
714 break;
715 case CIRC_MINOR_EVENT_CANNIBALIZED:
716 event_desc = "CANNIBALIZED";
719 /* event_tail can currently be up to 130 chars long */
720 const char *hs_state_str =
721 circuit_purpose_to_controller_hs_state_string(purpose);
722 const struct timeval *old_timestamp_began = tv;
723 char tbuf[ISO_TIME_USEC_LEN+1];
724 format_iso_time_nospace_usec(tbuf, old_timestamp_began);
726 tor_snprintf(event_tail, sizeof(event_tail),
727 " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
728 circuit_purpose_to_controller_string(purpose),
729 (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
730 (hs_state_str != NULL) ? hs_state_str : "",
731 tbuf);
734 break;
735 default:
736 log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
737 tor_fragile_assert();
738 return 0;
742 char *circdesc = circuit_describe_status_for_controller(circ);
743 const char *sp = strlen(circdesc) ? " " : "";
744 send_control_event(EVENT_CIRCUIT_STATUS_MINOR,
745 "650 CIRC_MINOR %lu %s%s%s%s\r\n",
746 (unsigned long)circ->global_identifier,
747 event_desc, sp,
748 circdesc,
749 event_tail);
750 tor_free(circdesc);
753 return 0;
757 * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
758 * interested controllers.
761 control_event_circuit_purpose_changed(origin_circuit_t *circ,
762 int old_purpose)
764 return control_event_circuit_status_minor(circ,
765 CIRC_MINOR_EVENT_PURPOSE_CHANGED,
766 old_purpose,
767 NULL);
771 * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
772 * created-time from <b>old_tv_created</b>: tell any interested controllers.
775 control_event_circuit_cannibalized(origin_circuit_t *circ,
776 int old_purpose,
777 const struct timeval *old_tv_created)
779 return control_event_circuit_status_minor(circ,
780 CIRC_MINOR_EVENT_CANNIBALIZED,
781 old_purpose,
782 old_tv_created);
785 /** Something has happened to the stream associated with AP connection
786 * <b>conn</b>: tell any interested control connections. */
788 control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
789 int reason_code)
791 char reason_buf[64];
792 char addrport_buf[64];
793 const char *status;
794 circuit_t *circ;
795 origin_circuit_t *origin_circ = NULL;
796 char buf[256];
797 const char *purpose = "";
798 tor_assert(conn->socks_request);
800 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
801 return 0;
803 if (tp == STREAM_EVENT_CLOSED &&
804 (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
805 return 0;
807 write_stream_target_to_buf(conn, buf, sizeof(buf));
809 reason_buf[0] = '\0';
810 switch (tp)
812 case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
813 case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
814 case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
815 case STREAM_EVENT_FAILED: status = "FAILED"; break;
816 case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
817 case STREAM_EVENT_NEW: status = "NEW"; break;
818 case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
819 case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
820 case STREAM_EVENT_REMAP: status = "REMAP"; break;
821 case STREAM_EVENT_CONTROLLER_WAIT: status = "CONTROLLER_WAIT"; break;
822 default:
823 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
824 return 0;
826 if (reason_code && (tp == STREAM_EVENT_FAILED ||
827 tp == STREAM_EVENT_CLOSED ||
828 tp == STREAM_EVENT_FAILED_RETRIABLE)) {
829 const char *reason_str = stream_end_reason_to_control_string(reason_code);
830 char *r = NULL;
831 if (!reason_str) {
832 tor_asprintf(&r, " UNKNOWN_%d", reason_code);
833 reason_str = r;
835 if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
836 tor_snprintf(reason_buf, sizeof(reason_buf),
837 " REASON=END REMOTE_REASON=%s", reason_str);
838 else
839 tor_snprintf(reason_buf, sizeof(reason_buf),
840 " REASON=%s", reason_str);
841 tor_free(r);
842 } else if (reason_code && tp == STREAM_EVENT_REMAP) {
843 switch (reason_code) {
844 case REMAP_STREAM_SOURCE_CACHE:
845 strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
846 break;
847 case REMAP_STREAM_SOURCE_EXIT:
848 strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
849 break;
850 default:
851 tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
852 reason_code);
853 /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
854 break;
858 if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
860 * When the control conn is an AF_UNIX socket and we have no address,
861 * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
862 * dnsserv.c.
864 if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
865 tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
866 ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
867 } else {
869 * else leave it blank so control on AF_UNIX doesn't need to make
870 * something up.
872 addrport_buf[0] = '\0';
874 } else {
875 addrport_buf[0] = '\0';
878 if (tp == STREAM_EVENT_NEW_RESOLVE) {
879 purpose = " PURPOSE=DNS_REQUEST";
880 } else if (tp == STREAM_EVENT_NEW) {
881 if (conn->use_begindir) {
882 connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
883 int linked_dir_purpose = -1;
884 if (linked && linked->type == CONN_TYPE_DIR)
885 linked_dir_purpose = linked->purpose;
886 if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
887 purpose = " PURPOSE=DIR_UPLOAD";
888 else
889 purpose = " PURPOSE=DIR_FETCH";
890 } else
891 purpose = " PURPOSE=USER";
894 circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
895 if (circ && CIRCUIT_IS_ORIGIN(circ))
896 origin_circ = TO_ORIGIN_CIRCUIT(circ);
899 char *conndesc = entry_connection_describe_status_for_controller(conn);
900 const char *sp = strlen(conndesc) ? " " : "";
901 send_control_event(EVENT_STREAM_STATUS,
902 "650 STREAM %"PRIu64" %s %lu %s%s%s%s%s%s\r\n",
903 (ENTRY_TO_CONN(conn)->global_identifier),
904 status,
905 origin_circ?
906 (unsigned long)origin_circ->global_identifier : 0ul,
907 buf, reason_buf, addrport_buf, purpose, sp, conndesc);
908 tor_free(conndesc);
911 /* XXX need to specify its intended exit, etc? */
913 return 0;
916 /** Called when the status of an OR connection <b>conn</b> changes: tell any
917 * interested control connections. <b>tp</b> is the new status for the
918 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
919 * may be the reason why.
922 control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
923 int reason)
925 int ncircs = 0;
926 const char *status;
927 char name[128];
928 char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
930 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
931 return 0;
933 switch (tp)
935 case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
936 case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
937 case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
938 case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
939 case OR_CONN_EVENT_NEW: status = "NEW"; break;
940 default:
941 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
942 return 0;
944 if (conn->chan) {
945 ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
946 } else {
947 ncircs = 0;
949 ncircs += connection_or_get_num_circuits(conn);
950 if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
951 tor_snprintf(ncircs_buf, sizeof(ncircs_buf), " NCIRCS=%d", ncircs);
954 orconn_target_get_name(name, sizeof(name), conn);
955 send_control_event(EVENT_OR_CONN_STATUS,
956 "650 ORCONN %s %s%s%s%s ID=%"PRIu64"\r\n",
957 name, status,
958 reason ? " REASON=" : "",
959 orconn_end_reason_to_control_string(reason),
960 ncircs_buf,
961 (conn->base_.global_identifier));
963 return 0;
967 * Print out STREAM_BW event for a single conn
970 control_event_stream_bandwidth(edge_connection_t *edge_conn)
972 struct timeval now;
973 char tbuf[ISO_TIME_USEC_LEN+1];
974 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
975 if (!edge_conn->n_read && !edge_conn->n_written)
976 return 0;
978 tor_gettimeofday(&now);
979 format_iso_time_nospace_usec(tbuf, &now);
980 send_control_event(EVENT_STREAM_BANDWIDTH_USED,
981 "650 STREAM_BW %"PRIu64" %lu %lu %s\r\n",
982 (edge_conn->base_.global_identifier),
983 (unsigned long)edge_conn->n_read,
984 (unsigned long)edge_conn->n_written,
985 tbuf);
987 edge_conn->n_written = edge_conn->n_read = 0;
990 return 0;
993 /** A second or more has elapsed: tell any interested control
994 * connections how much bandwidth streams have used. */
996 control_event_stream_bandwidth_used(void)
998 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
999 smartlist_t *conns = get_connection_array();
1000 edge_connection_t *edge_conn;
1001 struct timeval now;
1002 char tbuf[ISO_TIME_USEC_LEN+1];
1004 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
1006 if (conn->type != CONN_TYPE_AP)
1007 continue;
1008 edge_conn = TO_EDGE_CONN(conn);
1009 if (!edge_conn->n_read && !edge_conn->n_written)
1010 continue;
1012 tor_gettimeofday(&now);
1013 format_iso_time_nospace_usec(tbuf, &now);
1014 send_control_event(EVENT_STREAM_BANDWIDTH_USED,
1015 "650 STREAM_BW %"PRIu64" %lu %lu %s\r\n",
1016 (edge_conn->base_.global_identifier),
1017 (unsigned long)edge_conn->n_read,
1018 (unsigned long)edge_conn->n_written,
1019 tbuf);
1021 edge_conn->n_written = edge_conn->n_read = 0;
1023 SMARTLIST_FOREACH_END(conn);
1026 return 0;
1029 /** A second or more has elapsed: tell any interested control connections
1030 * how much bandwidth origin circuits have used. */
1032 control_event_circ_bandwidth_used(void)
1034 if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
1035 return 0;
1037 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1038 if (!CIRCUIT_IS_ORIGIN(circ))
1039 continue;
1041 control_event_circ_bandwidth_used_for_circ(TO_ORIGIN_CIRCUIT(circ));
1043 SMARTLIST_FOREACH_END(circ);
1045 return 0;
1049 * Emit a CIRC_BW event line for a specific circuit.
1051 * This function sets the values it emits to 0, and does not emit
1052 * an event if there is no new data to report since the last call.
1054 * Therefore, it may be called at any frequency.
1057 control_event_circ_bandwidth_used_for_circ(origin_circuit_t *ocirc)
1059 struct timeval now;
1060 char tbuf[ISO_TIME_USEC_LEN+1];
1062 tor_assert(ocirc);
1064 if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
1065 return 0;
1067 /* n_read_circ_bw and n_written_circ_bw are always updated
1068 * when there is any new cell on a circuit, and set to 0 after
1069 * the event, below.
1071 * Therefore, checking them is sufficient to determine if there
1072 * is new data to report. */
1073 if (!ocirc->n_read_circ_bw && !ocirc->n_written_circ_bw)
1074 return 0;
1076 tor_gettimeofday(&now);
1077 format_iso_time_nospace_usec(tbuf, &now);
1078 send_control_event(EVENT_CIRC_BANDWIDTH_USED,
1079 "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu TIME=%s "
1080 "DELIVERED_READ=%lu OVERHEAD_READ=%lu "
1081 "DELIVERED_WRITTEN=%lu OVERHEAD_WRITTEN=%lu\r\n",
1082 ocirc->global_identifier,
1083 (unsigned long)ocirc->n_read_circ_bw,
1084 (unsigned long)ocirc->n_written_circ_bw,
1085 tbuf,
1086 (unsigned long)ocirc->n_delivered_read_circ_bw,
1087 (unsigned long)ocirc->n_overhead_read_circ_bw,
1088 (unsigned long)ocirc->n_delivered_written_circ_bw,
1089 (unsigned long)ocirc->n_overhead_written_circ_bw);
1090 ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
1091 ocirc->n_overhead_written_circ_bw = ocirc->n_overhead_read_circ_bw = 0;
1092 ocirc->n_delivered_written_circ_bw = ocirc->n_delivered_read_circ_bw = 0;
1094 return 0;
1097 /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
1098 * bandwidth counters. */
1100 control_event_conn_bandwidth(connection_t *conn)
1102 const char *conn_type_str;
1103 if (!get_options()->TestingEnableConnBwEvent ||
1104 !EVENT_IS_INTERESTING(EVENT_CONN_BW))
1105 return 0;
1106 if (!conn->n_read_conn_bw && !conn->n_written_conn_bw)
1107 return 0;
1108 switch (conn->type) {
1109 case CONN_TYPE_OR:
1110 conn_type_str = "OR";
1111 break;
1112 case CONN_TYPE_DIR:
1113 conn_type_str = "DIR";
1114 break;
1115 case CONN_TYPE_EXIT:
1116 conn_type_str = "EXIT";
1117 break;
1118 default:
1119 return 0;
1121 send_control_event(EVENT_CONN_BW,
1122 "650 CONN_BW ID=%"PRIu64" TYPE=%s "
1123 "READ=%lu WRITTEN=%lu\r\n",
1124 (conn->global_identifier),
1125 conn_type_str,
1126 (unsigned long)conn->n_read_conn_bw,
1127 (unsigned long)conn->n_written_conn_bw);
1128 conn->n_written_conn_bw = conn->n_read_conn_bw = 0;
1129 return 0;
1132 /** A second or more has elapsed: tell any interested control
1133 * connections how much bandwidth connections have used. */
1135 control_event_conn_bandwidth_used(void)
1137 if (get_options()->TestingEnableConnBwEvent &&
1138 EVENT_IS_INTERESTING(EVENT_CONN_BW)) {
1139 SMARTLIST_FOREACH(get_connection_array(), connection_t *, conn,
1140 control_event_conn_bandwidth(conn));
1142 return 0;
1145 /** Helper: iterate over cell statistics of <b>circ</b> and sum up added
1146 * cells, removed cells, and waiting times by cell command and direction.
1147 * Store results in <b>cell_stats</b>. Free cell statistics of the
1148 * circuit afterwards. */
1149 void
1150 sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
1152 memset(cell_stats, 0, sizeof(cell_stats_t));
1153 SMARTLIST_FOREACH_BEGIN(circ->testing_cell_stats,
1154 const testing_cell_stats_entry_t *, ent) {
1155 tor_assert(ent->command <= CELL_COMMAND_MAX_);
1156 if (!ent->removed && !ent->exitward) {
1157 cell_stats->added_cells_appward[ent->command] += 1;
1158 } else if (!ent->removed && ent->exitward) {
1159 cell_stats->added_cells_exitward[ent->command] += 1;
1160 } else if (!ent->exitward) {
1161 cell_stats->removed_cells_appward[ent->command] += 1;
1162 cell_stats->total_time_appward[ent->command] += ent->waiting_time * 10;
1163 } else {
1164 cell_stats->removed_cells_exitward[ent->command] += 1;
1165 cell_stats->total_time_exitward[ent->command] += ent->waiting_time * 10;
1167 } SMARTLIST_FOREACH_END(ent);
1168 circuit_clear_testing_cell_stats(circ);
1171 /** Helper: append a cell statistics string to <code>event_parts</code>,
1172 * prefixed with <code>key</code>=. Statistics consist of comma-separated
1173 * key:value pairs with lower-case command strings as keys and cell
1174 * numbers or total waiting times as values. A key:value pair is included
1175 * if the entry in <code>include_if_non_zero</code> is not zero, but with
1176 * the (possibly zero) entry from <code>number_to_include</code>. Both
1177 * arrays are expected to have a length of CELL_COMMAND_MAX_ + 1. If no
1178 * entry in <code>include_if_non_zero</code> is positive, no string will
1179 * be added to <code>event_parts</code>. */
1180 void
1181 append_cell_stats_by_command(smartlist_t *event_parts, const char *key,
1182 const uint64_t *include_if_non_zero,
1183 const uint64_t *number_to_include)
1185 smartlist_t *key_value_strings = smartlist_new();
1186 int i;
1187 for (i = 0; i <= CELL_COMMAND_MAX_; i++) {
1188 if (include_if_non_zero[i] > 0) {
1189 smartlist_add_asprintf(key_value_strings, "%s:%"PRIu64,
1190 cell_command_to_string(i),
1191 (number_to_include[i]));
1194 if (smartlist_len(key_value_strings) > 0) {
1195 char *joined = smartlist_join_strings(key_value_strings, ",", 0, NULL);
1196 smartlist_add_asprintf(event_parts, "%s=%s", key, joined);
1197 SMARTLIST_FOREACH(key_value_strings, char *, cp, tor_free(cp));
1198 tor_free(joined);
1200 smartlist_free(key_value_strings);
1203 /** Helper: format <b>cell_stats</b> for <b>circ</b> for inclusion in a
1204 * CELL_STATS event and write result string to <b>event_string</b>. */
1205 void
1206 format_cell_stats(char **event_string, circuit_t *circ,
1207 cell_stats_t *cell_stats)
1209 smartlist_t *event_parts = smartlist_new();
1210 if (CIRCUIT_IS_ORIGIN(circ)) {
1211 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1212 smartlist_add_asprintf(event_parts, "ID=%lu",
1213 (unsigned long)ocirc->global_identifier);
1214 } else if (TO_OR_CIRCUIT(circ)->p_chan) {
1215 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1216 smartlist_add_asprintf(event_parts, "InboundQueue=%lu",
1217 (unsigned long)or_circ->p_circ_id);
1218 smartlist_add_asprintf(event_parts, "InboundConn=%"PRIu64,
1219 (or_circ->p_chan->global_identifier));
1220 append_cell_stats_by_command(event_parts, "InboundAdded",
1221 cell_stats->added_cells_appward,
1222 cell_stats->added_cells_appward);
1223 append_cell_stats_by_command(event_parts, "InboundRemoved",
1224 cell_stats->removed_cells_appward,
1225 cell_stats->removed_cells_appward);
1226 append_cell_stats_by_command(event_parts, "InboundTime",
1227 cell_stats->removed_cells_appward,
1228 cell_stats->total_time_appward);
1230 if (circ->n_chan) {
1231 smartlist_add_asprintf(event_parts, "OutboundQueue=%lu",
1232 (unsigned long)circ->n_circ_id);
1233 smartlist_add_asprintf(event_parts, "OutboundConn=%"PRIu64,
1234 (circ->n_chan->global_identifier));
1235 append_cell_stats_by_command(event_parts, "OutboundAdded",
1236 cell_stats->added_cells_exitward,
1237 cell_stats->added_cells_exitward);
1238 append_cell_stats_by_command(event_parts, "OutboundRemoved",
1239 cell_stats->removed_cells_exitward,
1240 cell_stats->removed_cells_exitward);
1241 append_cell_stats_by_command(event_parts, "OutboundTime",
1242 cell_stats->removed_cells_exitward,
1243 cell_stats->total_time_exitward);
1245 *event_string = smartlist_join_strings(event_parts, " ", 0, NULL);
1246 SMARTLIST_FOREACH(event_parts, char *, cp, tor_free(cp));
1247 smartlist_free(event_parts);
1250 /** A second or more has elapsed: tell any interested control connection
1251 * how many cells have been processed for a given circuit. */
1253 control_event_circuit_cell_stats(void)
1255 cell_stats_t *cell_stats;
1256 char *event_string;
1257 if (!get_options()->TestingEnableCellStatsEvent ||
1258 !EVENT_IS_INTERESTING(EVENT_CELL_STATS))
1259 return 0;
1260 cell_stats = tor_malloc(sizeof(cell_stats_t));
1261 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1262 if (!circ->testing_cell_stats)
1263 continue;
1264 sum_up_cell_stats_by_command(circ, cell_stats);
1265 format_cell_stats(&event_string, circ, cell_stats);
1266 send_control_event(EVENT_CELL_STATS,
1267 "650 CELL_STATS %s\r\n", event_string);
1268 tor_free(event_string);
1270 SMARTLIST_FOREACH_END(circ);
1271 tor_free(cell_stats);
1272 return 0;
1275 /* about 5 minutes worth. */
1276 #define N_BW_EVENTS_TO_CACHE 300
1277 /* Index into cached_bw_events to next write. */
1278 static int next_measurement_idx = 0;
1279 /* number of entries set in n_measurements */
1280 static int n_measurements = 0;
1281 static struct cached_bw_event_t {
1282 uint32_t n_read;
1283 uint32_t n_written;
1284 } cached_bw_events[N_BW_EVENTS_TO_CACHE];
1286 /** A second or more has elapsed: tell any interested control
1287 * connections how much bandwidth we used. */
1289 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
1291 cached_bw_events[next_measurement_idx].n_read = n_read;
1292 cached_bw_events[next_measurement_idx].n_written = n_written;
1293 if (++next_measurement_idx == N_BW_EVENTS_TO_CACHE)
1294 next_measurement_idx = 0;
1295 if (n_measurements < N_BW_EVENTS_TO_CACHE)
1296 ++n_measurements;
1298 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
1299 send_control_event(EVENT_BANDWIDTH_USED,
1300 "650 BW %lu %lu\r\n",
1301 (unsigned long)n_read,
1302 (unsigned long)n_written);
1305 return 0;
1308 char *
1309 get_bw_samples(void)
1311 int i;
1312 int idx = (next_measurement_idx + N_BW_EVENTS_TO_CACHE - n_measurements)
1313 % N_BW_EVENTS_TO_CACHE;
1314 tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
1316 smartlist_t *elements = smartlist_new();
1318 for (i = 0; i < n_measurements; ++i) {
1319 tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
1320 const struct cached_bw_event_t *bwe = &cached_bw_events[idx];
1322 smartlist_add_asprintf(elements, "%u,%u",
1323 (unsigned)bwe->n_read,
1324 (unsigned)bwe->n_written);
1326 idx = (idx + 1) % N_BW_EVENTS_TO_CACHE;
1329 char *result = smartlist_join_strings(elements, " ", 0, NULL);
1331 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
1332 smartlist_free(elements);
1334 return result;
1337 /** Called when we are sending a log message to the controllers: suspend
1338 * sending further log messages to the controllers until we're done. Used by
1339 * CONN_LOG_PROTECT. */
1340 void
1341 disable_control_logging(void)
1343 ++disable_log_messages;
1346 /** We're done sending a log message to the controllers: re-enable controller
1347 * logging. Used by CONN_LOG_PROTECT. */
1348 void
1349 enable_control_logging(void)
1351 if (--disable_log_messages < 0)
1352 tor_assert(0);
1355 /** Remove newline and carriage-return characters from @a msg, replacing them
1356 * with spaces, and discarding any that appear at the end of the message */
1357 void
1358 control_logmsg_strip_newlines(char *msg)
1360 char *cp;
1361 for (cp = msg; *cp; ++cp) {
1362 if (*cp == '\r' || *cp == '\n') {
1363 *cp = ' ';
1366 if (cp == msg)
1367 return;
1368 /* Remove trailing spaces */
1369 for (--cp; *cp == ' '; --cp) {
1370 *cp = '\0';
1371 if (cp == msg)
1372 break;
1376 /** We got a log message: tell any interested control connections. */
1377 void
1378 control_event_logmsg(int severity, log_domain_mask_t domain, const char *msg)
1380 int event;
1382 /* Don't even think of trying to add stuff to a buffer from a cpuworker
1383 * thread. (See #25987 for plan to fix.) */
1384 if (! in_main_thread())
1385 return;
1387 if (disable_log_messages)
1388 return;
1390 if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
1391 severity <= LOG_NOTICE) {
1392 char *esc = esc_for_log(msg);
1393 ++disable_log_messages;
1394 control_event_general_status(severity, "BUG REASON=%s", esc);
1395 --disable_log_messages;
1396 tor_free(esc);
1399 event = log_severity_to_event(severity);
1400 if (event >= 0 && EVENT_IS_INTERESTING(event)) {
1401 char *b = NULL;
1402 const char *s;
1403 if (strchr(msg, '\n')) {
1404 b = tor_strdup(msg);
1405 control_logmsg_strip_newlines(b);
1407 switch (severity) {
1408 case LOG_DEBUG: s = "DEBUG"; break;
1409 case LOG_INFO: s = "INFO"; break;
1410 case LOG_NOTICE: s = "NOTICE"; break;
1411 case LOG_WARN: s = "WARN"; break;
1412 case LOG_ERR: s = "ERR"; break;
1413 default: s = "UnknownLogSeverity"; break;
1415 ++disable_log_messages;
1416 send_control_event(event, "650 %s %s\r\n", s, b?b:msg);
1417 if (severity == LOG_ERR) {
1418 /* Force a flush, since we may be about to die horribly */
1419 queued_events_flush_all(1);
1421 --disable_log_messages;
1422 tor_free(b);
1427 * Logging callback: called when there is a queued pending log callback.
1429 void
1430 control_event_logmsg_pending(void)
1432 if (! in_main_thread()) {
1433 /* We can't handle this case yet, since we're using a
1434 * mainloop_event_t to invoke queued_events_flush_all. We ought to
1435 * use a different mechanism instead: see #25987.
1437 return;
1439 tor_assert(flush_queued_events_event);
1440 mainloop_event_activate(flush_queued_events_event);
1443 /** Called whenever we receive new router descriptors: tell any
1444 * interested control connections. <b>routers</b> is a list of
1445 * routerinfo_t's.
1448 control_event_descriptors_changed(smartlist_t *routers)
1450 char *msg;
1452 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
1453 return 0;
1456 smartlist_t *names = smartlist_new();
1457 char *ids;
1458 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
1459 char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
1460 router_get_verbose_nickname(b, ri);
1461 smartlist_add(names, b);
1463 ids = smartlist_join_strings(names, " ", 0, NULL);
1464 tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
1465 send_control_event_string(EVENT_NEW_DESC, msg);
1466 tor_free(ids);
1467 tor_free(msg);
1468 SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
1469 smartlist_free(names);
1471 return 0;
1474 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
1475 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
1476 * <b>error</b> is non-NULL, it is an error code describing the failure
1477 * mode of the mapping.
1480 control_event_address_mapped(const char *from, const char *to,
1481 time_t expires, const char *error,
1482 const int cached, uint64_t stream_id)
1484 char *stream_id_str = NULL;
1485 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
1486 return 0;
1488 if (stream_id) {
1489 tor_asprintf(&stream_id_str, " STREAMID=%"PRIu64"", stream_id);
1492 if (expires < 3 || expires == TIME_MAX)
1493 send_control_event(EVENT_ADDRMAP,
1494 "650 ADDRMAP %s %s NEVER %s%s"
1495 "CACHED=\"%s\"%s\r\n",
1496 from, to, error ? error : "", error ? " " : "",
1497 cached ? "YES" : "NO",
1498 stream_id ? stream_id_str : "");
1499 else {
1500 char buf[ISO_TIME_LEN+1];
1501 char buf2[ISO_TIME_LEN+1];
1502 format_local_iso_time(buf,expires);
1503 format_iso_time(buf2,expires);
1504 send_control_event(EVENT_ADDRMAP,
1505 "650 ADDRMAP %s %s \"%s\" %s%sEXPIRES=\"%s\" "
1506 "CACHED=\"%s\"%s\r\n",
1507 from, to, buf, error ? error : "",
1508 error ? " " : "", buf2, cached ? "YES" : "NO",
1509 stream_id ? stream_id_str: "");
1512 tor_free(stream_id_str);
1514 return 0;
1516 /** The network liveness has changed; this is called from circuitstats.c
1517 * whenever we receive a cell, or when timeout expires and we assume the
1518 * network is down. */
1520 control_event_network_liveness_update(int liveness)
1522 if (liveness > 0) {
1523 if (get_cached_network_liveness() <= 0) {
1524 /* Update cached liveness */
1525 set_cached_network_liveness(1);
1526 log_debug(LD_CONTROL, "Sending NETWORK_LIVENESS UP");
1527 send_control_event_string(EVENT_NETWORK_LIVENESS,
1528 "650 NETWORK_LIVENESS UP\r\n");
1530 /* else was already live, no-op */
1531 } else {
1532 if (get_cached_network_liveness() > 0) {
1533 /* Update cached liveness */
1534 set_cached_network_liveness(0);
1535 log_debug(LD_CONTROL, "Sending NETWORK_LIVENESS DOWN");
1536 send_control_event_string(EVENT_NETWORK_LIVENESS,
1537 "650 NETWORK_LIVENESS DOWN\r\n");
1539 /* else was already dead, no-op */
1542 return 0;
1545 /** Helper function for NS-style events. Constructs and sends an event
1546 * of type <b>event</b> with string <b>event_string</b> out of the set of
1547 * networkstatuses <b>statuses</b>. Currently it is used for NS events
1548 * and NEWCONSENSUS events. */
1549 static int
1550 control_event_networkstatus_changed_helper(smartlist_t *statuses,
1551 uint16_t event,
1552 const char *event_string)
1554 smartlist_t *strs;
1555 char *s, *esc = NULL;
1556 if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
1557 return 0;
1559 strs = smartlist_new();
1560 smartlist_add_strdup(strs, "650+");
1561 smartlist_add_strdup(strs, event_string);
1562 smartlist_add_strdup(strs, "\r\n");
1563 SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
1565 s = networkstatus_getinfo_helper_single(rs);
1566 if (!s) continue;
1567 smartlist_add(strs, s);
1570 s = smartlist_join_strings(strs, "", 0, NULL);
1571 write_escaped_data(s, strlen(s), &esc);
1572 SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
1573 smartlist_free(strs);
1574 tor_free(s);
1575 send_control_event_string(event, esc);
1576 send_control_event_string(event,
1577 "650 OK\r\n");
1579 tor_free(esc);
1580 return 0;
1583 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
1584 * an NS event to any controller that cares. */
1586 control_event_networkstatus_changed(smartlist_t *statuses)
1588 return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
1591 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
1592 * event consisting of an NS-style line for each relay in the consensus. */
1594 control_event_newconsensus(const networkstatus_t *consensus)
1596 if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
1597 return 0;
1598 return control_event_networkstatus_changed_helper(
1599 consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
1602 /** Called when we compute a new circuitbuildtimeout */
1604 control_event_buildtimeout_set(buildtimeout_set_event_t type,
1605 const char *args)
1607 const char *type_string = NULL;
1609 if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
1610 return 0;
1612 switch (type) {
1613 case BUILDTIMEOUT_SET_EVENT_COMPUTED:
1614 type_string = "COMPUTED";
1615 break;
1616 case BUILDTIMEOUT_SET_EVENT_RESET:
1617 type_string = "RESET";
1618 break;
1619 case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
1620 type_string = "SUSPENDED";
1621 break;
1622 case BUILDTIMEOUT_SET_EVENT_DISCARD:
1623 type_string = "DISCARD";
1624 break;
1625 case BUILDTIMEOUT_SET_EVENT_RESUME:
1626 type_string = "RESUME";
1627 break;
1628 default:
1629 type_string = "UNKNOWN";
1630 break;
1633 send_control_event(EVENT_BUILDTIMEOUT_SET,
1634 "650 BUILDTIMEOUT_SET %s %s\r\n",
1635 type_string, args);
1637 return 0;
1640 /** Called when a signal has been processed from signal_callback */
1642 control_event_signal(uintptr_t signal_num)
1644 const char *signal_string = NULL;
1646 if (!control_event_is_interesting(EVENT_GOT_SIGNAL))
1647 return 0;
1649 for (unsigned i = 0; signal_table[i].signal_name != NULL; ++i) {
1650 if ((int)signal_num == signal_table[i].sig) {
1651 signal_string = signal_table[i].signal_name;
1652 break;
1656 if (signal_string == NULL) {
1657 log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
1658 (unsigned long)signal_num);
1659 return -1;
1662 send_control_event(EVENT_GOT_SIGNAL, "650 SIGNAL %s\r\n",
1663 signal_string);
1664 return 0;
1667 /** Called when a single local_routerstatus_t has changed: Sends an NS event
1668 * to any controller that cares. */
1670 control_event_networkstatus_changed_single(const routerstatus_t *rs)
1672 smartlist_t *statuses;
1673 int r;
1675 if (!EVENT_IS_INTERESTING(EVENT_NS))
1676 return 0;
1678 statuses = smartlist_new();
1679 smartlist_add(statuses, (void*)rs);
1680 r = control_event_networkstatus_changed(statuses);
1681 smartlist_free(statuses);
1682 return r;
1685 /** Our own router descriptor has changed; tell any controllers that care.
1688 control_event_my_descriptor_changed(void)
1690 send_control_event(EVENT_DESCCHANGED, "650 DESCCHANGED\r\n");
1691 return 0;
1694 /** Helper: sends a status event where <b>type</b> is one of
1695 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
1696 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
1697 * string corresponding to <b>args</b>. */
1698 static int
1699 control_event_status(int type, int severity, const char *format, va_list args)
1701 char *user_buf = NULL;
1702 char format_buf[160];
1703 const char *status, *sev;
1705 switch (type) {
1706 case EVENT_STATUS_GENERAL:
1707 status = "STATUS_GENERAL";
1708 break;
1709 case EVENT_STATUS_CLIENT:
1710 status = "STATUS_CLIENT";
1711 break;
1712 case EVENT_STATUS_SERVER:
1713 status = "STATUS_SERVER";
1714 break;
1715 default:
1716 log_warn(LD_BUG, "Unrecognized status type %d", type);
1717 return -1;
1719 switch (severity) {
1720 case LOG_NOTICE:
1721 sev = "NOTICE";
1722 break;
1723 case LOG_WARN:
1724 sev = "WARN";
1725 break;
1726 case LOG_ERR:
1727 sev = "ERR";
1728 break;
1729 default:
1730 log_warn(LD_BUG, "Unrecognized status severity %d", severity);
1731 return -1;
1733 if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
1734 status, sev)<0) {
1735 log_warn(LD_BUG, "Format string too long.");
1736 return -1;
1738 if (tor_vasprintf(&user_buf, format, args)<0) {
1739 log_warn(LD_BUG, "Failed to create user buffer.");
1740 return -1;
1743 send_control_event(type, "%s %s\r\n", format_buf, user_buf);
1744 tor_free(user_buf);
1745 return 0;
1748 #ifndef COCCI
1749 #define CONTROL_EVENT_STATUS_BODY(event, sev) \
1750 int r; \
1751 do { \
1752 va_list ap; \
1753 if (!EVENT_IS_INTERESTING(event)) \
1754 return 0; \
1756 va_start(ap, format); \
1757 r = control_event_status((event), (sev), format, ap); \
1758 va_end(ap); \
1759 } while (0)
1760 #endif /* !defined(COCCI) */
1762 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
1763 * by formatting the arguments using the printf-style <b>format</b>. */
1765 control_event_general_status(int severity, const char *format, ...)
1767 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, severity);
1768 return r;
1771 /** Format and send an EVENT_STATUS_GENERAL LOG_ERR event, and flush it to the
1772 * controller(s) immediately. */
1774 control_event_general_error(const char *format, ...)
1776 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, LOG_ERR);
1777 /* Force a flush, since we may be about to die horribly */
1778 queued_events_flush_all(1);
1779 return r;
1782 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
1783 * by formatting the arguments using the printf-style <b>format</b>. */
1785 control_event_client_status(int severity, const char *format, ...)
1787 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, severity);
1788 return r;
1791 /** Format and send an EVENT_STATUS_CLIENT LOG_ERR event, and flush it to the
1792 * controller(s) immediately. */
1794 control_event_client_error(const char *format, ...)
1796 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, LOG_ERR);
1797 /* Force a flush, since we may be about to die horribly */
1798 queued_events_flush_all(1);
1799 return r;
1802 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
1803 * by formatting the arguments using the printf-style <b>format</b>. */
1805 control_event_server_status(int severity, const char *format, ...)
1807 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, severity);
1808 return r;
1811 /** Format and send an EVENT_STATUS_SERVER LOG_ERR event, and flush it to the
1812 * controller(s) immediately. */
1814 control_event_server_error(const char *format, ...)
1816 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, LOG_ERR);
1817 /* Force a flush, since we may be about to die horribly */
1818 queued_events_flush_all(1);
1819 return r;
1822 /** Called when the status of an entry guard with the given <b>nickname</b>
1823 * and identity <b>digest</b> has changed to <b>status</b>: tells any
1824 * controllers that care. */
1826 control_event_guard(const char *nickname, const char *digest,
1827 const char *status)
1829 char hbuf[HEX_DIGEST_LEN+1];
1830 base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
1831 if (!EVENT_IS_INTERESTING(EVENT_GUARD))
1832 return 0;
1835 char buf[MAX_VERBOSE_NICKNAME_LEN+1];
1836 const node_t *node = node_get_by_id(digest);
1837 if (node) {
1838 node_get_verbose_nickname(node, buf);
1839 } else {
1840 tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
1842 send_control_event(EVENT_GUARD,
1843 "650 GUARD ENTRY %s %s\r\n", buf, status);
1845 return 0;
1848 /** Called when a configuration option changes. This is generally triggered
1849 * by SETCONF requests and RELOAD/SIGHUP signals. The <b>changes</b> are
1850 * a linked list of configuration key-values.
1851 * <b>changes</b> can be NULL, meaning "no changes".
1853 void
1854 control_event_conf_changed(const config_line_t *changes)
1856 char *result;
1857 smartlist_t *lines;
1858 if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) || !changes) {
1859 return;
1861 lines = smartlist_new();
1862 for (const config_line_t *line = changes; line; line = line->next) {
1863 if (line->value == NULL) {
1864 smartlist_add_asprintf(lines, "650-%s", line->key);
1865 } else {
1866 smartlist_add_asprintf(lines, "650-%s=%s", line->key, line->value);
1869 result = smartlist_join_strings(lines, "\r\n", 0, NULL);
1870 send_control_event(EVENT_CONF_CHANGED,
1871 "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
1872 tor_free(result);
1873 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1874 smartlist_free(lines);
1877 /** We just generated a new summary of which countries we've seen clients
1878 * from recently. Send a copy to the controller in case it wants to
1879 * display it for the user. */
1880 void
1881 control_event_clients_seen(const char *controller_str)
1883 send_control_event(EVENT_CLIENTS_SEEN,
1884 "650 CLIENTS_SEEN %s\r\n", controller_str);
1887 /** A new pluggable transport called <b>transport_name</b> was
1888 * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
1889 * "server" or "client" depending on the mode of the pluggable
1890 * transport.
1891 * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
1893 void
1894 control_event_transport_launched(const char *mode, const char *transport_name,
1895 tor_addr_t *addr, uint16_t port)
1897 send_control_event(EVENT_TRANSPORT_LAUNCHED,
1898 "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
1899 mode, transport_name, fmt_addr(addr), port);
1902 /** A pluggable transport called <b>pt_name</b> has emitted a log message
1903 * found in <b>message</b> at <b>severity</b> log level. */
1904 void
1905 control_event_pt_log(const char *log)
1907 send_control_event(EVENT_PT_LOG,
1908 "650 PT_LOG %s\r\n",
1909 log);
1912 /** A pluggable transport has emitted a STATUS message found in
1913 * <b>status</b>. */
1914 void
1915 control_event_pt_status(const char *status)
1917 send_control_event(EVENT_PT_STATUS,
1918 "650 PT_STATUS %s\r\n",
1919 status);
1922 /** Convert rendezvous auth type to string for HS_DESC control events
1924 const char *
1925 rend_auth_type_to_string(rend_auth_type_t auth_type)
1927 const char *str;
1929 switch (auth_type) {
1930 case REND_NO_AUTH:
1931 str = "NO_AUTH";
1932 break;
1933 case REND_V3_AUTH:
1934 str = "REND_V3_AUTH";
1935 break;
1936 default:
1937 str = "UNKNOWN";
1940 return str;
1943 /** Return either the onion address if the given pointer is a non empty
1944 * string else the unknown string. */
1945 static const char *
1946 rend_hsaddress_str_or_unknown(const char *onion_address)
1948 static const char *str_unknown = "UNKNOWN";
1949 const char *str_ret = str_unknown;
1951 /* No valid pointer, unknown it is. */
1952 if (!onion_address) {
1953 goto end;
1955 /* Empty onion address thus we don't know, unknown it is. */
1956 if (onion_address[0] == '\0') {
1957 goto end;
1959 /* All checks are good so return the given onion address. */
1960 str_ret = onion_address;
1962 end:
1963 return str_ret;
1966 /** send HS_DESC requested event.
1968 * <b>rend_query</b> is used to fetch requested onion address and auth type.
1969 * <b>hs_dir</b> is the description of contacting hs directory.
1970 * <b>desc_id_base32</b> is the ID of requested hs descriptor.
1971 * <b>hsdir_index</b> is the HSDir fetch index value for v3, an hex string.
1973 void
1974 control_event_hs_descriptor_requested(const char *onion_address,
1975 rend_auth_type_t auth_type,
1976 const char *id_digest,
1977 const char *desc_id,
1978 const char *hsdir_index)
1980 char *hsdir_index_field = NULL;
1982 if (BUG(!id_digest || !desc_id)) {
1983 return;
1986 if (hsdir_index) {
1987 tor_asprintf(&hsdir_index_field, " HSDIR_INDEX=%s", hsdir_index);
1990 send_control_event(EVENT_HS_DESC,
1991 "650 HS_DESC REQUESTED %s %s %s %s%s\r\n",
1992 rend_hsaddress_str_or_unknown(onion_address),
1993 rend_auth_type_to_string(auth_type),
1994 node_describe_longname_by_id(id_digest),
1995 desc_id,
1996 hsdir_index_field ? hsdir_index_field : "");
1997 tor_free(hsdir_index_field);
2000 /** send HS_DESC CREATED event when a local service generates a descriptor.
2002 * <b>onion_address</b> is service address.
2003 * <b>desc_id</b> is the descriptor ID.
2004 * <b>replica</b> is the the descriptor replica number. If it is negative, it
2005 * is ignored.
2007 void
2008 control_event_hs_descriptor_created(const char *onion_address,
2009 const char *desc_id,
2010 int replica)
2012 char *replica_field = NULL;
2014 if (BUG(!onion_address || !desc_id)) {
2015 return;
2018 if (replica >= 0) {
2019 tor_asprintf(&replica_field, " REPLICA=%d", replica);
2022 send_control_event(EVENT_HS_DESC,
2023 "650 HS_DESC CREATED %s UNKNOWN UNKNOWN %s%s\r\n",
2024 onion_address, desc_id,
2025 replica_field ? replica_field : "");
2026 tor_free(replica_field);
2029 /** send HS_DESC upload event.
2031 * <b>onion_address</b> is service address.
2032 * <b>hs_dir</b> is the description of contacting hs directory.
2033 * <b>desc_id</b> is the ID of requested hs descriptor.
2035 void
2036 control_event_hs_descriptor_upload(const char *onion_address,
2037 const char *id_digest,
2038 const char *desc_id,
2039 const char *hsdir_index)
2041 char *hsdir_index_field = NULL;
2043 if (BUG(!onion_address || !id_digest || !desc_id)) {
2044 return;
2047 if (hsdir_index) {
2048 tor_asprintf(&hsdir_index_field, " HSDIR_INDEX=%s", hsdir_index);
2051 send_control_event(EVENT_HS_DESC,
2052 "650 HS_DESC UPLOAD %s UNKNOWN %s %s%s\r\n",
2053 onion_address,
2054 node_describe_longname_by_id(id_digest),
2055 desc_id,
2056 hsdir_index_field ? hsdir_index_field : "");
2057 tor_free(hsdir_index_field);
2060 /** send HS_DESC event after got response from hs directory.
2062 * NOTE: this is an internal function used by following functions:
2063 * control_event_hsv3_descriptor_failed
2065 * So do not call this function directly.
2067 static void
2068 event_hs_descriptor_receive_end(const char *action,
2069 const char *onion_address,
2070 const char *desc_id,
2071 rend_auth_type_t auth_type,
2072 const char *hsdir_id_digest,
2073 const char *reason)
2075 char *reason_field = NULL;
2077 if (BUG(!action || !onion_address)) {
2078 return;
2081 if (reason) {
2082 tor_asprintf(&reason_field, " REASON=%s", reason);
2085 send_control_event(EVENT_HS_DESC,
2086 "650 HS_DESC %s %s %s %s%s%s\r\n",
2087 action,
2088 rend_hsaddress_str_or_unknown(onion_address),
2089 rend_auth_type_to_string(auth_type),
2090 hsdir_id_digest ?
2091 node_describe_longname_by_id(hsdir_id_digest) :
2092 "UNKNOWN",
2093 desc_id ? desc_id : "",
2094 reason_field ? reason_field : "");
2096 tor_free(reason_field);
2099 /** send HS_DESC event after got response from hs directory.
2101 * NOTE: this is an internal function used by following functions:
2102 * control_event_hs_descriptor_uploaded
2103 * control_event_hs_descriptor_upload_failed
2105 * So do not call this function directly.
2107 void
2108 control_event_hs_descriptor_upload_end(const char *action,
2109 const char *onion_address,
2110 const char *id_digest,
2111 const char *reason)
2113 char *reason_field = NULL;
2115 if (BUG(!action || !id_digest)) {
2116 return;
2119 if (reason) {
2120 tor_asprintf(&reason_field, " REASON=%s", reason);
2123 send_control_event(EVENT_HS_DESC,
2124 "650 HS_DESC %s %s UNKNOWN %s%s\r\n",
2125 action,
2126 rend_hsaddress_str_or_unknown(onion_address),
2127 node_describe_longname_by_id(id_digest),
2128 reason_field ? reason_field : "");
2130 tor_free(reason_field);
2133 /* Send HS_DESC RECEIVED event
2135 * Called when we successfully received a hidden service descriptor. */
2136 void
2137 control_event_hsv3_descriptor_received(const char *onion_address,
2138 const char *desc_id,
2139 const char *hsdir_id_digest)
2141 char *desc_id_field = NULL;
2143 if (BUG(!onion_address || !desc_id || !hsdir_id_digest)) {
2144 return;
2147 /* Because DescriptorID is an optional positional value, we need to add a
2148 * whitespace before in order to not be next to the HsDir value. */
2149 tor_asprintf(&desc_id_field, " %s", desc_id);
2151 event_hs_descriptor_receive_end("RECEIVED", onion_address, desc_id_field,
2152 REND_NO_AUTH, hsdir_id_digest, NULL);
2153 tor_free(desc_id_field);
2156 /** send HS_DESC UPLOADED event
2158 * called when we successfully uploaded a hidden service descriptor.
2160 void
2161 control_event_hs_descriptor_uploaded(const char *id_digest,
2162 const char *onion_address)
2164 if (BUG(!id_digest)) {
2165 return;
2168 control_event_hs_descriptor_upload_end("UPLOADED", onion_address,
2169 id_digest, NULL);
2172 /** Send HS_DESC event to inform controller that the query to
2173 * <b>onion_address</b> failed to retrieve hidden service descriptor
2174 * <b>desc_id</b> from directory identified by <b>hsdir_id_digest</b>. If
2175 * NULL, "UNKNOWN" is used. If <b>reason</b> is not NULL, add it to REASON=
2176 * field. */
2177 void
2178 control_event_hsv3_descriptor_failed(const char *onion_address,
2179 const char *desc_id,
2180 const char *hsdir_id_digest,
2181 const char *reason)
2183 char *desc_id_field = NULL;
2185 if (BUG(!onion_address || !desc_id || !reason)) {
2186 return;
2189 /* Because DescriptorID is an optional positional value, we need to add a
2190 * whitespace before in order to not be next to the HsDir value. */
2191 tor_asprintf(&desc_id_field, " %s", desc_id);
2193 event_hs_descriptor_receive_end("FAILED", onion_address, desc_id_field,
2194 REND_NO_AUTH, hsdir_id_digest, reason);
2195 tor_free(desc_id_field);
2198 /** Send HS_DESC_CONTENT event after completion of a successful fetch
2199 * from hs directory. If <b>hsdir_id_digest</b> is NULL, it is replaced
2200 * by "UNKNOWN". If <b>content</b> is NULL, it is replaced by an empty
2201 * string. The <b>onion_address</b> or <b>desc_id</b> set to NULL will
2202 * not trigger the control event. */
2203 void
2204 control_event_hs_descriptor_content(const char *onion_address,
2205 const char *desc_id,
2206 const char *hsdir_id_digest,
2207 const char *content)
2209 static const char *event_name = "HS_DESC_CONTENT";
2210 char *esc_content = NULL;
2212 if (!onion_address || !desc_id) {
2213 log_warn(LD_BUG, "Called with onion_address==%p, desc_id==%p, ",
2214 onion_address, desc_id);
2215 return;
2218 if (content == NULL) {
2219 /* Point it to empty content so it can still be escaped. */
2220 content = "";
2222 write_escaped_data(content, strlen(content), &esc_content);
2224 send_control_event(EVENT_HS_DESC_CONTENT,
2225 "650+%s %s %s %s\r\n%s650 OK\r\n",
2226 event_name,
2227 rend_hsaddress_str_or_unknown(onion_address),
2228 desc_id,
2229 hsdir_id_digest ?
2230 node_describe_longname_by_id(hsdir_id_digest) :
2231 "UNKNOWN",
2232 esc_content);
2233 tor_free(esc_content);
2236 /** Send HS_DESC event to inform controller upload of hidden service
2237 * descriptor identified by <b>id_digest</b> failed. If <b>reason</b>
2238 * is not NULL, add it to REASON= field.
2240 void
2241 control_event_hs_descriptor_upload_failed(const char *id_digest,
2242 const char *onion_address,
2243 const char *reason)
2245 if (BUG(!id_digest)) {
2246 return;
2248 control_event_hs_descriptor_upload_end("FAILED", onion_address,
2249 id_digest, reason);
2252 void
2253 control_events_free_all(void)
2255 smartlist_t *queued_events = NULL;
2257 stats_prev_n_read = stats_prev_n_written = 0;
2259 if (queued_control_events_lock) {
2260 tor_mutex_acquire(queued_control_events_lock);
2261 flush_queued_event_pending = 0;
2262 queued_events = queued_control_events;
2263 queued_control_events = NULL;
2264 tor_mutex_release(queued_control_events_lock);
2266 if (queued_events) {
2267 SMARTLIST_FOREACH(queued_events, queued_event_t *, ev,
2268 queued_event_free(ev));
2269 smartlist_free(queued_events);
2271 if (flush_queued_events_event) {
2272 mainloop_event_free(flush_queued_events_event);
2273 flush_queued_events_event = NULL;
2275 global_event_mask = 0;
2276 disable_log_messages = 0;
2279 #ifdef TOR_UNIT_TESTS
2280 /* For testing: change the value of global_event_mask */
2281 void
2282 control_testing_set_global_event_mask(uint64_t mask)
2284 global_event_mask = mask;
2286 #endif /* defined(TOR_UNIT_TESTS) */