Control port STREAM XON/XOFF status event notification
[tor.git] / src / feature / control / control_events.c
blob4c8cf9a425dc4f57a7d420e4f440e2f82d826db7
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/congestion_control_common.h"
25 #include "core/or/reasons.h"
26 #include "feature/control/control.h"
27 #include "feature/control/control_events.h"
28 #include "feature/control/control_fmt.h"
29 #include "feature/control/control_proto.h"
30 #include "feature/dircommon/directory.h"
31 #include "feature/nodelist/describe.h"
32 #include "feature/nodelist/networkstatus.h"
33 #include "feature/nodelist/nodelist.h"
35 #include "feature/control/control_connection_st.h"
36 #include "core/or/entry_connection_st.h"
37 #include "feature/nodelist/networkstatus_st.h"
38 #include "core/or/or_connection_st.h"
39 #include "core/or/or_circuit_st.h"
40 #include "core/or/origin_circuit_st.h"
42 #include "lib/evloop/compat_libevent.h"
43 #include "lib/encoding/confline.h"
45 static void flush_queued_events_cb(mainloop_event_t *event, void *arg);
46 static void control_get_bytes_rw_last_sec(uint64_t *r, uint64_t *w);
48 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
49 * finished authentication and is accepting commands. */
50 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
52 /** An event mask of all the events that any controller is interested in
53 * receiving. */
54 static event_mask_t global_event_mask = 0;
56 /** True iff we have disabled log messages from being sent to the controller */
57 static int disable_log_messages = 0;
59 /** Macro: true if any control connection is interested in events of type
60 * <b>e</b>. */
61 #define EVENT_IS_INTERESTING(e) \
62 (!! (global_event_mask & EVENT_MASK_(e)))
64 /** Macro: true if any event from the bitfield 'e' is interesting. */
65 #define ANY_EVENT_IS_INTERESTING(e) \
66 (!! (global_event_mask & (e)))
68 static void send_control_event_impl(uint16_t event,
69 const char *format, va_list ap)
70 CHECK_PRINTF(2,0);
71 static int control_event_status(int type, int severity, const char *format,
72 va_list args)
73 CHECK_PRINTF(3,0);
75 static void send_control_event(uint16_t event,
76 const char *format, ...)
77 CHECK_PRINTF(2,3);
79 /** Table mapping event values to their names. Used to implement SETEVENTS
80 * and GETINFO events/names, and to keep they in sync. */
81 const struct control_event_t control_event_table[] = {
82 { EVENT_CIRCUIT_STATUS, "CIRC" },
83 { EVENT_CIRCUIT_STATUS_MINOR, "CIRC_MINOR" },
84 { EVENT_STREAM_STATUS, "STREAM" },
85 { EVENT_OR_CONN_STATUS, "ORCONN" },
86 { EVENT_BANDWIDTH_USED, "BW" },
87 { EVENT_DEBUG_MSG, "DEBUG" },
88 { EVENT_INFO_MSG, "INFO" },
89 { EVENT_NOTICE_MSG, "NOTICE" },
90 { EVENT_WARN_MSG, "WARN" },
91 { EVENT_ERR_MSG, "ERR" },
92 { EVENT_NEW_DESC, "NEWDESC" },
93 { EVENT_ADDRMAP, "ADDRMAP" },
94 { EVENT_DESCCHANGED, "DESCCHANGED" },
95 { EVENT_NS, "NS" },
96 { EVENT_STATUS_GENERAL, "STATUS_GENERAL" },
97 { EVENT_STATUS_CLIENT, "STATUS_CLIENT" },
98 { EVENT_STATUS_SERVER, "STATUS_SERVER" },
99 { EVENT_GUARD, "GUARD" },
100 { EVENT_STREAM_BANDWIDTH_USED, "STREAM_BW" },
101 { EVENT_CLIENTS_SEEN, "CLIENTS_SEEN" },
102 { EVENT_NEWCONSENSUS, "NEWCONSENSUS" },
103 { EVENT_BUILDTIMEOUT_SET, "BUILDTIMEOUT_SET" },
104 { EVENT_GOT_SIGNAL, "SIGNAL" },
105 { EVENT_CONF_CHANGED, "CONF_CHANGED"},
106 { EVENT_CONN_BW, "CONN_BW" },
107 { EVENT_CELL_STATS, "CELL_STATS" },
108 { EVENT_CIRC_BANDWIDTH_USED, "CIRC_BW" },
109 { EVENT_TRANSPORT_LAUNCHED, "TRANSPORT_LAUNCHED" },
110 { EVENT_HS_DESC, "HS_DESC" },
111 { EVENT_HS_DESC_CONTENT, "HS_DESC_CONTENT" },
112 { EVENT_NETWORK_LIVENESS, "NETWORK_LIVENESS" },
113 { 0, NULL },
116 /** Given a log severity, return the corresponding control event code. */
117 static inline int
118 log_severity_to_event(int severity)
120 switch (severity) {
121 case LOG_DEBUG: return EVENT_DEBUG_MSG;
122 case LOG_INFO: return EVENT_INFO_MSG;
123 case LOG_NOTICE: return EVENT_NOTICE_MSG;
124 case LOG_WARN: return EVENT_WARN_MSG;
125 case LOG_ERR: return EVENT_ERR_MSG;
126 default: return -1;
130 /** Helper: clear bandwidth counters of all origin circuits. */
131 static void
132 clear_circ_bw_fields(void)
134 origin_circuit_t *ocirc;
135 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
136 if (!CIRCUIT_IS_ORIGIN(circ))
137 continue;
138 ocirc = TO_ORIGIN_CIRCUIT(circ);
139 ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
140 ocirc->n_overhead_written_circ_bw = ocirc->n_overhead_read_circ_bw = 0;
141 ocirc->n_delivered_written_circ_bw = ocirc->n_delivered_read_circ_bw = 0;
143 SMARTLIST_FOREACH_END(circ);
146 /* Helper to emit the BUILDTIMEOUT_SET circuit build time event */
147 void
148 cbt_control_event_buildtimeout_set(const circuit_build_times_t *cbt,
149 buildtimeout_set_event_t type)
151 char *args = NULL;
152 double qnt;
153 double timeout_rate = 0.0;
154 double close_rate = 0.0;
156 switch (type) {
157 case BUILDTIMEOUT_SET_EVENT_RESET:
158 case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
159 case BUILDTIMEOUT_SET_EVENT_DISCARD:
160 qnt = 1.0;
161 break;
162 case BUILDTIMEOUT_SET_EVENT_COMPUTED:
163 case BUILDTIMEOUT_SET_EVENT_RESUME:
164 default:
165 qnt = circuit_build_times_quantile_cutoff();
166 break;
169 /* The timeout rate is the ratio of the timeout count over
170 * the total number of circuits attempted. The total number of
171 * circuits is (timeouts+succeeded), since every circuit
172 * either succeeds, or times out. "Closed" circuits are
173 * MEASURE_TIMEOUT circuits whose measurement period expired.
174 * All MEASURE_TIMEOUT circuits are counted in the timeouts stat
175 * before transitioning to MEASURE_TIMEOUT (in
176 * circuit_build_times_mark_circ_as_measurement_only()).
177 * MEASURE_TIMEOUT circuits that succeed are *not* counted as
178 * "succeeded". See circuit_build_times_handle_completed_hop().
180 * We cast the denominator
181 * to promote it to double before the addition, to avoid int32
182 * overflow. */
183 const double total_circuits =
184 ((double)cbt->num_circ_timeouts) + cbt->num_circ_succeeded;
185 if (total_circuits >= 1.0) {
186 timeout_rate = cbt->num_circ_timeouts / total_circuits;
187 close_rate = cbt->num_circ_closed / total_circuits;
190 tor_asprintf(&args, "TOTAL_TIMES=%lu "
191 "TIMEOUT_MS=%lu XM=%lu ALPHA=%f CUTOFF_QUANTILE=%f "
192 "TIMEOUT_RATE=%f CLOSE_MS=%lu CLOSE_RATE=%f",
193 (unsigned long)cbt->total_build_times,
194 (unsigned long)cbt->timeout_ms,
195 (unsigned long)cbt->Xm, cbt->alpha, qnt,
196 timeout_rate,
197 (unsigned long)cbt->close_ms,
198 close_rate);
200 control_event_buildtimeout_set(type, args);
202 tor_free(args);
204 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
205 * connection's event_mask field. */
206 void
207 control_update_global_event_mask(void)
209 smartlist_t *conns = get_connection_array();
210 event_mask_t old_mask, new_mask;
211 old_mask = global_event_mask;
212 int any_old_per_sec_events = control_any_per_second_event_enabled();
214 global_event_mask = 0;
215 SMARTLIST_FOREACH(conns, connection_t *, _conn,
217 if (_conn->type == CONN_TYPE_CONTROL &&
218 STATE_IS_OPEN(_conn->state)) {
219 control_connection_t *conn = TO_CONTROL_CONN(_conn);
220 global_event_mask |= conn->event_mask;
224 new_mask = global_event_mask;
226 /* Handle the aftermath. Set up the log callback to tell us only what
227 * we want to hear...*/
228 control_adjust_event_log_severity();
230 /* Macro: true if ev was false before and is true now. */
231 #define NEWLY_ENABLED(ev) \
232 (! (old_mask & (ev)) && (new_mask & (ev)))
234 /* ...then, if we've started logging stream or circ bw, clear the
235 * appropriate fields. */
236 if (NEWLY_ENABLED(EVENT_STREAM_BANDWIDTH_USED)) {
237 SMARTLIST_FOREACH(conns, connection_t *, conn,
239 if (conn->type == CONN_TYPE_AP) {
240 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
241 edge_conn->n_written = edge_conn->n_read = 0;
245 if (NEWLY_ENABLED(EVENT_CIRC_BANDWIDTH_USED)) {
246 clear_circ_bw_fields();
248 if (NEWLY_ENABLED(EVENT_BANDWIDTH_USED)) {
249 uint64_t r, w;
250 control_get_bytes_rw_last_sec(&r, &w);
252 if (any_old_per_sec_events != control_any_per_second_event_enabled()) {
253 rescan_periodic_events(get_options());
256 #undef NEWLY_ENABLED
259 /** Given a control event code for a message event, return the corresponding
260 * log severity. */
261 static inline int
262 event_to_log_severity(int event)
264 switch (event) {
265 case EVENT_DEBUG_MSG: return LOG_DEBUG;
266 case EVENT_INFO_MSG: return LOG_INFO;
267 case EVENT_NOTICE_MSG: return LOG_NOTICE;
268 case EVENT_WARN_MSG: return LOG_WARN;
269 case EVENT_ERR_MSG: return LOG_ERR;
270 default: return -1;
274 /** Adjust the log severities that result in control_event_logmsg being called
275 * to match the severity of log messages that any controllers are interested
276 * in. */
277 void
278 control_adjust_event_log_severity(void)
280 int i;
281 int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
283 for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
284 if (EVENT_IS_INTERESTING(i)) {
285 min_log_event = i;
286 break;
289 for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
290 if (EVENT_IS_INTERESTING(i)) {
291 max_log_event = i;
292 break;
295 if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
296 if (min_log_event > EVENT_NOTICE_MSG)
297 min_log_event = EVENT_NOTICE_MSG;
298 if (max_log_event < EVENT_ERR_MSG)
299 max_log_event = EVENT_ERR_MSG;
301 if (min_log_event <= max_log_event)
302 change_callback_log_severity(event_to_log_severity(min_log_event),
303 event_to_log_severity(max_log_event),
304 control_event_logmsg);
305 else
306 change_callback_log_severity(LOG_ERR, LOG_ERR,
307 control_event_logmsg);
310 /** Return true iff the event with code <b>c</b> is being sent to any current
311 * control connection. This is useful if the amount of work needed to prepare
312 * to call the appropriate control_event_...() function is high.
315 control_event_is_interesting(int event)
317 return EVENT_IS_INTERESTING(event);
320 /** Return true if any event that needs to fire once a second is enabled. */
322 control_any_per_second_event_enabled(void)
324 return ANY_EVENT_IS_INTERESTING(
325 EVENT_MASK_(EVENT_BANDWIDTH_USED) |
326 EVENT_MASK_(EVENT_CELL_STATS) |
327 EVENT_MASK_(EVENT_CIRC_BANDWIDTH_USED) |
328 EVENT_MASK_(EVENT_CONN_BW) |
329 EVENT_MASK_(EVENT_STREAM_BANDWIDTH_USED)
333 /* The value of 'get_bytes_read()' the previous time that
334 * control_get_bytes_rw_last_sec() as called. */
335 static uint64_t stats_prev_n_read = 0;
336 /* The value of 'get_bytes_written()' the previous time that
337 * control_get_bytes_rw_last_sec() as called. */
338 static uint64_t stats_prev_n_written = 0;
341 * Set <b>n_read</b> and <b>n_written</b> to the total number of bytes read
342 * and written by Tor since the last call to this function.
344 * Call this only from the main thread.
346 static void
347 control_get_bytes_rw_last_sec(uint64_t *n_read,
348 uint64_t *n_written)
350 const uint64_t stats_n_bytes_read = get_bytes_read();
351 const uint64_t stats_n_bytes_written = get_bytes_written();
353 *n_read = stats_n_bytes_read - stats_prev_n_read;
354 *n_written = stats_n_bytes_written - stats_prev_n_written;
355 stats_prev_n_read = stats_n_bytes_read;
356 stats_prev_n_written = stats_n_bytes_written;
360 * Run all the controller events (if any) that are scheduled to trigger once
361 * per second.
363 void
364 control_per_second_events(void)
366 if (!control_any_per_second_event_enabled())
367 return;
369 uint64_t bytes_read, bytes_written;
370 control_get_bytes_rw_last_sec(&bytes_read, &bytes_written);
371 control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
373 control_event_stream_bandwidth_used();
374 control_event_conn_bandwidth_used();
375 control_event_circ_bandwidth_used();
376 control_event_circuit_cell_stats();
379 /** Represents an event that's queued to be sent to one or more
380 * controllers. */
381 typedef struct queued_event_t {
382 uint16_t event;
383 char *msg;
384 } queued_event_t;
386 /** Pointer to int. If this is greater than 0, we don't allow new events to be
387 * queued. */
388 static tor_threadlocal_t block_event_queue_flag;
390 /** Holds a smartlist of queued_event_t objects that may need to be sent
391 * to one or more controllers */
392 static smartlist_t *queued_control_events = NULL;
394 /** True if the flush_queued_events_event is pending. */
395 static int flush_queued_event_pending = 0;
397 /** Lock to protect the above fields. */
398 static tor_mutex_t *queued_control_events_lock = NULL;
400 /** An event that should fire in order to flush the contents of
401 * queued_control_events. */
402 static mainloop_event_t *flush_queued_events_event = NULL;
404 void
405 control_initialize_event_queue(void)
407 if (queued_control_events == NULL) {
408 queued_control_events = smartlist_new();
411 if (flush_queued_events_event == NULL) {
412 struct event_base *b = tor_libevent_get_base();
413 if (b) {
414 flush_queued_events_event =
415 mainloop_event_new(flush_queued_events_cb, NULL);
416 tor_assert(flush_queued_events_event);
420 if (queued_control_events_lock == NULL) {
421 queued_control_events_lock = tor_mutex_new();
422 tor_threadlocal_init(&block_event_queue_flag);
426 static int *
427 get_block_event_queue(void)
429 int *val = tor_threadlocal_get(&block_event_queue_flag);
430 if (PREDICT_UNLIKELY(val == NULL)) {
431 val = tor_malloc_zero(sizeof(int));
432 tor_threadlocal_set(&block_event_queue_flag, val);
434 return val;
437 /** Helper: inserts an event on the list of events queued to be sent to
438 * one or more controllers, and schedules the events to be flushed if needed.
440 * This function takes ownership of <b>msg</b>, and may free it.
442 * We queue these events rather than send them immediately in order to break
443 * the dependency in our callgraph from code that generates events for the
444 * controller, and the network layer at large. Otherwise, nearly every
445 * interesting part of Tor would potentially call every other interesting part
446 * of Tor.
448 MOCK_IMPL(STATIC void,
449 queue_control_event_string,(uint16_t event, char *msg))
451 /* This is redundant with checks done elsewhere, but it's a last-ditch
452 * attempt to avoid queueing something we shouldn't have to queue. */
453 if (PREDICT_UNLIKELY( ! EVENT_IS_INTERESTING(event) )) {
454 tor_free(msg);
455 return;
458 int *block_event_queue = get_block_event_queue();
459 if (*block_event_queue) {
460 tor_free(msg);
461 return;
464 queued_event_t *ev = tor_malloc(sizeof(*ev));
465 ev->event = event;
466 ev->msg = msg;
468 /* No queueing an event while queueing an event */
469 ++*block_event_queue;
471 tor_mutex_acquire(queued_control_events_lock);
472 tor_assert(queued_control_events);
473 smartlist_add(queued_control_events, ev);
475 int activate_event = 0;
476 if (! flush_queued_event_pending && in_main_thread()) {
477 activate_event = 1;
478 flush_queued_event_pending = 1;
481 tor_mutex_release(queued_control_events_lock);
483 --*block_event_queue;
485 /* We just put an event on the queue; mark the queue to be
486 * flushed. We only do this from the main thread for now; otherwise,
487 * we'd need to incur locking overhead in Libevent or use a socket.
489 if (activate_event) {
490 tor_assert(flush_queued_events_event);
491 mainloop_event_activate(flush_queued_events_event);
495 #define queued_event_free(ev) \
496 FREE_AND_NULL(queued_event_t, queued_event_free_, (ev))
498 /** Release all storage held by <b>ev</b>. */
499 static void
500 queued_event_free_(queued_event_t *ev)
502 if (ev == NULL)
503 return;
505 tor_free(ev->msg);
506 tor_free(ev);
509 /** Send every queued event to every controller that's interested in it,
510 * and remove the events from the queue. If <b>force</b> is true,
511 * then make all controllers send their data out immediately, since we
512 * may be about to shut down. */
513 static void
514 queued_events_flush_all(int force)
516 /* Make sure that we get all the pending log events, if there are any. */
517 flush_pending_log_callbacks();
519 if (PREDICT_UNLIKELY(queued_control_events == NULL)) {
520 return;
522 smartlist_t *all_conns = get_connection_array();
523 smartlist_t *controllers = smartlist_new();
524 smartlist_t *queued_events;
526 int *block_event_queue = get_block_event_queue();
527 ++*block_event_queue;
529 tor_mutex_acquire(queued_control_events_lock);
530 /* No queueing an event while flushing events. */
531 flush_queued_event_pending = 0;
532 queued_events = queued_control_events;
533 queued_control_events = smartlist_new();
534 tor_mutex_release(queued_control_events_lock);
536 /* Gather all the controllers that will care... */
537 SMARTLIST_FOREACH_BEGIN(all_conns, connection_t *, conn) {
538 if (conn->type == CONN_TYPE_CONTROL &&
539 !conn->marked_for_close &&
540 conn->state == CONTROL_CONN_STATE_OPEN) {
541 control_connection_t *control_conn = TO_CONTROL_CONN(conn);
543 smartlist_add(controllers, control_conn);
545 } SMARTLIST_FOREACH_END(conn);
547 SMARTLIST_FOREACH_BEGIN(queued_events, queued_event_t *, ev) {
548 const event_mask_t bit = ((event_mask_t)1) << ev->event;
549 const size_t msg_len = strlen(ev->msg);
550 SMARTLIST_FOREACH_BEGIN(controllers, control_connection_t *,
551 control_conn) {
552 if (control_conn->event_mask & bit) {
553 connection_buf_add(ev->msg, msg_len, TO_CONN(control_conn));
555 } SMARTLIST_FOREACH_END(control_conn);
557 queued_event_free(ev);
558 } SMARTLIST_FOREACH_END(ev);
560 if (force) {
561 SMARTLIST_FOREACH_BEGIN(controllers, control_connection_t *,
562 control_conn) {
563 connection_flush(TO_CONN(control_conn));
564 } SMARTLIST_FOREACH_END(control_conn);
567 smartlist_free(queued_events);
568 smartlist_free(controllers);
570 --*block_event_queue;
573 /** Libevent callback: Flushes pending events to controllers that are
574 * interested in them. */
575 static void
576 flush_queued_events_cb(mainloop_event_t *event, void *arg)
578 (void) event;
579 (void) arg;
580 queued_events_flush_all(0);
583 /** Send an event to all v1 controllers that are listening for code
584 * <b>event</b>. The event's body is given by <b>msg</b>.
586 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
587 * respect to the EXTENDED_EVENTS feature. */
588 MOCK_IMPL(STATIC void,
589 send_control_event_string,(uint16_t event,
590 const char *msg))
592 tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
593 queue_control_event_string(event, tor_strdup(msg));
596 /** Helper for send_control_event and control_event_status:
597 * Send an event to all v1 controllers that are listening for code
598 * <b>event</b>. The event's body is created by the printf-style format in
599 * <b>format</b>, and other arguments as provided. */
600 static void
601 send_control_event_impl(uint16_t event,
602 const char *format, va_list ap)
604 char *buf = NULL;
605 int len;
607 len = tor_vasprintf(&buf, format, ap);
608 if (len < 0) {
609 log_warn(LD_BUG, "Unable to format event for controller.");
610 return;
613 queue_control_event_string(event, buf);
616 /** Send an event to all v1 controllers that are listening for code
617 * <b>event</b>. The event's body is created by the printf-style format in
618 * <b>format</b>, and other arguments as provided. */
619 static void
620 send_control_event(uint16_t event,
621 const char *format, ...)
623 va_list ap;
624 va_start(ap, format);
625 send_control_event_impl(event, format, ap);
626 va_end(ap);
629 /** Something major has happened to circuit <b>circ</b>: tell any
630 * interested control connections. */
632 control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
633 int reason_code)
635 const char *status;
636 char reasons[64] = "";
638 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
639 return 0;
640 tor_assert(circ);
642 switch (tp)
644 case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
645 case CIRC_EVENT_BUILT: status = "BUILT"; break;
646 case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
647 case CIRC_EVENT_FAILED: status = "FAILED"; break;
648 case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
649 default:
650 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
651 tor_fragile_assert();
652 return 0;
655 if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
656 const char *reason_str = circuit_end_reason_to_control_string(reason_code);
657 char unk_reason_buf[16];
658 if (!reason_str) {
659 tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
660 reason_str = unk_reason_buf;
662 if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
663 tor_snprintf(reasons, sizeof(reasons),
664 " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
665 } else {
666 tor_snprintf(reasons, sizeof(reasons),
667 " REASON=%s", reason_str);
672 char *circdesc = circuit_describe_status_for_controller(circ);
673 const char *sp = strlen(circdesc) ? " " : "";
674 send_control_event(EVENT_CIRCUIT_STATUS,
675 "650 CIRC %lu %s%s%s%s\r\n",
676 (unsigned long)circ->global_identifier,
677 status, sp,
678 circdesc,
679 reasons);
680 tor_free(circdesc);
683 return 0;
686 /** Something minor has happened to circuit <b>circ</b>: tell any
687 * interested control connections. */
688 static int
689 control_event_circuit_status_minor(origin_circuit_t *circ,
690 circuit_status_minor_event_t e,
691 int purpose, const struct timeval *tv)
693 const char *event_desc;
694 char event_tail[160] = "";
695 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
696 return 0;
697 tor_assert(circ);
699 switch (e)
701 case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
702 event_desc = "PURPOSE_CHANGED";
705 /* event_tail can currently be up to 68 chars long */
706 const char *hs_state_str =
707 circuit_purpose_to_controller_hs_state_string(purpose);
708 tor_snprintf(event_tail, sizeof(event_tail),
709 " OLD_PURPOSE=%s%s%s",
710 circuit_purpose_to_controller_string(purpose),
711 (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
712 (hs_state_str != NULL) ? hs_state_str : "");
715 break;
716 case CIRC_MINOR_EVENT_CANNIBALIZED:
717 event_desc = "CANNIBALIZED";
720 /* event_tail can currently be up to 130 chars long */
721 const char *hs_state_str =
722 circuit_purpose_to_controller_hs_state_string(purpose);
723 const struct timeval *old_timestamp_began = tv;
724 char tbuf[ISO_TIME_USEC_LEN+1];
725 format_iso_time_nospace_usec(tbuf, old_timestamp_began);
727 tor_snprintf(event_tail, sizeof(event_tail),
728 " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
729 circuit_purpose_to_controller_string(purpose),
730 (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
731 (hs_state_str != NULL) ? hs_state_str : "",
732 tbuf);
735 break;
736 default:
737 log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
738 tor_fragile_assert();
739 return 0;
743 char *circdesc = circuit_describe_status_for_controller(circ);
744 const char *sp = strlen(circdesc) ? " " : "";
745 send_control_event(EVENT_CIRCUIT_STATUS_MINOR,
746 "650 CIRC_MINOR %lu %s%s%s%s\r\n",
747 (unsigned long)circ->global_identifier,
748 event_desc, sp,
749 circdesc,
750 event_tail);
751 tor_free(circdesc);
754 return 0;
758 * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
759 * interested controllers.
762 control_event_circuit_purpose_changed(origin_circuit_t *circ,
763 int old_purpose)
765 return control_event_circuit_status_minor(circ,
766 CIRC_MINOR_EVENT_PURPOSE_CHANGED,
767 old_purpose,
768 NULL);
772 * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
773 * created-time from <b>old_tv_created</b>: tell any interested controllers.
776 control_event_circuit_cannibalized(origin_circuit_t *circ,
777 int old_purpose,
778 const struct timeval *old_tv_created)
780 return control_event_circuit_status_minor(circ,
781 CIRC_MINOR_EVENT_CANNIBALIZED,
782 old_purpose,
783 old_tv_created);
786 /** Something has happened to the stream associated with AP connection
787 * <b>conn</b>: tell any interested control connections. */
789 control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
790 int reason_code)
792 char reason_buf[64];
793 char addrport_buf[64];
794 const char *status;
795 circuit_t *circ;
796 origin_circuit_t *origin_circ = NULL;
797 char buf[256];
798 const char *purpose = "";
799 tor_assert(conn->socks_request);
801 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
802 return 0;
804 if (tp == STREAM_EVENT_CLOSED &&
805 (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
806 return 0;
808 write_stream_target_to_buf(conn, buf, sizeof(buf));
810 reason_buf[0] = '\0';
811 switch (tp)
813 case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
814 case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
815 case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
816 case STREAM_EVENT_FAILED: status = "FAILED"; break;
817 case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
818 case STREAM_EVENT_NEW: status = "NEW"; break;
819 case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
820 case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
821 case STREAM_EVENT_REMAP: status = "REMAP"; break;
822 case STREAM_EVENT_CONTROLLER_WAIT: status = "CONTROLLER_WAIT"; break;
823 case STREAM_EVENT_XOFF_SENT: status = "XOFF_SENT"; break;
824 case STREAM_EVENT_XOFF_RECV: status = "XOFF_RECV"; break;
825 case STREAM_EVENT_XON_SENT: status = "XON_SENT"; break;
826 case STREAM_EVENT_XON_RECV: status = "XON_RECV"; break;
827 default:
828 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
829 return 0;
831 if (reason_code && (tp == STREAM_EVENT_FAILED ||
832 tp == STREAM_EVENT_CLOSED ||
833 tp == STREAM_EVENT_FAILED_RETRIABLE)) {
834 const char *reason_str = stream_end_reason_to_control_string(reason_code);
835 char *r = NULL;
836 if (!reason_str) {
837 tor_asprintf(&r, " UNKNOWN_%d", reason_code);
838 reason_str = r;
840 if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
841 tor_snprintf(reason_buf, sizeof(reason_buf),
842 " REASON=END REMOTE_REASON=%s", reason_str);
843 else
844 tor_snprintf(reason_buf, sizeof(reason_buf),
845 " REASON=%s", reason_str);
846 tor_free(r);
847 } else if (reason_code && tp == STREAM_EVENT_REMAP) {
848 switch (reason_code) {
849 case REMAP_STREAM_SOURCE_CACHE:
850 strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
851 break;
852 case REMAP_STREAM_SOURCE_EXIT:
853 strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
854 break;
855 default:
856 tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
857 reason_code);
858 /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
859 break;
863 if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
865 * When the control conn is an AF_UNIX socket and we have no address,
866 * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
867 * dnsserv.c.
869 if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
870 tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
871 ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
872 } else {
874 * else leave it blank so control on AF_UNIX doesn't need to make
875 * something up.
877 addrport_buf[0] = '\0';
879 } else {
880 addrport_buf[0] = '\0';
883 if (tp == STREAM_EVENT_NEW_RESOLVE) {
884 purpose = " PURPOSE=DNS_REQUEST";
885 } else if (tp == STREAM_EVENT_NEW) {
886 if (conn->use_begindir) {
887 connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
888 int linked_dir_purpose = -1;
889 if (linked && linked->type == CONN_TYPE_DIR)
890 linked_dir_purpose = linked->purpose;
891 if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
892 purpose = " PURPOSE=DIR_UPLOAD";
893 else
894 purpose = " PURPOSE=DIR_FETCH";
895 } else
896 purpose = " PURPOSE=USER";
899 circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
900 if (circ && CIRCUIT_IS_ORIGIN(circ))
901 origin_circ = TO_ORIGIN_CIRCUIT(circ);
904 char *conndesc = entry_connection_describe_status_for_controller(conn);
905 const char *sp = strlen(conndesc) ? " " : "";
906 send_control_event(EVENT_STREAM_STATUS,
907 "650 STREAM %"PRIu64" %s %lu %s%s%s%s%s%s\r\n",
908 (ENTRY_TO_CONN(conn)->global_identifier),
909 status,
910 origin_circ?
911 (unsigned long)origin_circ->global_identifier : 0ul,
912 buf, reason_buf, addrport_buf, purpose, sp, conndesc);
913 tor_free(conndesc);
916 /* XXX need to specify its intended exit, etc? */
918 return 0;
921 /** Called when the status of an OR connection <b>conn</b> changes: tell any
922 * interested control connections. <b>tp</b> is the new status for the
923 * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
924 * may be the reason why.
927 control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
928 int reason)
930 int ncircs = 0;
931 const char *status;
932 char name[128];
933 char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
935 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
936 return 0;
938 switch (tp)
940 case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
941 case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
942 case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
943 case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
944 case OR_CONN_EVENT_NEW: status = "NEW"; break;
945 default:
946 log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
947 return 0;
949 if (conn->chan) {
950 ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
951 } else {
952 ncircs = 0;
954 ncircs += connection_or_get_num_circuits(conn);
955 if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
956 tor_snprintf(ncircs_buf, sizeof(ncircs_buf), " NCIRCS=%d", ncircs);
959 orconn_target_get_name(name, sizeof(name), conn);
960 send_control_event(EVENT_OR_CONN_STATUS,
961 "650 ORCONN %s %s%s%s%s ID=%"PRIu64"\r\n",
962 name, status,
963 reason ? " REASON=" : "",
964 orconn_end_reason_to_control_string(reason),
965 ncircs_buf,
966 (conn->base_.global_identifier));
968 return 0;
972 * Print out STREAM_BW event for a single conn
975 control_event_stream_bandwidth(edge_connection_t *edge_conn)
977 struct timeval now;
978 char tbuf[ISO_TIME_USEC_LEN+1];
979 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
980 if (!edge_conn->n_read && !edge_conn->n_written)
981 return 0;
983 tor_gettimeofday(&now);
984 format_iso_time_nospace_usec(tbuf, &now);
985 send_control_event(EVENT_STREAM_BANDWIDTH_USED,
986 "650 STREAM_BW %"PRIu64" %lu %lu %s\r\n",
987 (edge_conn->base_.global_identifier),
988 (unsigned long)edge_conn->n_read,
989 (unsigned long)edge_conn->n_written,
990 tbuf);
992 edge_conn->n_written = edge_conn->n_read = 0;
995 return 0;
998 /** A second or more has elapsed: tell any interested control
999 * connections how much bandwidth streams have used. */
1001 control_event_stream_bandwidth_used(void)
1003 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
1004 smartlist_t *conns = get_connection_array();
1005 edge_connection_t *edge_conn;
1006 struct timeval now;
1007 char tbuf[ISO_TIME_USEC_LEN+1];
1009 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
1011 if (conn->type != CONN_TYPE_AP)
1012 continue;
1013 edge_conn = TO_EDGE_CONN(conn);
1014 if (!edge_conn->n_read && !edge_conn->n_written)
1015 continue;
1017 tor_gettimeofday(&now);
1018 format_iso_time_nospace_usec(tbuf, &now);
1019 send_control_event(EVENT_STREAM_BANDWIDTH_USED,
1020 "650 STREAM_BW %"PRIu64" %lu %lu %s\r\n",
1021 (edge_conn->base_.global_identifier),
1022 (unsigned long)edge_conn->n_read,
1023 (unsigned long)edge_conn->n_written,
1024 tbuf);
1026 edge_conn->n_written = edge_conn->n_read = 0;
1028 SMARTLIST_FOREACH_END(conn);
1031 return 0;
1034 /** A second or more has elapsed: tell any interested control connections
1035 * how much bandwidth origin circuits have used. */
1037 control_event_circ_bandwidth_used(void)
1039 if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
1040 return 0;
1042 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1043 if (!CIRCUIT_IS_ORIGIN(circ))
1044 continue;
1046 control_event_circ_bandwidth_used_for_circ(TO_ORIGIN_CIRCUIT(circ));
1048 SMARTLIST_FOREACH_END(circ);
1050 return 0;
1054 * Emit a CIRC_BW event line for a specific circuit.
1056 * This function sets the values it emits to 0, and does not emit
1057 * an event if there is no new data to report since the last call.
1059 * Therefore, it may be called at any frequency.
1062 control_event_circ_bandwidth_used_for_circ(origin_circuit_t *ocirc)
1064 struct timeval now;
1065 char tbuf[ISO_TIME_USEC_LEN+1];
1067 tor_assert(ocirc);
1069 if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
1070 return 0;
1072 /* n_read_circ_bw and n_written_circ_bw are always updated
1073 * when there is any new cell on a circuit, and set to 0 after
1074 * the event, below.
1076 * Therefore, checking them is sufficient to determine if there
1077 * is new data to report. */
1078 if (!ocirc->n_read_circ_bw && !ocirc->n_written_circ_bw)
1079 return 0;
1081 tor_gettimeofday(&now);
1082 format_iso_time_nospace_usec(tbuf, &now);
1084 char *ccontrol_buf = congestion_control_get_control_port_fields(ocirc);
1085 send_control_event(EVENT_CIRC_BANDWIDTH_USED,
1086 "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu TIME=%s "
1087 "DELIVERED_READ=%lu OVERHEAD_READ=%lu "
1088 "DELIVERED_WRITTEN=%lu OVERHEAD_WRITTEN=%lu%s\r\n",
1089 ocirc->global_identifier,
1090 (unsigned long)ocirc->n_read_circ_bw,
1091 (unsigned long)ocirc->n_written_circ_bw,
1092 tbuf,
1093 (unsigned long)ocirc->n_delivered_read_circ_bw,
1094 (unsigned long)ocirc->n_overhead_read_circ_bw,
1095 (unsigned long)ocirc->n_delivered_written_circ_bw,
1096 (unsigned long)ocirc->n_overhead_written_circ_bw,
1097 ccontrol_buf ? ccontrol_buf : "");
1099 ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
1100 ocirc->n_overhead_written_circ_bw = ocirc->n_overhead_read_circ_bw = 0;
1101 ocirc->n_delivered_written_circ_bw = ocirc->n_delivered_read_circ_bw = 0;
1103 if (ccontrol_buf)
1104 tor_free(ccontrol_buf);
1106 return 0;
1109 /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
1110 * bandwidth counters. */
1112 control_event_conn_bandwidth(connection_t *conn)
1114 const char *conn_type_str;
1115 if (!get_options()->TestingEnableConnBwEvent ||
1116 !EVENT_IS_INTERESTING(EVENT_CONN_BW))
1117 return 0;
1118 if (!conn->n_read_conn_bw && !conn->n_written_conn_bw)
1119 return 0;
1120 switch (conn->type) {
1121 case CONN_TYPE_OR:
1122 conn_type_str = "OR";
1123 break;
1124 case CONN_TYPE_DIR:
1125 conn_type_str = "DIR";
1126 break;
1127 case CONN_TYPE_EXIT:
1128 conn_type_str = "EXIT";
1129 break;
1130 default:
1131 return 0;
1133 send_control_event(EVENT_CONN_BW,
1134 "650 CONN_BW ID=%"PRIu64" TYPE=%s "
1135 "READ=%lu WRITTEN=%lu\r\n",
1136 (conn->global_identifier),
1137 conn_type_str,
1138 (unsigned long)conn->n_read_conn_bw,
1139 (unsigned long)conn->n_written_conn_bw);
1140 conn->n_written_conn_bw = conn->n_read_conn_bw = 0;
1141 return 0;
1144 /** A second or more has elapsed: tell any interested control
1145 * connections how much bandwidth connections have used. */
1147 control_event_conn_bandwidth_used(void)
1149 if (get_options()->TestingEnableConnBwEvent &&
1150 EVENT_IS_INTERESTING(EVENT_CONN_BW)) {
1151 SMARTLIST_FOREACH(get_connection_array(), connection_t *, conn,
1152 control_event_conn_bandwidth(conn));
1154 return 0;
1157 /** Helper: iterate over cell statistics of <b>circ</b> and sum up added
1158 * cells, removed cells, and waiting times by cell command and direction.
1159 * Store results in <b>cell_stats</b>. Free cell statistics of the
1160 * circuit afterwards. */
1161 void
1162 sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
1164 memset(cell_stats, 0, sizeof(cell_stats_t));
1165 SMARTLIST_FOREACH_BEGIN(circ->testing_cell_stats,
1166 const testing_cell_stats_entry_t *, ent) {
1167 tor_assert(ent->command <= CELL_COMMAND_MAX_);
1168 if (!ent->removed && !ent->exitward) {
1169 cell_stats->added_cells_appward[ent->command] += 1;
1170 } else if (!ent->removed && ent->exitward) {
1171 cell_stats->added_cells_exitward[ent->command] += 1;
1172 } else if (!ent->exitward) {
1173 cell_stats->removed_cells_appward[ent->command] += 1;
1174 cell_stats->total_time_appward[ent->command] += ent->waiting_time * 10;
1175 } else {
1176 cell_stats->removed_cells_exitward[ent->command] += 1;
1177 cell_stats->total_time_exitward[ent->command] += ent->waiting_time * 10;
1179 } SMARTLIST_FOREACH_END(ent);
1180 circuit_clear_testing_cell_stats(circ);
1183 /** Helper: append a cell statistics string to <code>event_parts</code>,
1184 * prefixed with <code>key</code>=. Statistics consist of comma-separated
1185 * key:value pairs with lower-case command strings as keys and cell
1186 * numbers or total waiting times as values. A key:value pair is included
1187 * if the entry in <code>include_if_non_zero</code> is not zero, but with
1188 * the (possibly zero) entry from <code>number_to_include</code>. Both
1189 * arrays are expected to have a length of CELL_COMMAND_MAX_ + 1. If no
1190 * entry in <code>include_if_non_zero</code> is positive, no string will
1191 * be added to <code>event_parts</code>. */
1192 void
1193 append_cell_stats_by_command(smartlist_t *event_parts, const char *key,
1194 const uint64_t *include_if_non_zero,
1195 const uint64_t *number_to_include)
1197 smartlist_t *key_value_strings = smartlist_new();
1198 int i;
1199 for (i = 0; i <= CELL_COMMAND_MAX_; i++) {
1200 if (include_if_non_zero[i] > 0) {
1201 smartlist_add_asprintf(key_value_strings, "%s:%"PRIu64,
1202 cell_command_to_string(i),
1203 (number_to_include[i]));
1206 if (smartlist_len(key_value_strings) > 0) {
1207 char *joined = smartlist_join_strings(key_value_strings, ",", 0, NULL);
1208 smartlist_add_asprintf(event_parts, "%s=%s", key, joined);
1209 SMARTLIST_FOREACH(key_value_strings, char *, cp, tor_free(cp));
1210 tor_free(joined);
1212 smartlist_free(key_value_strings);
1215 /** Helper: format <b>cell_stats</b> for <b>circ</b> for inclusion in a
1216 * CELL_STATS event and write result string to <b>event_string</b>. */
1217 void
1218 format_cell_stats(char **event_string, circuit_t *circ,
1219 cell_stats_t *cell_stats)
1221 smartlist_t *event_parts = smartlist_new();
1222 if (CIRCUIT_IS_ORIGIN(circ)) {
1223 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1224 smartlist_add_asprintf(event_parts, "ID=%lu",
1225 (unsigned long)ocirc->global_identifier);
1226 } else if (TO_OR_CIRCUIT(circ)->p_chan) {
1227 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1228 smartlist_add_asprintf(event_parts, "InboundQueue=%lu",
1229 (unsigned long)or_circ->p_circ_id);
1230 smartlist_add_asprintf(event_parts, "InboundConn=%"PRIu64,
1231 (or_circ->p_chan->global_identifier));
1232 append_cell_stats_by_command(event_parts, "InboundAdded",
1233 cell_stats->added_cells_appward,
1234 cell_stats->added_cells_appward);
1235 append_cell_stats_by_command(event_parts, "InboundRemoved",
1236 cell_stats->removed_cells_appward,
1237 cell_stats->removed_cells_appward);
1238 append_cell_stats_by_command(event_parts, "InboundTime",
1239 cell_stats->removed_cells_appward,
1240 cell_stats->total_time_appward);
1242 if (circ->n_chan) {
1243 smartlist_add_asprintf(event_parts, "OutboundQueue=%lu",
1244 (unsigned long)circ->n_circ_id);
1245 smartlist_add_asprintf(event_parts, "OutboundConn=%"PRIu64,
1246 (circ->n_chan->global_identifier));
1247 append_cell_stats_by_command(event_parts, "OutboundAdded",
1248 cell_stats->added_cells_exitward,
1249 cell_stats->added_cells_exitward);
1250 append_cell_stats_by_command(event_parts, "OutboundRemoved",
1251 cell_stats->removed_cells_exitward,
1252 cell_stats->removed_cells_exitward);
1253 append_cell_stats_by_command(event_parts, "OutboundTime",
1254 cell_stats->removed_cells_exitward,
1255 cell_stats->total_time_exitward);
1257 *event_string = smartlist_join_strings(event_parts, " ", 0, NULL);
1258 SMARTLIST_FOREACH(event_parts, char *, cp, tor_free(cp));
1259 smartlist_free(event_parts);
1262 /** A second or more has elapsed: tell any interested control connection
1263 * how many cells have been processed for a given circuit. */
1265 control_event_circuit_cell_stats(void)
1267 cell_stats_t *cell_stats;
1268 char *event_string;
1269 if (!get_options()->TestingEnableCellStatsEvent ||
1270 !EVENT_IS_INTERESTING(EVENT_CELL_STATS))
1271 return 0;
1272 cell_stats = tor_malloc(sizeof(cell_stats_t));
1273 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1274 if (!circ->testing_cell_stats)
1275 continue;
1276 sum_up_cell_stats_by_command(circ, cell_stats);
1277 format_cell_stats(&event_string, circ, cell_stats);
1278 send_control_event(EVENT_CELL_STATS,
1279 "650 CELL_STATS %s\r\n", event_string);
1280 tor_free(event_string);
1282 SMARTLIST_FOREACH_END(circ);
1283 tor_free(cell_stats);
1284 return 0;
1287 /* about 5 minutes worth. */
1288 #define N_BW_EVENTS_TO_CACHE 300
1289 /* Index into cached_bw_events to next write. */
1290 static int next_measurement_idx = 0;
1291 /* number of entries set in n_measurements */
1292 static int n_measurements = 0;
1293 static struct cached_bw_event_t {
1294 uint32_t n_read;
1295 uint32_t n_written;
1296 } cached_bw_events[N_BW_EVENTS_TO_CACHE];
1298 /** A second or more has elapsed: tell any interested control
1299 * connections how much bandwidth we used. */
1301 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
1303 cached_bw_events[next_measurement_idx].n_read = n_read;
1304 cached_bw_events[next_measurement_idx].n_written = n_written;
1305 if (++next_measurement_idx == N_BW_EVENTS_TO_CACHE)
1306 next_measurement_idx = 0;
1307 if (n_measurements < N_BW_EVENTS_TO_CACHE)
1308 ++n_measurements;
1310 if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
1311 send_control_event(EVENT_BANDWIDTH_USED,
1312 "650 BW %lu %lu\r\n",
1313 (unsigned long)n_read,
1314 (unsigned long)n_written);
1317 return 0;
1320 char *
1321 get_bw_samples(void)
1323 int i;
1324 int idx = (next_measurement_idx + N_BW_EVENTS_TO_CACHE - n_measurements)
1325 % N_BW_EVENTS_TO_CACHE;
1326 tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
1328 smartlist_t *elements = smartlist_new();
1330 for (i = 0; i < n_measurements; ++i) {
1331 tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
1332 const struct cached_bw_event_t *bwe = &cached_bw_events[idx];
1334 smartlist_add_asprintf(elements, "%u,%u",
1335 (unsigned)bwe->n_read,
1336 (unsigned)bwe->n_written);
1338 idx = (idx + 1) % N_BW_EVENTS_TO_CACHE;
1341 char *result = smartlist_join_strings(elements, " ", 0, NULL);
1343 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
1344 smartlist_free(elements);
1346 return result;
1349 /** Called when we are sending a log message to the controllers: suspend
1350 * sending further log messages to the controllers until we're done. Used by
1351 * CONN_LOG_PROTECT. */
1352 void
1353 disable_control_logging(void)
1355 ++disable_log_messages;
1358 /** We're done sending a log message to the controllers: re-enable controller
1359 * logging. Used by CONN_LOG_PROTECT. */
1360 void
1361 enable_control_logging(void)
1363 if (--disable_log_messages < 0)
1364 tor_assert(0);
1367 /** Remove newline and carriage-return characters from @a msg, replacing them
1368 * with spaces, and discarding any that appear at the end of the message */
1369 void
1370 control_logmsg_strip_newlines(char *msg)
1372 char *cp;
1373 for (cp = msg; *cp; ++cp) {
1374 if (*cp == '\r' || *cp == '\n') {
1375 *cp = ' ';
1378 if (cp == msg)
1379 return;
1380 /* Remove trailing spaces */
1381 for (--cp; *cp == ' '; --cp) {
1382 *cp = '\0';
1383 if (cp == msg)
1384 break;
1388 /** We got a log message: tell any interested control connections. */
1389 void
1390 control_event_logmsg(int severity, log_domain_mask_t domain, const char *msg)
1392 int event;
1394 /* Don't even think of trying to add stuff to a buffer from a cpuworker
1395 * thread. (See #25987 for plan to fix.) */
1396 if (! in_main_thread())
1397 return;
1399 if (disable_log_messages)
1400 return;
1402 if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
1403 severity <= LOG_NOTICE) {
1404 char *esc = esc_for_log(msg);
1405 ++disable_log_messages;
1406 control_event_general_status(severity, "BUG REASON=%s", esc);
1407 --disable_log_messages;
1408 tor_free(esc);
1411 event = log_severity_to_event(severity);
1412 if (event >= 0 && EVENT_IS_INTERESTING(event)) {
1413 char *b = NULL;
1414 const char *s;
1415 if (strchr(msg, '\n')) {
1416 b = tor_strdup(msg);
1417 control_logmsg_strip_newlines(b);
1419 switch (severity) {
1420 case LOG_DEBUG: s = "DEBUG"; break;
1421 case LOG_INFO: s = "INFO"; break;
1422 case LOG_NOTICE: s = "NOTICE"; break;
1423 case LOG_WARN: s = "WARN"; break;
1424 case LOG_ERR: s = "ERR"; break;
1425 default: s = "UnknownLogSeverity"; break;
1427 ++disable_log_messages;
1428 send_control_event(event, "650 %s %s\r\n", s, b?b:msg);
1429 if (severity == LOG_ERR) {
1430 /* Force a flush, since we may be about to die horribly */
1431 queued_events_flush_all(1);
1433 --disable_log_messages;
1434 tor_free(b);
1439 * Logging callback: called when there is a queued pending log callback.
1441 void
1442 control_event_logmsg_pending(void)
1444 if (! in_main_thread()) {
1445 /* We can't handle this case yet, since we're using a
1446 * mainloop_event_t to invoke queued_events_flush_all. We ought to
1447 * use a different mechanism instead: see #25987.
1449 return;
1451 tor_assert(flush_queued_events_event);
1452 mainloop_event_activate(flush_queued_events_event);
1455 /** Called whenever we receive new router descriptors: tell any
1456 * interested control connections. <b>routers</b> is a list of
1457 * routerinfo_t's.
1460 control_event_descriptors_changed(smartlist_t *routers)
1462 char *msg;
1464 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
1465 return 0;
1468 smartlist_t *names = smartlist_new();
1469 char *ids;
1470 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
1471 char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
1472 router_get_verbose_nickname(b, ri);
1473 smartlist_add(names, b);
1475 ids = smartlist_join_strings(names, " ", 0, NULL);
1476 tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
1477 send_control_event_string(EVENT_NEW_DESC, msg);
1478 tor_free(ids);
1479 tor_free(msg);
1480 SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
1481 smartlist_free(names);
1483 return 0;
1486 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
1487 * <b>expires</b> values less than 3 are special; see connection_edge.c. If
1488 * <b>error</b> is non-NULL, it is an error code describing the failure
1489 * mode of the mapping.
1492 control_event_address_mapped(const char *from, const char *to,
1493 time_t expires, const char *error,
1494 const int cached, uint64_t stream_id)
1496 char *stream_id_str = NULL;
1497 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
1498 return 0;
1500 if (stream_id) {
1501 tor_asprintf(&stream_id_str, " STREAMID=%"PRIu64"", stream_id);
1504 if (expires < 3 || expires == TIME_MAX)
1505 send_control_event(EVENT_ADDRMAP,
1506 "650 ADDRMAP %s %s NEVER %s%s"
1507 "CACHED=\"%s\"%s\r\n",
1508 from, to, error ? error : "", error ? " " : "",
1509 cached ? "YES" : "NO",
1510 stream_id ? stream_id_str : "");
1511 else {
1512 char buf[ISO_TIME_LEN+1];
1513 char buf2[ISO_TIME_LEN+1];
1514 format_local_iso_time(buf,expires);
1515 format_iso_time(buf2,expires);
1516 send_control_event(EVENT_ADDRMAP,
1517 "650 ADDRMAP %s %s \"%s\" %s%sEXPIRES=\"%s\" "
1518 "CACHED=\"%s\"%s\r\n",
1519 from, to, buf, error ? error : "",
1520 error ? " " : "", buf2, cached ? "YES" : "NO",
1521 stream_id ? stream_id_str: "");
1524 tor_free(stream_id_str);
1526 return 0;
1528 /** The network liveness has changed; this is called from circuitstats.c
1529 * whenever we receive a cell, or when timeout expires and we assume the
1530 * network is down. */
1532 control_event_network_liveness_update(int liveness)
1534 if (liveness > 0) {
1535 if (get_cached_network_liveness() <= 0) {
1536 /* Update cached liveness */
1537 set_cached_network_liveness(1);
1538 log_debug(LD_CONTROL, "Sending NETWORK_LIVENESS UP");
1539 send_control_event_string(EVENT_NETWORK_LIVENESS,
1540 "650 NETWORK_LIVENESS UP\r\n");
1542 /* else was already live, no-op */
1543 } else {
1544 if (get_cached_network_liveness() > 0) {
1545 /* Update cached liveness */
1546 set_cached_network_liveness(0);
1547 log_debug(LD_CONTROL, "Sending NETWORK_LIVENESS DOWN");
1548 send_control_event_string(EVENT_NETWORK_LIVENESS,
1549 "650 NETWORK_LIVENESS DOWN\r\n");
1551 /* else was already dead, no-op */
1554 return 0;
1557 /** Helper function for NS-style events. Constructs and sends an event
1558 * of type <b>event</b> with string <b>event_string</b> out of the set of
1559 * networkstatuses <b>statuses</b>. Currently it is used for NS events
1560 * and NEWCONSENSUS events. */
1561 static int
1562 control_event_networkstatus_changed_helper(smartlist_t *statuses,
1563 uint16_t event,
1564 const char *event_string)
1566 smartlist_t *strs;
1567 char *s, *esc = NULL;
1568 if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
1569 return 0;
1571 strs = smartlist_new();
1572 smartlist_add_strdup(strs, "650+");
1573 smartlist_add_strdup(strs, event_string);
1574 smartlist_add_strdup(strs, "\r\n");
1575 SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
1577 s = networkstatus_getinfo_helper_single(rs);
1578 if (!s) continue;
1579 smartlist_add(strs, s);
1582 s = smartlist_join_strings(strs, "", 0, NULL);
1583 write_escaped_data(s, strlen(s), &esc);
1584 SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
1585 smartlist_free(strs);
1586 tor_free(s);
1587 send_control_event_string(event, esc);
1588 send_control_event_string(event,
1589 "650 OK\r\n");
1591 tor_free(esc);
1592 return 0;
1595 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
1596 * an NS event to any controller that cares. */
1598 control_event_networkstatus_changed(smartlist_t *statuses)
1600 return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
1603 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
1604 * event consisting of an NS-style line for each relay in the consensus. */
1606 control_event_newconsensus(const networkstatus_t *consensus)
1608 if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
1609 return 0;
1610 return control_event_networkstatus_changed_helper(
1611 consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
1614 /** Called when we compute a new circuitbuildtimeout */
1616 control_event_buildtimeout_set(buildtimeout_set_event_t type,
1617 const char *args)
1619 const char *type_string = NULL;
1621 if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
1622 return 0;
1624 switch (type) {
1625 case BUILDTIMEOUT_SET_EVENT_COMPUTED:
1626 type_string = "COMPUTED";
1627 break;
1628 case BUILDTIMEOUT_SET_EVENT_RESET:
1629 type_string = "RESET";
1630 break;
1631 case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
1632 type_string = "SUSPENDED";
1633 break;
1634 case BUILDTIMEOUT_SET_EVENT_DISCARD:
1635 type_string = "DISCARD";
1636 break;
1637 case BUILDTIMEOUT_SET_EVENT_RESUME:
1638 type_string = "RESUME";
1639 break;
1640 default:
1641 type_string = "UNKNOWN";
1642 break;
1645 send_control_event(EVENT_BUILDTIMEOUT_SET,
1646 "650 BUILDTIMEOUT_SET %s %s\r\n",
1647 type_string, args);
1649 return 0;
1652 /** Called when a signal has been processed from signal_callback */
1654 control_event_signal(uintptr_t signal_num)
1656 const char *signal_string = NULL;
1658 if (!control_event_is_interesting(EVENT_GOT_SIGNAL))
1659 return 0;
1661 for (unsigned i = 0; signal_table[i].signal_name != NULL; ++i) {
1662 if ((int)signal_num == signal_table[i].sig) {
1663 signal_string = signal_table[i].signal_name;
1664 break;
1668 if (signal_string == NULL) {
1669 log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
1670 (unsigned long)signal_num);
1671 return -1;
1674 send_control_event(EVENT_GOT_SIGNAL, "650 SIGNAL %s\r\n",
1675 signal_string);
1676 return 0;
1679 /** Called when a single local_routerstatus_t has changed: Sends an NS event
1680 * to any controller that cares. */
1682 control_event_networkstatus_changed_single(const routerstatus_t *rs)
1684 smartlist_t *statuses;
1685 int r;
1687 if (!EVENT_IS_INTERESTING(EVENT_NS))
1688 return 0;
1690 statuses = smartlist_new();
1691 smartlist_add(statuses, (void*)rs);
1692 r = control_event_networkstatus_changed(statuses);
1693 smartlist_free(statuses);
1694 return r;
1697 /** Our own router descriptor has changed; tell any controllers that care.
1700 control_event_my_descriptor_changed(void)
1702 send_control_event(EVENT_DESCCHANGED, "650 DESCCHANGED\r\n");
1703 return 0;
1706 /** Helper: sends a status event where <b>type</b> is one of
1707 * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
1708 * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
1709 * string corresponding to <b>args</b>. */
1710 static int
1711 control_event_status(int type, int severity, const char *format, va_list args)
1713 char *user_buf = NULL;
1714 char format_buf[160];
1715 const char *status, *sev;
1717 switch (type) {
1718 case EVENT_STATUS_GENERAL:
1719 status = "STATUS_GENERAL";
1720 break;
1721 case EVENT_STATUS_CLIENT:
1722 status = "STATUS_CLIENT";
1723 break;
1724 case EVENT_STATUS_SERVER:
1725 status = "STATUS_SERVER";
1726 break;
1727 default:
1728 log_warn(LD_BUG, "Unrecognized status type %d", type);
1729 return -1;
1731 switch (severity) {
1732 case LOG_NOTICE:
1733 sev = "NOTICE";
1734 break;
1735 case LOG_WARN:
1736 sev = "WARN";
1737 break;
1738 case LOG_ERR:
1739 sev = "ERR";
1740 break;
1741 default:
1742 log_warn(LD_BUG, "Unrecognized status severity %d", severity);
1743 return -1;
1745 if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
1746 status, sev)<0) {
1747 log_warn(LD_BUG, "Format string too long.");
1748 return -1;
1750 if (tor_vasprintf(&user_buf, format, args)<0) {
1751 log_warn(LD_BUG, "Failed to create user buffer.");
1752 return -1;
1755 send_control_event(type, "%s %s\r\n", format_buf, user_buf);
1756 tor_free(user_buf);
1757 return 0;
1760 #ifndef COCCI
1761 #define CONTROL_EVENT_STATUS_BODY(event, sev) \
1762 int r; \
1763 do { \
1764 va_list ap; \
1765 if (!EVENT_IS_INTERESTING(event)) \
1766 return 0; \
1768 va_start(ap, format); \
1769 r = control_event_status((event), (sev), format, ap); \
1770 va_end(ap); \
1771 } while (0)
1772 #endif /* !defined(COCCI) */
1774 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
1775 * by formatting the arguments using the printf-style <b>format</b>. */
1777 control_event_general_status(int severity, const char *format, ...)
1779 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, severity);
1780 return r;
1783 /** Format and send an EVENT_STATUS_GENERAL LOG_ERR event, and flush it to the
1784 * controller(s) immediately. */
1786 control_event_general_error(const char *format, ...)
1788 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, LOG_ERR);
1789 /* Force a flush, since we may be about to die horribly */
1790 queued_events_flush_all(1);
1791 return r;
1794 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
1795 * by formatting the arguments using the printf-style <b>format</b>. */
1797 control_event_client_status(int severity, const char *format, ...)
1799 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, severity);
1800 return r;
1803 /** Format and send an EVENT_STATUS_CLIENT LOG_ERR event, and flush it to the
1804 * controller(s) immediately. */
1806 control_event_client_error(const char *format, ...)
1808 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, LOG_ERR);
1809 /* Force a flush, since we may be about to die horribly */
1810 queued_events_flush_all(1);
1811 return r;
1814 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
1815 * by formatting the arguments using the printf-style <b>format</b>. */
1817 control_event_server_status(int severity, const char *format, ...)
1819 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, severity);
1820 return r;
1823 /** Format and send an EVENT_STATUS_SERVER LOG_ERR event, and flush it to the
1824 * controller(s) immediately. */
1826 control_event_server_error(const char *format, ...)
1828 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, LOG_ERR);
1829 /* Force a flush, since we may be about to die horribly */
1830 queued_events_flush_all(1);
1831 return r;
1834 /** Called when the status of an entry guard with the given <b>nickname</b>
1835 * and identity <b>digest</b> has changed to <b>status</b>: tells any
1836 * controllers that care. */
1838 control_event_guard(const char *nickname, const char *digest,
1839 const char *status)
1841 char hbuf[HEX_DIGEST_LEN+1];
1842 base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
1843 if (!EVENT_IS_INTERESTING(EVENT_GUARD))
1844 return 0;
1847 char buf[MAX_VERBOSE_NICKNAME_LEN+1];
1848 const node_t *node = node_get_by_id(digest);
1849 if (node) {
1850 node_get_verbose_nickname(node, buf);
1851 } else {
1852 tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
1854 send_control_event(EVENT_GUARD,
1855 "650 GUARD ENTRY %s %s\r\n", buf, status);
1857 return 0;
1860 /** Called when a configuration option changes. This is generally triggered
1861 * by SETCONF requests and RELOAD/SIGHUP signals. The <b>changes</b> are
1862 * a linked list of configuration key-values.
1863 * <b>changes</b> can be NULL, meaning "no changes".
1865 void
1866 control_event_conf_changed(const config_line_t *changes)
1868 char *result;
1869 smartlist_t *lines;
1870 if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) || !changes) {
1871 return;
1873 lines = smartlist_new();
1874 for (const config_line_t *line = changes; line; line = line->next) {
1875 if (line->value == NULL) {
1876 smartlist_add_asprintf(lines, "650-%s", line->key);
1877 } else {
1878 smartlist_add_asprintf(lines, "650-%s=%s", line->key, line->value);
1881 result = smartlist_join_strings(lines, "\r\n", 0, NULL);
1882 send_control_event(EVENT_CONF_CHANGED,
1883 "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
1884 tor_free(result);
1885 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1886 smartlist_free(lines);
1889 /** We just generated a new summary of which countries we've seen clients
1890 * from recently. Send a copy to the controller in case it wants to
1891 * display it for the user. */
1892 void
1893 control_event_clients_seen(const char *controller_str)
1895 send_control_event(EVENT_CLIENTS_SEEN,
1896 "650 CLIENTS_SEEN %s\r\n", controller_str);
1899 /** A new pluggable transport called <b>transport_name</b> was
1900 * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
1901 * "server" or "client" depending on the mode of the pluggable
1902 * transport.
1903 * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
1905 void
1906 control_event_transport_launched(const char *mode, const char *transport_name,
1907 tor_addr_t *addr, uint16_t port)
1909 send_control_event(EVENT_TRANSPORT_LAUNCHED,
1910 "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
1911 mode, transport_name, fmt_addr(addr), port);
1914 /** A pluggable transport called <b>pt_name</b> has emitted a log message
1915 * found in <b>message</b> at <b>severity</b> log level. */
1916 void
1917 control_event_pt_log(const char *log)
1919 send_control_event(EVENT_PT_LOG,
1920 "650 PT_LOG %s\r\n",
1921 log);
1924 /** A pluggable transport has emitted a STATUS message found in
1925 * <b>status</b>. */
1926 void
1927 control_event_pt_status(const char *status)
1929 send_control_event(EVENT_PT_STATUS,
1930 "650 PT_STATUS %s\r\n",
1931 status);
1934 /** Convert rendezvous auth type to string for HS_DESC control events
1936 const char *
1937 rend_auth_type_to_string(rend_auth_type_t auth_type)
1939 const char *str;
1941 switch (auth_type) {
1942 case REND_NO_AUTH:
1943 str = "NO_AUTH";
1944 break;
1945 case REND_V3_AUTH:
1946 str = "REND_V3_AUTH";
1947 break;
1948 default:
1949 str = "UNKNOWN";
1952 return str;
1955 /** Return either the onion address if the given pointer is a non empty
1956 * string else the unknown string. */
1957 static const char *
1958 rend_hsaddress_str_or_unknown(const char *onion_address)
1960 static const char *str_unknown = "UNKNOWN";
1961 const char *str_ret = str_unknown;
1963 /* No valid pointer, unknown it is. */
1964 if (!onion_address) {
1965 goto end;
1967 /* Empty onion address thus we don't know, unknown it is. */
1968 if (onion_address[0] == '\0') {
1969 goto end;
1971 /* All checks are good so return the given onion address. */
1972 str_ret = onion_address;
1974 end:
1975 return str_ret;
1978 /** send HS_DESC requested event.
1980 * <b>rend_query</b> is used to fetch requested onion address and auth type.
1981 * <b>hs_dir</b> is the description of contacting hs directory.
1982 * <b>desc_id_base32</b> is the ID of requested hs descriptor.
1983 * <b>hsdir_index</b> is the HSDir fetch index value for v3, an hex string.
1985 void
1986 control_event_hs_descriptor_requested(const char *onion_address,
1987 rend_auth_type_t auth_type,
1988 const char *id_digest,
1989 const char *desc_id,
1990 const char *hsdir_index)
1992 char *hsdir_index_field = NULL;
1994 if (BUG(!id_digest || !desc_id)) {
1995 return;
1998 if (hsdir_index) {
1999 tor_asprintf(&hsdir_index_field, " HSDIR_INDEX=%s", hsdir_index);
2002 send_control_event(EVENT_HS_DESC,
2003 "650 HS_DESC REQUESTED %s %s %s %s%s\r\n",
2004 rend_hsaddress_str_or_unknown(onion_address),
2005 rend_auth_type_to_string(auth_type),
2006 node_describe_longname_by_id(id_digest),
2007 desc_id,
2008 hsdir_index_field ? hsdir_index_field : "");
2009 tor_free(hsdir_index_field);
2012 /** send HS_DESC CREATED event when a local service generates a descriptor.
2014 * <b>onion_address</b> is service address.
2015 * <b>desc_id</b> is the descriptor ID.
2016 * <b>replica</b> is the the descriptor replica number. If it is negative, it
2017 * is ignored.
2019 void
2020 control_event_hs_descriptor_created(const char *onion_address,
2021 const char *desc_id,
2022 int replica)
2024 char *replica_field = NULL;
2026 if (BUG(!onion_address || !desc_id)) {
2027 return;
2030 if (replica >= 0) {
2031 tor_asprintf(&replica_field, " REPLICA=%d", replica);
2034 send_control_event(EVENT_HS_DESC,
2035 "650 HS_DESC CREATED %s UNKNOWN UNKNOWN %s%s\r\n",
2036 onion_address, desc_id,
2037 replica_field ? replica_field : "");
2038 tor_free(replica_field);
2041 /** send HS_DESC upload event.
2043 * <b>onion_address</b> is service address.
2044 * <b>hs_dir</b> is the description of contacting hs directory.
2045 * <b>desc_id</b> is the ID of requested hs descriptor.
2047 void
2048 control_event_hs_descriptor_upload(const char *onion_address,
2049 const char *id_digest,
2050 const char *desc_id,
2051 const char *hsdir_index)
2053 char *hsdir_index_field = NULL;
2055 if (BUG(!onion_address || !id_digest || !desc_id)) {
2056 return;
2059 if (hsdir_index) {
2060 tor_asprintf(&hsdir_index_field, " HSDIR_INDEX=%s", hsdir_index);
2063 send_control_event(EVENT_HS_DESC,
2064 "650 HS_DESC UPLOAD %s UNKNOWN %s %s%s\r\n",
2065 onion_address,
2066 node_describe_longname_by_id(id_digest),
2067 desc_id,
2068 hsdir_index_field ? hsdir_index_field : "");
2069 tor_free(hsdir_index_field);
2072 /** send HS_DESC event after got response from hs directory.
2074 * NOTE: this is an internal function used by following functions:
2075 * control_event_hsv3_descriptor_failed
2077 * So do not call this function directly.
2079 static void
2080 event_hs_descriptor_receive_end(const char *action,
2081 const char *onion_address,
2082 const char *desc_id,
2083 rend_auth_type_t auth_type,
2084 const char *hsdir_id_digest,
2085 const char *reason)
2087 char *reason_field = NULL;
2089 if (BUG(!action || !onion_address)) {
2090 return;
2093 if (reason) {
2094 tor_asprintf(&reason_field, " REASON=%s", reason);
2097 send_control_event(EVENT_HS_DESC,
2098 "650 HS_DESC %s %s %s %s%s%s\r\n",
2099 action,
2100 rend_hsaddress_str_or_unknown(onion_address),
2101 rend_auth_type_to_string(auth_type),
2102 hsdir_id_digest ?
2103 node_describe_longname_by_id(hsdir_id_digest) :
2104 "UNKNOWN",
2105 desc_id ? desc_id : "",
2106 reason_field ? reason_field : "");
2108 tor_free(reason_field);
2111 /** send HS_DESC event after got response from hs directory.
2113 * NOTE: this is an internal function used by following functions:
2114 * control_event_hs_descriptor_uploaded
2115 * control_event_hs_descriptor_upload_failed
2117 * So do not call this function directly.
2119 void
2120 control_event_hs_descriptor_upload_end(const char *action,
2121 const char *onion_address,
2122 const char *id_digest,
2123 const char *reason)
2125 char *reason_field = NULL;
2127 if (BUG(!action || !id_digest)) {
2128 return;
2131 if (reason) {
2132 tor_asprintf(&reason_field, " REASON=%s", reason);
2135 send_control_event(EVENT_HS_DESC,
2136 "650 HS_DESC %s %s UNKNOWN %s%s\r\n",
2137 action,
2138 rend_hsaddress_str_or_unknown(onion_address),
2139 node_describe_longname_by_id(id_digest),
2140 reason_field ? reason_field : "");
2142 tor_free(reason_field);
2145 /* Send HS_DESC RECEIVED event
2147 * Called when we successfully received a hidden service descriptor. */
2148 void
2149 control_event_hsv3_descriptor_received(const char *onion_address,
2150 const char *desc_id,
2151 const char *hsdir_id_digest)
2153 char *desc_id_field = NULL;
2155 if (BUG(!onion_address || !desc_id || !hsdir_id_digest)) {
2156 return;
2159 /* Because DescriptorID is an optional positional value, we need to add a
2160 * whitespace before in order to not be next to the HsDir value. */
2161 tor_asprintf(&desc_id_field, " %s", desc_id);
2163 event_hs_descriptor_receive_end("RECEIVED", onion_address, desc_id_field,
2164 REND_NO_AUTH, hsdir_id_digest, NULL);
2165 tor_free(desc_id_field);
2168 /** send HS_DESC UPLOADED event
2170 * called when we successfully uploaded a hidden service descriptor.
2172 void
2173 control_event_hs_descriptor_uploaded(const char *id_digest,
2174 const char *onion_address)
2176 if (BUG(!id_digest)) {
2177 return;
2180 control_event_hs_descriptor_upload_end("UPLOADED", onion_address,
2181 id_digest, NULL);
2184 /** Send HS_DESC event to inform controller that the query to
2185 * <b>onion_address</b> failed to retrieve hidden service descriptor
2186 * <b>desc_id</b> from directory identified by <b>hsdir_id_digest</b>. If
2187 * NULL, "UNKNOWN" is used. If <b>reason</b> is not NULL, add it to REASON=
2188 * field. */
2189 void
2190 control_event_hsv3_descriptor_failed(const char *onion_address,
2191 const char *desc_id,
2192 const char *hsdir_id_digest,
2193 const char *reason)
2195 char *desc_id_field = NULL;
2197 if (BUG(!onion_address || !desc_id || !reason)) {
2198 return;
2201 /* Because DescriptorID is an optional positional value, we need to add a
2202 * whitespace before in order to not be next to the HsDir value. */
2203 tor_asprintf(&desc_id_field, " %s", desc_id);
2205 event_hs_descriptor_receive_end("FAILED", onion_address, desc_id_field,
2206 REND_NO_AUTH, hsdir_id_digest, reason);
2207 tor_free(desc_id_field);
2210 /** Send HS_DESC_CONTENT event after completion of a successful fetch
2211 * from hs directory. If <b>hsdir_id_digest</b> is NULL, it is replaced
2212 * by "UNKNOWN". If <b>content</b> is NULL, it is replaced by an empty
2213 * string. The <b>onion_address</b> or <b>desc_id</b> set to NULL will
2214 * not trigger the control event. */
2215 void
2216 control_event_hs_descriptor_content(const char *onion_address,
2217 const char *desc_id,
2218 const char *hsdir_id_digest,
2219 const char *content)
2221 static const char *event_name = "HS_DESC_CONTENT";
2222 char *esc_content = NULL;
2224 if (!onion_address || !desc_id) {
2225 log_warn(LD_BUG, "Called with onion_address==%p, desc_id==%p, ",
2226 onion_address, desc_id);
2227 return;
2230 if (content == NULL) {
2231 /* Point it to empty content so it can still be escaped. */
2232 content = "";
2234 write_escaped_data(content, strlen(content), &esc_content);
2236 send_control_event(EVENT_HS_DESC_CONTENT,
2237 "650+%s %s %s %s\r\n%s650 OK\r\n",
2238 event_name,
2239 rend_hsaddress_str_or_unknown(onion_address),
2240 desc_id,
2241 hsdir_id_digest ?
2242 node_describe_longname_by_id(hsdir_id_digest) :
2243 "UNKNOWN",
2244 esc_content);
2245 tor_free(esc_content);
2248 /** Send HS_DESC event to inform controller upload of hidden service
2249 * descriptor identified by <b>id_digest</b> failed. If <b>reason</b>
2250 * is not NULL, add it to REASON= field.
2252 void
2253 control_event_hs_descriptor_upload_failed(const char *id_digest,
2254 const char *onion_address,
2255 const char *reason)
2257 if (BUG(!id_digest)) {
2258 return;
2260 control_event_hs_descriptor_upload_end("FAILED", onion_address,
2261 id_digest, reason);
2264 void
2265 control_events_free_all(void)
2267 smartlist_t *queued_events = NULL;
2269 stats_prev_n_read = stats_prev_n_written = 0;
2271 if (queued_control_events_lock) {
2272 tor_mutex_acquire(queued_control_events_lock);
2273 flush_queued_event_pending = 0;
2274 queued_events = queued_control_events;
2275 queued_control_events = NULL;
2276 tor_mutex_release(queued_control_events_lock);
2278 if (queued_events) {
2279 SMARTLIST_FOREACH(queued_events, queued_event_t *, ev,
2280 queued_event_free(ev));
2281 smartlist_free(queued_events);
2283 if (flush_queued_events_event) {
2284 mainloop_event_free(flush_queued_events_event);
2285 flush_queued_events_event = NULL;
2287 global_event_mask = 0;
2288 disable_log_messages = 0;
2291 #ifdef TOR_UNIT_TESTS
2292 /* For testing: change the value of global_event_mask */
2293 void
2294 control_testing_set_global_event_mask(uint64_t mask)
2296 global_event_mask = mask;
2298 #endif /* defined(TOR_UNIT_TESTS) */