Tor 0.4.9.1-alpha-dev
control_events.c
Go to the documentation of this file.
1/* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2021, The Tor Project, Inc. */
3/* See LICENSE for licensing information */
4
5/**
6 * \file control_events.c
7 * \brief Implement the event-reporting part of the controller API.
8 **/
9
10#define CONTROL_MODULE_PRIVATE
11#define CONTROL_EVENTS_PRIVATE
12#define OCIRC_EVENT_PRIVATE
13
14#include "core/or/or.h"
15#include "app/config/config.h"
18#include "core/or/channeltls.h"
19#include "core/or/circuitlist.h"
21#include "core/or/command.h"
25#include "core/or/reasons.h"
34
39#include "core/or/or_circuit_st.h"
41
44
45static void flush_queued_events_cb(mainloop_event_t *event, void *arg);
46static void control_get_bytes_rw_last_sec(uint64_t *r, uint64_t *w);
47
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)
51
52/** An event mask of all the events that any controller is interested in
53 * receiving. */
54static event_mask_t global_event_mask = 0;
55
56/** True iff we have disabled log messages from being sent to the controller */
57static int disable_log_messages = 0;
58
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)))
63
64/** Macro: true if any event from the bitfield 'e' is interesting. */
65#define ANY_EVENT_IS_INTERESTING(e) \
66 (!! (global_event_mask & (e)))
67
68static void send_control_event_impl(uint16_t event,
69 const char *format, va_list ap)
70 CHECK_PRINTF(2,0);
71static int control_event_status(int type, int severity, const char *format,
72 va_list args)
73 CHECK_PRINTF(3,0);
74
75static void send_control_event(uint16_t event,
76 const char *format, ...)
77 CHECK_PRINTF(2,3);
78
79/** Table mapping event values to their names. Used to implement SETEVENTS
80 * and GETINFO events/names, and to keep they in sync. */
81const 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 },
114};
115
116/** Given a log severity, return the corresponding control event code. */
117static inline int
119{
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;
127 }
128}
129
130/** Helper: clear bandwidth counters of all origin circuits. */
131static void
133{
134 origin_circuit_t *ocirc;
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;
142 }
143 SMARTLIST_FOREACH_END(circ);
144}
145
146/* Helper to emit the BUILDTIMEOUT_SET circuit build time event */
147void
148cbt_control_event_buildtimeout_set(const circuit_build_times_t *cbt,
150{
151 char *args = NULL;
152 double qnt;
153 double timeout_rate = 0.0;
154 double close_rate = 0.0;
155
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:
166 break;
167 }
168
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().
179 *
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;
188 }
189
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);
199
201
202 tor_free(args);
203}
204/** Set <b>global_event_mask*</b> to the bitwise OR of each live control
205 * connection's event_mask field. */
206void
208{
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();
213
215 SMARTLIST_FOREACH(conns, connection_t *, _conn,
216 {
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;
221 }
222 });
223
224 new_mask = global_event_mask;
225
226 /* Handle the aftermath. Set up the log callback to tell us only what
227 * we want to hear...*/
229
230 /* Macro: true if ev was false before and is true now. */
231#define NEWLY_ENABLED(ev) \
232 (! (old_mask & (ev)) && (new_mask & (ev)))
233
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,
238 {
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;
242 }
243 });
244 }
245 if (NEWLY_ENABLED(EVENT_CIRC_BANDWIDTH_USED)) {
247 }
248 if (NEWLY_ENABLED(EVENT_BANDWIDTH_USED)) {
249 uint64_t r, w;
251 }
252 if (any_old_per_sec_events != control_any_per_second_event_enabled()) {
254 }
255
256#undef NEWLY_ENABLED
257}
258
259/** Given a control event code for a message event, return the corresponding
260 * log severity. */
261static inline int
263{
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;
271 }
272}
273
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. */
277void
279{
280 int i;
281 int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
282
283 for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
284 if (EVENT_IS_INTERESTING(i)) {
285 min_log_event = i;
286 break;
287 }
288 }
289 for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
290 if (EVENT_IS_INTERESTING(i)) {
291 max_log_event = i;
292 break;
293 }
294 }
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;
300 }
301 if (min_log_event <= max_log_event)
303 event_to_log_severity(max_log_event),
305 else
308}
309
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.
313 */
314int
316{
317 return EVENT_IS_INTERESTING(event);
318}
319
320/** Return true if any event that needs to fire once a second is enabled. */
321int
323{
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)
330 );
331}
332
333/* The value of 'get_bytes_read()' the previous time that
334 * control_get_bytes_rw_last_sec() as called. */
335static 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. */
338static uint64_t stats_prev_n_written = 0;
339
340/**
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.
343 *
344 * Call this only from the main thread.
345 */
346static void
348 uint64_t *n_written)
349{
350 const uint64_t stats_n_bytes_read = get_bytes_read();
351 const uint64_t stats_n_bytes_written = get_bytes_written();
352
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;
357}
358
359/**
360 * Run all the controller events (if any) that are scheduled to trigger once
361 * per second.
362 */
363void
365{
367 return;
368
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);
372
377}
378
379/** Represents an event that's queued to be sent to one or more
380 * controllers. */
381typedef struct queued_event_t {
382 uint16_t event;
383 char *msg;
385
386/** Pointer to int. If this is greater than 0, we don't allow new events to be
387 * queued. */
389
390/** Holds a smartlist of queued_event_t objects that may need to be sent
391 * to one or more controllers */
393
394/** True if the flush_queued_events_event is pending. */
396
397/** Lock to protect the above fields. */
399
400/** An event that should fire in order to flush the contents of
401 * queued_control_events. */
403
404void
405control_initialize_event_queue(void)
406{
407 if (queued_control_events == NULL) {
409 }
410
411 if (flush_queued_events_event == NULL) {
412 struct event_base *b = tor_libevent_get_base();
413 if (b) {
417 }
418 }
419
420 if (queued_control_events_lock == NULL) {
423 }
424}
425
426static int *
427get_block_event_queue(void)
428{
430 if (PREDICT_UNLIKELY(val == NULL)) {
431 val = tor_malloc_zero(sizeof(int));
433 }
434 return val;
435}
436
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.
439 *
440 * This function takes ownership of <b>msg</b>, and may free it.
441 *
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.
447 */
448MOCK_IMPL(STATIC void,
449queue_control_event_string,(uint16_t event, char *msg))
450{
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;
456 }
457
458 int *block_event_queue = get_block_event_queue();
459 if (*block_event_queue) {
460 tor_free(msg);
461 return;
462 }
463
464 queued_event_t *ev = tor_malloc(sizeof(*ev));
465 ev->event = event;
466 ev->msg = msg;
467
468 /* No queueing an event while queueing an event */
469 ++*block_event_queue;
470
474
475 int activate_event = 0;
477 activate_event = 1;
479 }
480
482
483 --*block_event_queue;
484
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.
488 */
489 if (activate_event) {
492 }
493}
494
495#define queued_event_free(ev) \
496 FREE_AND_NULL(queued_event_t, queued_event_free_, (ev))
497
498/** Release all storage held by <b>ev</b>. */
499static void
501{
502 if (ev == NULL)
503 return;
504
505 tor_free(ev->msg);
506 tor_free(ev);
507}
508
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. */
513static void
515{
516 /* Make sure that we get all the pending log events, if there are any. */
518
519 if (PREDICT_UNLIKELY(queued_control_events == NULL)) {
520 return;
521 }
522 smartlist_t *all_conns = get_connection_array();
523 smartlist_t *controllers = smartlist_new();
524 smartlist_t *queued_events;
525
526 int *block_event_queue = get_block_event_queue();
527 ++*block_event_queue;
528
530 /* No queueing an event while flushing events. */
532 queued_events = queued_control_events;
535
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);
542
543 smartlist_add(controllers, control_conn);
544 }
545 } SMARTLIST_FOREACH_END(conn);
546
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);
551 control_conn) {
552 if (control_conn->event_mask & bit) {
553 connection_buf_add(ev->msg, msg_len, TO_CONN(control_conn));
554 }
555 } SMARTLIST_FOREACH_END(control_conn);
556
557 queued_event_free(ev);
558 } SMARTLIST_FOREACH_END(ev);
559
560 if (force) {
562 control_conn) {
563 connection_flush(TO_CONN(control_conn));
564 } SMARTLIST_FOREACH_END(control_conn);
565 }
566
567 smartlist_free(queued_events);
568 smartlist_free(controllers);
569
570 --*block_event_queue;
571}
572
573/** Libevent callback: Flushes pending events to controllers that are
574 * interested in them. */
575static void
577{
578 (void) event;
579 (void) arg;
581}
582
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>.
585 *
586 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
587 * respect to the EXTENDED_EVENTS feature. */
588MOCK_IMPL(STATIC void,
589send_control_event_string,(uint16_t event,
590 const char *msg))
591{
592 tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
593 queue_control_event_string(event, tor_strdup(msg));
594}
595
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. */
600static void
602 const char *format, va_list ap)
603{
604 char *buf = NULL;
605 int len;
606
607 len = tor_vasprintf(&buf, format, ap);
608 if (len < 0) {
609 log_warn(LD_BUG, "Unable to format event for controller.");
610 return;
611 }
612
613 queue_control_event_string(event, buf);
614}
615
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. */
619static void
620send_control_event(uint16_t event,
621 const char *format, ...)
622{
623 va_list ap;
624 va_start(ap, format);
625 send_control_event_impl(event, format, ap);
626 va_end(ap);
627}
628
629/** Something major has happened to circuit <b>circ</b>: tell any
630 * interested control connections. */
631int
633 int reason_code)
634{
635 const char *status;
636 char reasons[64] = "";
637
638 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
639 return 0;
640 tor_assert(circ);
641
642 switch (tp)
643 {
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);
652 return 0;
653 }
654
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;
661 }
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);
668 }
669 }
670
671 {
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);
681 }
682
683 return 0;
684}
685
686/** Something minor has happened to circuit <b>circ</b>: tell any
687 * interested control connections. */
688static int
691 int purpose, const struct timeval *tv)
692{
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);
698
699 switch (e)
700 {
701 case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
702 event_desc = "PURPOSE_CHANGED";
703
704 {
705 /* event_tail can currently be up to 68 chars long */
706 const char *hs_state_str =
708 tor_snprintf(event_tail, sizeof(event_tail),
709 " OLD_PURPOSE=%s%s%s",
711 (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
712 (hs_state_str != NULL) ? hs_state_str : "");
713 }
714
715 break;
716 case CIRC_MINOR_EVENT_CANNIBALIZED:
717 event_desc = "CANNIBALIZED";
718
719 {
720 /* event_tail can currently be up to 130 chars long */
721 const char *hs_state_str =
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);
726
727 tor_snprintf(event_tail, sizeof(event_tail),
728 " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
730 (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
731 (hs_state_str != NULL) ? hs_state_str : "",
732 tbuf);
733 }
734
735 break;
736 default:
737 log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
739 return 0;
740 }
741
742 {
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);
752 }
753
754 return 0;
755}
756
757/**
758 * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
759 * interested controllers.
760 */
761int
763 int old_purpose)
764{
766 CIRC_MINOR_EVENT_PURPOSE_CHANGED,
767 old_purpose,
768 NULL);
769}
770
771/**
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.
774 */
775int
777 int old_purpose,
778 const struct timeval *old_tv_created)
779{
781 CIRC_MINOR_EVENT_CANNIBALIZED,
782 old_purpose,
783 old_tv_created);
784}
785
786/** Something has happened to the stream associated with AP connection
787 * <b>conn</b>: tell any interested control connections. */
788int
790 int reason_code)
791{
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 = "";
800
801 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
802 return 0;
803
804 if (tp == STREAM_EVENT_CLOSED &&
806 return 0;
807
808 write_stream_target_to_buf(conn, buf, sizeof(buf));
809
810 reason_buf[0] = '\0';
811 switch (tp)
812 {
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;
830 }
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;
839 }
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) {
850 strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
851 break;
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;
860 }
861 }
862
863 if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
864 /*
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.
868 */
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 {
873 /*
874 * else leave it blank so control on AF_UNIX doesn't need to make
875 * something up.
876 */
877 addrport_buf[0] = '\0';
878 }
879 } else {
880 addrport_buf[0] = '\0';
881 }
882
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";
897 }
898
900 if (circ && CIRCUIT_IS_ORIGIN(circ))
901 origin_circ = TO_ORIGIN_CIRCUIT(circ);
902
903 {
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);
914 }
915
916 /* XXX need to specify its intended exit, etc? */
917
918 return 0;
919}
920
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.
925 */
926int
928 int reason)
929{
930 int ncircs = 0;
931 const char *status;
932 char name[128];
933 char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
934
935 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
936 return 0;
937
938 switch (tp)
939 {
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;
948 }
949 if (conn->chan) {
950 ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
951 } else {
952 ncircs = 0;
953 }
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);
957 }
958
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=" : "",
965 ncircs_buf,
966 (conn->base_.global_identifier));
967
968 return 0;
969}
970
971/**
972 * Print out STREAM_BW event for a single conn
973 */
974int
976{
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;
982
983 tor_gettimeofday(&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);
991
992 edge_conn->n_written = edge_conn->n_read = 0;
993 }
994
995 return 0;
996}
997
998/** A second or more has elapsed: tell any interested control
999 * connections how much bandwidth streams have used. */
1000int
1002{
1003 if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
1005 edge_connection_t *edge_conn;
1006 struct timeval now;
1007 char tbuf[ISO_TIME_USEC_LEN+1];
1008
1010 {
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;
1016
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);
1025
1026 edge_conn->n_written = edge_conn->n_read = 0;
1027 }
1028 SMARTLIST_FOREACH_END(conn);
1029 }
1030
1031 return 0;
1032}
1033
1034/** A second or more has elapsed: tell any interested control connections
1035 * how much bandwidth origin circuits have used. */
1036int
1038{
1039 if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
1040 return 0;
1041
1043 if (!CIRCUIT_IS_ORIGIN(circ))
1044 continue;
1045
1047 }
1048 SMARTLIST_FOREACH_END(circ);
1049
1050 return 0;
1051}
1052
1053/**
1054 * Emit a CIRC_BW event line for a specific circuit.
1055 *
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.
1058 *
1059 * Therefore, it may be called at any frequency.
1060 */
1061int
1063{
1064 struct timeval now;
1065 char tbuf[ISO_TIME_USEC_LEN+1];
1066
1067 tor_assert(ocirc);
1068
1069 if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
1070 return 0;
1071
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.
1075 *
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;
1080
1081 tor_gettimeofday(&now);
1082 format_iso_time_nospace_usec(tbuf, &now);
1083
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 : "");
1098
1099 ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
1102
1103 if (ccontrol_buf)
1104 tor_free(ccontrol_buf);
1105
1106 return 0;
1107}
1108
1109/** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
1110 * bandwidth counters. */
1111int
1113{
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;
1132 }
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;
1142}
1143
1144/** A second or more has elapsed: tell any interested control
1145 * connections how much bandwidth connections have used. */
1146int
1148{
1149 if (get_options()->TestingEnableConnBwEvent &&
1150 EVENT_IS_INTERESTING(EVENT_CONN_BW)) {
1153 }
1154 return 0;
1155}
1156
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. */
1161void
1162sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
1163{
1164 memset(cell_stats, 0, sizeof(cell_stats_t));
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;
1178 }
1179 } SMARTLIST_FOREACH_END(ent);
1181}
1182
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>. */
1192void
1193append_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)
1196{
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,
1203 (number_to_include[i]));
1204 }
1205 }
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);
1211 }
1212 smartlist_free(key_value_strings);
1213}
1214
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>. */
1217void
1218format_cell_stats(char **event_string, circuit_t *circ,
1219 cell_stats_t *cell_stats)
1220{
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);
1241 }
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);
1256 }
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);
1260}
1261
1262/** A second or more has elapsed: tell any interested control connection
1263 * how many cells have been processed for a given circuit. */
1264int
1266{
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));
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);
1281 }
1282 SMARTLIST_FOREACH_END(circ);
1283 tor_free(cell_stats);
1284 return 0;
1285}
1286
1287/* about 5 minutes worth. */
1288#define N_BW_EVENTS_TO_CACHE 300
1289/* Index into cached_bw_events to next write. */
1290static int next_measurement_idx = 0;
1291/* number of entries set in n_measurements */
1292static int n_measurements = 0;
1293static struct cached_bw_event_t {
1294 uint32_t n_read;
1295 uint32_t n_written;
1296} cached_bw_events[N_BW_EVENTS_TO_CACHE];
1297
1298/** A second or more has elapsed: tell any interested control
1299 * connections how much bandwidth we used. */
1300int
1301control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
1302{
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;
1309
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);
1315 }
1316
1317 return 0;
1318}
1319
1320char *
1321get_bw_samples(void)
1322{
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);
1327
1328 smartlist_t *elements = smartlist_new();
1329
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];
1333
1334 smartlist_add_asprintf(elements, "%u,%u",
1335 (unsigned)bwe->n_read,
1336 (unsigned)bwe->n_written);
1337
1338 idx = (idx + 1) % N_BW_EVENTS_TO_CACHE;
1339 }
1340
1341 char *result = smartlist_join_strings(elements, " ", 0, NULL);
1342
1343 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
1344 smartlist_free(elements);
1345
1346 return result;
1347}
1348
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. */
1352void
1354{
1356}
1357
1358/** We're done sending a log message to the controllers: re-enable controller
1359 * logging. Used by CONN_LOG_PROTECT. */
1360void
1362{
1363 if (--disable_log_messages < 0)
1364 tor_assert(0);
1365}
1366
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 */
1369void
1371{
1372 char *cp;
1373 for (cp = msg; *cp; ++cp) {
1374 if (*cp == '\r' || *cp == '\n') {
1375 *cp = ' ';
1376 }
1377 }
1378 if (cp == msg)
1379 return;
1380 /* Remove trailing spaces */
1381 for (--cp; *cp == ' '; --cp) {
1382 *cp = '\0';
1383 if (cp == msg)
1384 break;
1385 }
1386}
1387
1388/** We got a log message: tell any interested control connections. */
1389void
1390control_event_logmsg(int severity, log_domain_mask_t domain, const char *msg)
1391{
1392 int event;
1393
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;
1398
1400 return;
1401
1402 if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
1403 severity <= LOG_NOTICE) {
1404 char *esc = esc_for_log(msg);
1406 control_event_general_status(severity, "BUG REASON=%s", esc);
1408 tor_free(esc);
1409 }
1410
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);
1418 }
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;
1426 }
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 */
1432 }
1434 tor_free(b);
1435 }
1436}
1437
1438/**
1439 * Logging callback: called when there is a queued pending log callback.
1440 */
1441void
1443{
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.
1448 **/
1449 return;
1450 }
1453}
1454
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.
1458 */
1459int
1461{
1462 char *msg;
1463
1464 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
1465 return 0;
1466
1467 {
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);
1473 smartlist_add(names, b);
1474 });
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);
1482 }
1483 return 0;
1484}
1485
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.
1490 */
1491int
1492control_event_address_mapped(const char *from, const char *to,
1493 time_t expires, const char *error,
1494 const int cached, uint64_t stream_id)
1495{
1496 char *stream_id_str = NULL;
1497 if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
1498 return 0;
1499
1500 if (stream_id) {
1501 tor_asprintf(&stream_id_str, " STREAMID=%"PRIu64"", stream_id);
1502 }
1503
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: "");
1522 }
1523
1524 tor_free(stream_id_str);
1525
1526 return 0;
1527}
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. */
1531int
1533{
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");
1541 }
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");
1550 }
1551 /* else was already dead, no-op */
1552 }
1553
1554 return 0;
1555}
1556
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. */
1561static int
1563 uint16_t event,
1564 const char *event_string)
1565{
1566 smartlist_t *strs;
1567 char *s, *esc = NULL;
1568 if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
1569 return 0;
1570
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,
1576 {
1578 if (!s) continue;
1579 smartlist_add(strs, s);
1580 });
1581
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);
1589 "650 OK\r\n");
1590
1591 tor_free(esc);
1592 return 0;
1593}
1594
1595/** Called when the routerstatus_ts <b>statuses</b> have changed: sends
1596 * an NS event to any controller that cares. */
1597int
1599{
1600 return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
1601}
1602
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. */
1605int
1607{
1608 if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
1609 return 0;
1611 consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
1612}
1613
1614/** Called when we compute a new circuitbuildtimeout */
1615int
1617 const char *args)
1618{
1619 const char *type_string = NULL;
1620
1621 if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
1622 return 0;
1623
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;
1643 }
1644
1645 send_control_event(EVENT_BUILDTIMEOUT_SET,
1646 "650 BUILDTIMEOUT_SET %s %s\r\n",
1647 type_string, args);
1648
1649 return 0;
1650}
1651
1652/** Called when a signal has been processed from signal_callback */
1653int
1654control_event_signal(uintptr_t signal_num)
1655{
1656 const char *signal_string = NULL;
1657
1658 if (!control_event_is_interesting(EVENT_GOT_SIGNAL))
1659 return 0;
1660
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;
1665 }
1666 }
1667
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;
1672 }
1673
1674 send_control_event(EVENT_GOT_SIGNAL, "650 SIGNAL %s\r\n",
1675 signal_string);
1676 return 0;
1677}
1678
1679/** Called when a single local_routerstatus_t has changed: Sends an NS event
1680 * to any controller that cares. */
1681int
1683{
1684 smartlist_t *statuses;
1685 int r;
1686
1687 if (!EVENT_IS_INTERESTING(EVENT_NS))
1688 return 0;
1689
1690 statuses = smartlist_new();
1691 smartlist_add(statuses, (void*)rs);
1693 smartlist_free(statuses);
1694 return r;
1695}
1696
1697/** Our own router descriptor has changed; tell any controllers that care.
1698 */
1699int
1701{
1702 send_control_event(EVENT_DESCCHANGED, "650 DESCCHANGED\r\n");
1703 return 0;
1704}
1705
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>. */
1710static int
1711control_event_status(int type, int severity, const char *format, va_list args)
1712{
1713 char *user_buf = NULL;
1714 char format_buf[160];
1715 const char *status, *sev;
1716
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;
1730 }
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;
1744 }
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;
1749 }
1750 if (tor_vasprintf(&user_buf, format, args)<0) {
1751 log_warn(LD_BUG, "Failed to create user buffer.");
1752 return -1;
1753 }
1754
1755 send_control_event(type, "%s %s\r\n", format_buf, user_buf);
1756 tor_free(user_buf);
1757 return 0;
1758}
1759
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; \
1767 \
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) */
1773
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>. */
1776int
1777control_event_general_status(int severity, const char *format, ...)
1778{
1779 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, severity);
1780 return r;
1781}
1782
1783/** Format and send an EVENT_STATUS_GENERAL LOG_ERR event, and flush it to the
1784 * controller(s) immediately. */
1785int
1786control_event_general_error(const char *format, ...)
1787{
1788 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, LOG_ERR);
1789 /* Force a flush, since we may be about to die horribly */
1791 return r;
1792}
1793
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>. */
1796int
1797control_event_client_status(int severity, const char *format, ...)
1798{
1799 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, severity);
1800 return r;
1801}
1802
1803/** Format and send an EVENT_STATUS_CLIENT LOG_ERR event, and flush it to the
1804 * controller(s) immediately. */
1805int
1806control_event_client_error(const char *format, ...)
1807{
1808 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, LOG_ERR);
1809 /* Force a flush, since we may be about to die horribly */
1811 return r;
1812}
1813
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>. */
1816int
1817control_event_server_status(int severity, const char *format, ...)
1818{
1819 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, severity);
1820 return r;
1821}
1822
1823/** Format and send an EVENT_STATUS_SERVER LOG_ERR event, and flush it to the
1824 * controller(s) immediately. */
1825int
1826control_event_server_error(const char *format, ...)
1827{
1828 CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, LOG_ERR);
1829 /* Force a flush, since we may be about to die horribly */
1831 return r;
1832}
1833
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. */
1837int
1838control_event_guard(const char *nickname, const char *digest,
1839 const char *status)
1840{
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;
1845
1846 {
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);
1853 }
1854 send_control_event(EVENT_GUARD,
1855 "650 GUARD ENTRY %s %s\r\n", buf, status);
1856 }
1857 return 0;
1858}
1859
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".
1864 */
1865void
1867{
1868 char *result;
1869 smartlist_t *lines;
1870 if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) || !changes) {
1871 return;
1872 }
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);
1879 }
1880 }
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);
1887}
1888
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. */
1892void
1893control_event_clients_seen(const char *controller_str)
1894{
1895 send_control_event(EVENT_CLIENTS_SEEN,
1896 "650 CLIENTS_SEEN %s\r\n", controller_str);
1897}
1898
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
1904 */
1905void
1906control_event_transport_launched(const char *mode, const char *transport_name,
1907 tor_addr_t *addr, uint16_t port)
1908{
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);
1912}
1913
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. */
1916void
1917control_event_pt_log(const char *log)
1918{
1919 send_control_event(EVENT_PT_LOG,
1920 "650 PT_LOG %s\r\n",
1921 log);
1922}
1923
1924/** A pluggable transport has emitted a STATUS message found in
1925 * <b>status</b>. */
1926void
1927control_event_pt_status(const char *status)
1928{
1929 send_control_event(EVENT_PT_STATUS,
1930 "650 PT_STATUS %s\r\n",
1931 status);
1932}
1933
1934/** Convert rendezvous auth type to string for HS_DESC control events
1935 */
1936const char *
1938{
1939 const char *str;
1940
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";
1950 }
1951
1952 return str;
1953}
1954
1955/** Return either the onion address if the given pointer is a non empty
1956 * string else the unknown string. */
1957static const char *
1958rend_hsaddress_str_or_unknown(const char *onion_address)
1959{
1960 static const char *str_unknown = "UNKNOWN";
1961 const char *str_ret = str_unknown;
1962
1963 /* No valid pointer, unknown it is. */
1964 if (!onion_address) {
1965 goto end;
1966 }
1967 /* Empty onion address thus we don't know, unknown it is. */
1968 if (onion_address[0] == '\0') {
1969 goto end;
1970 }
1971 /* All checks are good so return the given onion address. */
1972 str_ret = onion_address;
1973
1974 end:
1975 return str_ret;
1976}
1977
1978/** send HS_DESC requested event.
1979 *
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.
1984 */
1985void
1987 rend_auth_type_t auth_type,
1988 const char *id_digest,
1989 const char *desc_id,
1990 const char *hsdir_index)
1991{
1992 char *hsdir_index_field = NULL;
1993
1994 if (BUG(!id_digest || !desc_id)) {
1995 return;
1996 }
1997
1998 if (hsdir_index) {
1999 tor_asprintf(&hsdir_index_field, " HSDIR_INDEX=%s", hsdir_index);
2000 }
2001
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),
2007 desc_id,
2008 hsdir_index_field ? hsdir_index_field : "");
2009 tor_free(hsdir_index_field);
2010}
2011
2012/** send HS_DESC CREATED event when a local service generates a descriptor.
2013 *
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.
2018 */
2019void
2020control_event_hs_descriptor_created(const char *onion_address,
2021 const char *desc_id,
2022 int replica)
2023{
2024 char *replica_field = NULL;
2025
2026 if (BUG(!onion_address || !desc_id)) {
2027 return;
2028 }
2029
2030 if (replica >= 0) {
2031 tor_asprintf(&replica_field, " REPLICA=%d", replica);
2032 }
2033
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);
2039}
2040
2041/** send HS_DESC upload event.
2042 *
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.
2046 */
2047void
2048control_event_hs_descriptor_upload(const char *onion_address,
2049 const char *id_digest,
2050 const char *desc_id,
2051 const char *hsdir_index)
2052{
2053 char *hsdir_index_field = NULL;
2054
2055 if (BUG(!onion_address || !id_digest || !desc_id)) {
2056 return;
2057 }
2058
2059 if (hsdir_index) {
2060 tor_asprintf(&hsdir_index_field, " HSDIR_INDEX=%s", hsdir_index);
2061 }
2062
2063 send_control_event(EVENT_HS_DESC,
2064 "650 HS_DESC UPLOAD %s UNKNOWN %s %s%s\r\n",
2065 onion_address,
2067 desc_id,
2068 hsdir_index_field ? hsdir_index_field : "");
2069 tor_free(hsdir_index_field);
2070}
2071
2072/** send HS_DESC event after got response from hs directory.
2073 *
2074 * NOTE: this is an internal function used by following functions:
2075 * control_event_hsv3_descriptor_failed
2076 *
2077 * So do not call this function directly.
2078 */
2079static void
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)
2086{
2087 char *reason_field = NULL;
2088
2089 if (BUG(!action || !onion_address)) {
2090 return;
2091 }
2092
2093 if (reason) {
2094 tor_asprintf(&reason_field, " REASON=%s", reason);
2095 }
2096
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 : "");
2107
2108 tor_free(reason_field);
2109}
2110
2111/** send HS_DESC event after got response from hs directory.
2112 *
2113 * NOTE: this is an internal function used by following functions:
2114 * control_event_hs_descriptor_uploaded
2115 * control_event_hs_descriptor_upload_failed
2116 *
2117 * So do not call this function directly.
2118 */
2119void
2121 const char *onion_address,
2122 const char *id_digest,
2123 const char *reason)
2124{
2125 char *reason_field = NULL;
2126
2127 if (BUG(!action || !id_digest)) {
2128 return;
2129 }
2130
2131 if (reason) {
2132 tor_asprintf(&reason_field, " REASON=%s", reason);
2133 }
2134
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),
2140 reason_field ? reason_field : "");
2141
2142 tor_free(reason_field);
2143}
2144
2145/* Send HS_DESC RECEIVED event
2146 *
2147 * Called when we successfully received a hidden service descriptor. */
2148void
2149control_event_hsv3_descriptor_received(const char *onion_address,
2150 const char *desc_id,
2151 const char *hsdir_id_digest)
2152{
2153 char *desc_id_field = NULL;
2154
2155 if (BUG(!onion_address || !desc_id || !hsdir_id_digest)) {
2156 return;
2157 }
2158
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);
2162
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);
2166}
2167
2168/** send HS_DESC UPLOADED event
2169 *
2170 * called when we successfully uploaded a hidden service descriptor.
2171 */
2172void
2174 const char *onion_address)
2175{
2176 if (BUG(!id_digest)) {
2177 return;
2178 }
2179
2180 control_event_hs_descriptor_upload_end("UPLOADED", onion_address,
2181 id_digest, NULL);
2182}
2183
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. */
2189void
2191 const char *desc_id,
2192 const char *hsdir_id_digest,
2193 const char *reason)
2194{
2195 char *desc_id_field = NULL;
2196
2197 if (BUG(!onion_address || !desc_id || !reason)) {
2198 return;
2199 }
2200
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);
2204
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);
2208}
2209
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. */
2215void
2216control_event_hs_descriptor_content(const char *onion_address,
2217 const char *desc_id,
2218 const char *hsdir_id_digest,
2219 const char *content)
2220{
2221 static const char *event_name = "HS_DESC_CONTENT";
2222 char *esc_content = NULL;
2223
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;
2228 }
2229
2230 if (content == NULL) {
2231 /* Point it to empty content so it can still be escaped. */
2232 content = "";
2233 }
2234 write_escaped_data(content, strlen(content), &esc_content);
2235
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);
2246}
2247
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.
2251 */
2252void
2254 const char *onion_address,
2255 const char *reason)
2256{
2257 if (BUG(!id_digest)) {
2258 return;
2259 }
2260 control_event_hs_descriptor_upload_end("FAILED", onion_address,
2261 id_digest, reason);
2262}
2263
2264void
2265control_events_free_all(void)
2266{
2267 smartlist_t *queued_events = NULL;
2268
2269 stats_prev_n_read = stats_prev_n_written = 0;
2270
2274 queued_events = queued_control_events;
2275 queued_control_events = NULL;
2277 }
2278 if (queued_events) {
2279 SMARTLIST_FOREACH(queued_events, queued_event_t *, ev,
2280 queued_event_free(ev));
2281 smartlist_free(queued_events);
2282 }
2284 mainloop_event_free(flush_queued_events_event);
2286 }
2289}
2290
2291#ifdef TOR_UNIT_TESTS
2292/* For testing: change the value of global_event_mask */
2293void
2294control_testing_set_global_event_mask(uint64_t mask)
2295{
2296 global_event_mask = mask;
2297}
2298#endif /* defined(TOR_UNIT_TESTS) */
#define fmt_addr(a)
Definition: address.h:239
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:478
Header file for channeltls.c.
const char * circuit_purpose_to_controller_hs_state_string(uint8_t purpose)
Definition: circuitlist.c:867
circuit_t * circuit_get_by_edge_conn(edge_connection_t *conn)
Definition: circuitlist.c:1606
origin_circuit_t * TO_ORIGIN_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:185
const char * circuit_purpose_to_controller_string(uint8_t purpose)
Definition: circuitlist.c:801
int circuit_count_pending_on_channel(channel_t *chan)
Definition: circuitlist.c:628
or_circuit_t * TO_OR_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:173
void circuit_clear_testing_cell_stats(circuit_t *circ)
Definition: circuitlist.c:1146
smartlist_t * circuit_get_global_list(void)
Definition: circuitlist.c:713
Header file for circuitlist.c.
#define CIRCUIT_IS_ORIGIN(c)
Definition: circuitlist.h:154
double circuit_build_times_quantile_cutoff(void)
Definition: circuitstats.c:267
Header file for circuitstats.c.
const char * cell_command_to_string(uint8_t command)
Definition: command.c:89
Header file for command.c.
struct event_base * tor_libevent_get_base(void)
mainloop_event_t * mainloop_event_new(void(*cb)(mainloop_event_t *, void *), void *userdata)
void mainloop_event_activate(mainloop_event_t *event)
Header for compat_libevent.c.
tor_mutex_t * tor_mutex_new(void)
Definition: compat_mutex.c:17
void tor_mutex_release(tor_mutex_t *m)
void tor_mutex_acquire(tor_mutex_t *m)
void * tor_threadlocal_get(tor_threadlocal_t *threadlocal)
void tor_threadlocal_set(tor_threadlocal_t *threadlocal, void *value)
int tor_threadlocal_init(tor_threadlocal_t *threadlocal)
int in_main_thread(void)
const char * name
Definition: config.c:2462
const or_options_t * get_options(void)
Definition: config.c:944
Header file for config.c.
Header for confline.c.
char * congestion_control_get_control_port_fields(const origin_circuit_t *circ)
Public APIs for congestion control.
int connection_flush(connection_t *conn)
Definition: connection.c:4701
Header file for connection.c.
#define CONN_TYPE_OR
Definition: connection.h:44
#define CONN_TYPE_CONTROL
Definition: connection.h:60
#define CONN_TYPE_AP
Definition: connection.h:51
#define CONN_TYPE_DIR
Definition: connection.h:55
#define CONN_TYPE_EXIT
Definition: connection.h:46
edge_connection_t * TO_EDGE_CONN(connection_t *c)
Header file for connection_edge.c.
int connection_or_get_num_circuits(or_connection_t *conn)
Header file for connection_or.c.
control_connection_t * TO_CONTROL_CONN(connection_t *c)
Definition: control.c:71
Header file for control.c.
#define CONTROL_CONN_STATE_OPEN
Definition: control.h:20
Controller connection structure.
void control_event_pt_status(const char *status)
int control_event_my_descriptor_changed(void)
const struct control_event_t control_event_table[]
static tor_threadlocal_t block_event_queue_flag
int control_event_server_error(const char *format,...)
int control_event_stream_bandwidth(edge_connection_t *edge_conn)
const char * rend_auth_type_to_string(rend_auth_type_t auth_type)
void control_event_pt_log(const char *log)
static mainloop_event_t * flush_queued_events_event
static void flush_queued_events_cb(mainloop_event_t *event, void *arg)
int control_event_general_status(int severity, const char *format,...)
#define EVENT_IS_INTERESTING(e)
void format_cell_stats(char **event_string, circuit_t *circ, cell_stats_t *cell_stats)
STATIC void send_control_event_string(uint16_t event, const char *msg)
void control_event_clients_seen(const char *controller_str)
static int control_event_networkstatus_changed_helper(smartlist_t *statuses, uint16_t event, const char *event_string)
int control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
static int event_to_log_severity(int event)
static void queued_events_flush_all(int force)
void control_event_hs_descriptor_content(const char *onion_address, const char *desc_id, const char *hsdir_id_digest, const char *content)
int control_event_circuit_purpose_changed(origin_circuit_t *circ, int old_purpose)
int control_event_conn_bandwidth(connection_t *conn)
int control_event_circuit_cell_stats(void)
static int flush_queued_event_pending
int control_event_buildtimeout_set(buildtimeout_set_event_t type, const char *args)
int control_event_signal(uintptr_t signal_num)
void control_event_hs_descriptor_requested(const char *onion_address, rend_auth_type_t auth_type, const char *id_digest, const char *desc_id, const char *hsdir_index)
void disable_control_logging(void)
void control_event_hs_descriptor_upload_failed(const char *id_digest, const char *onion_address, const char *reason)
void sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
int control_event_stream_bandwidth_used(void)
static event_mask_t global_event_mask
int control_event_guard(const char *nickname, const char *digest, const char *status)
STATIC void queue_control_event_string(uint16_t event, char *msg)
static void clear_circ_bw_fields(void)
static smartlist_t * queued_control_events
int control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp, int reason_code)
static int disable_log_messages
void control_event_hs_descriptor_upload(const char *onion_address, const char *id_digest, const char *desc_id, const char *hsdir_index)
static void send_control_event_impl(uint16_t event, const char *format, va_list ap)
void control_event_hs_descriptor_uploaded(const char *id_digest, const char *onion_address)
void control_event_hs_descriptor_upload_end(const char *action, const char *onion_address, const char *id_digest, const char *reason)
int control_event_general_error(const char *format,...)
int control_event_networkstatus_changed(smartlist_t *statuses)
int control_event_server_status(int severity, const char *format,...)
static void queued_event_free_(queued_event_t *ev)
int control_event_circ_bandwidth_used_for_circ(origin_circuit_t *ocirc)
int control_event_is_interesting(int event)
int control_event_client_error(const char *format,...)
int control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp, int reason)
int control_event_circ_bandwidth_used(void)
void enable_control_logging(void)
void control_event_hsv3_descriptor_failed(const char *onion_address, const char *desc_id, const char *hsdir_id_digest, const char *reason)
static tor_mutex_t * queued_control_events_lock
int control_event_network_liveness_update(int liveness)
#define STATE_IS_OPEN(s)
static int control_event_status(int type, int severity, const char *format, va_list args)
void control_event_transport_launched(const char *mode, const char *transport_name, tor_addr_t *addr, uint16_t port)
void append_cell_stats_by_command(smartlist_t *event_parts, const char *key, const uint64_t *include_if_non_zero, const uint64_t *number_to_include)
int control_event_conn_bandwidth_used(void)
void control_adjust_event_log_severity(void)
int control_event_client_status(int severity, const char *format,...)
int control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp, int reason_code)
int control_event_networkstatus_changed_single(const routerstatus_t *rs)
int control_event_circuit_cannibalized(origin_circuit_t *circ, int old_purpose, const struct timeval *old_tv_created)
void control_logmsg_strip_newlines(char *msg)
static int control_event_circuit_status_minor(origin_circuit_t *circ, circuit_status_minor_event_t e, int purpose, const struct timeval *tv)
static void send_control_event(uint16_t event, const char *format,...)
int control_event_descriptors_changed(smartlist_t *routers)
int control_event_newconsensus(const networkstatus_t *consensus)
static int log_severity_to_event(int severity)
int control_event_address_mapped(const char *from, const char *to, time_t expires, const char *error, const int cached, uint64_t stream_id)
static void event_hs_descriptor_receive_end(const char *action, const char *onion_address, const char *desc_id, rend_auth_type_t auth_type, const char *hsdir_id_digest, const char *reason)
static const char * rend_hsaddress_str_or_unknown(const char *onion_address)
void control_event_hs_descriptor_created(const char *onion_address, const char *desc_id, int replica)
void control_event_logmsg_pending(void)
void control_update_global_event_mask(void)
void control_per_second_events(void)
void control_event_logmsg(int severity, log_domain_mask_t domain, const char *msg)
static void control_get_bytes_rw_last_sec(uint64_t *r, uint64_t *w)
void control_event_conf_changed(const config_line_t *changes)
int control_any_per_second_event_enabled(void)
#define ANY_EVENT_IS_INTERESTING(e)
Header file for control_events.c.
#define REMAP_STREAM_SOURCE_EXIT
stream_status_event_t
circuit_status_minor_event_t
#define REMAP_STREAM_SOURCE_CACHE
buildtimeout_set_event_t
char * entry_connection_describe_status_for_controller(const entry_connection_t *conn)
Definition: control_fmt.c:173
char * circuit_describe_status_for_controller(origin_circuit_t *circ)
Definition: control_fmt.c:73
const char * node_describe_longname_by_id(const char *id_digest)
Definition: control_fmt.c:274
void orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
Definition: control_fmt.c:54
int write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
Definition: control_fmt.c:32
Header file for control_fmt.c.
size_t write_escaped_data(const char *data, size_t len, char **out)
Definition: control_proto.c:71
Header file for control_proto.c.
#define HEX_DIGEST_LEN
Definition: crypto_digest.h:35
void router_get_verbose_nickname(char *buf, const routerinfo_t *router)
Definition: describe.c:256
Header file for describe.c.
#define DIGEST_LEN
Definition: digest_sizes.h:20
Header file for directory.c.
#define DIR_PURPOSE_IS_UPLOAD(p)
Definition: directory.h:77
Entry connection structure.
#define ENTRY_TO_EDGE_CONN(c)
char * esc_for_log(const char *s)
Definition: escape.c:30
void change_callback_log_severity(int loglevelMin, int loglevelMax, log_callback cb)
Definition: log.c:1003
void flush_pending_log_callbacks(void)
Definition: log.c:1022
#define LOG_DEBUG
Definition: log.h:42
#define LOG_ERR
Definition: log.h:56
#define LD_BUG
Definition: log.h:86
#define LOG_NOTICE
Definition: log.h:50
#define LD_CONTROL
Definition: log.h:80
#define LOG_WARN
Definition: log.h:53
#define LOG_INFO
Definition: log.h:45
uint64_t log_domain_mask_t
Definition: logging_types.h:21
uint64_t get_bytes_read(void)
Definition: mainloop.c:455
static uint64_t stats_n_bytes_written
Definition: mainloop.c:140
static uint64_t stats_n_bytes_read
Definition: mainloop.c:138
smartlist_t * get_connection_array(void)
Definition: mainloop.c:443
uint64_t get_bytes_written(void)
Definition: mainloop.c:465
void rescan_periodic_events(const or_options_t *options)
Definition: mainloop.c:1597
Header file for mainloop.c.
#define tor_free(p)
Definition: malloc.h:56
char * networkstatus_getinfo_helper_single(const routerstatus_t *rs)
Header file for networkstatus.c.
Networkstatus consensus/vote structure.
const node_t * node_get_by_id(const char *identity_digest)
Definition: nodelist.c:226
void node_get_verbose_nickname(const node_t *node, char *verbose_name_out)
Definition: nodelist.c:1542
Header file for nodelist.c.
circuit_status_event_t
Definition: ocirc_event.h:19
Master header file for Tor-specific functionality.
#define END_STREAM_REASON_FLAG_REMOTE
Definition: or.h:289
#define MAX_VERBOSE_NICKNAME_LEN
Definition: or.h:118
rend_auth_type_t
Definition: or.h:356
#define END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
Definition: or.h:292
#define TO_CONN(c)
Definition: or.h:612
#define END_CIRC_REASON_FLAG_REMOTE
Definition: or.h:341
#define ENTRY_TO_CONN(c)
Definition: or.h:615
OR connection structure.
or_conn_status_event_t
Definition: orconn_event.h:59
Origin circuit structure.
int tor_vasprintf(char **strp, const char *fmt, va_list args)
Definition: printf.c:96
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
const char * stream_end_reason_to_control_string(int reason)
Definition: reasons.c:28
const char * orconn_end_reason_to_control_string(int r)
Definition: reasons.c:225
const char * circuit_end_reason_to_control_string(int reason)
Definition: reasons.c:328
Header file for reasons.c.
void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern,...)
Definition: smartlist.c:36
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition: smartlist.c:279
void smartlist_add_strdup(struct smartlist_t *sl, const char *string)
smartlist_t * smartlist_new(void)
void smartlist_add(smartlist_t *sl, void *element)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define SMARTLIST_FOREACH(sl, type, var, cmd)
uint64_t global_identifier
Definition: channel.h:197
smartlist_t * testing_cell_stats
Definition: circuit_st.h:213
channel_t * n_chan
Definition: circuit_st.h:70
circid_t n_circ_id
Definition: circuit_st.h:79
uint32_t n_read_conn_bw
unsigned int type
Definition: connection_st.h:50
uint64_t global_identifier
uint32_t n_written_conn_bw
unsigned int purpose
Definition: connection_st.h:51
socks_request_t * socks_request
smartlist_t * routerstatus_list
Definition: node_st.h:34
channel_t * p_chan
Definition: or_circuit_st.h:37
circid_t p_circ_id
Definition: or_circuit_st.h:33
channel_tls_t * chan
uint32_t n_overhead_written_circ_bw
uint32_t n_delivered_read_circ_bw
uint32_t n_delivered_written_circ_bw
uint32_t n_overhead_read_circ_bw
Definition: or.h:820
#define STATIC
Definition: testsupport.h:32
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
void format_iso_time_nospace_usec(char *buf, const struct timeval *tv)
Definition: time_fmt.c:354
void format_iso_time(char *buf, time_t t)
Definition: time_fmt.c:326
void format_local_iso_time(char *buf, time_t t)
Definition: time_fmt.c:316
void tor_gettimeofday(struct timeval *timeval)
#define tor_assert(expr)
Definition: util_bug.h:103
#define tor_fragile_assert()
Definition: util_bug.h:278