Tor  0.4.3.0-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-2019, 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"
17 #include "core/mainloop/mainloop.h"
18 #include "core/or/channeltls.h"
19 #include "core/or/circuitlist.h"
20 #include "core/or/command.h"
22 #include "core/or/connection_or.h"
23 #include "core/or/reasons.h"
32 
37 #include "core/or/or_circuit_st.h"
39 
41 #include "lib/encoding/confline.h"
42 
43 static void flush_queued_events_cb(mainloop_event_t *event, void *arg);
44 static void control_get_bytes_rw_last_sec(uint64_t *r, uint64_t *w);
45 
46 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
47  * finished authentication and is accepting commands. */
48 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
49 
50 /** An event mask of all the events that any controller is interested in
51  * receiving. */
52 static event_mask_t global_event_mask = 0;
53 
54 /** True iff we have disabled log messages from being sent to the controller */
55 static int disable_log_messages = 0;
56 
57 /** Macro: true if any control connection is interested in events of type
58  * <b>e</b>. */
59 #define EVENT_IS_INTERESTING(e) \
60  (!! (global_event_mask & EVENT_MASK_(e)))
61 
62 /** Macro: true if any event from the bitfield 'e' is interesting. */
63 #define ANY_EVENT_IS_INTERESTING(e) \
64  (!! (global_event_mask & (e)))
65 
66 static void send_control_event_impl(uint16_t event,
67  const char *format, va_list ap)
68  CHECK_PRINTF(2,0);
69 static int control_event_status(int type, int severity, const char *format,
70  va_list args)
71  CHECK_PRINTF(3,0);
72 
73 static void send_control_event(uint16_t event,
74  const char *format, ...)
75  CHECK_PRINTF(2,3);
76 
77 /** Table mapping event values to their names. Used to implement SETEVENTS
78  * and GETINFO events/names, and to keep they in sync. */
79 const struct control_event_t control_event_table[] = {
80  { EVENT_CIRCUIT_STATUS, "CIRC" },
81  { EVENT_CIRCUIT_STATUS_MINOR, "CIRC_MINOR" },
82  { EVENT_STREAM_STATUS, "STREAM" },
83  { EVENT_OR_CONN_STATUS, "ORCONN" },
84  { EVENT_BANDWIDTH_USED, "BW" },
85  { EVENT_DEBUG_MSG, "DEBUG" },
86  { EVENT_INFO_MSG, "INFO" },
87  { EVENT_NOTICE_MSG, "NOTICE" },
88  { EVENT_WARN_MSG, "WARN" },
89  { EVENT_ERR_MSG, "ERR" },
90  { EVENT_NEW_DESC, "NEWDESC" },
91  { EVENT_ADDRMAP, "ADDRMAP" },
92  { EVENT_DESCCHANGED, "DESCCHANGED" },
93  { EVENT_NS, "NS" },
94  { EVENT_STATUS_GENERAL, "STATUS_GENERAL" },
95  { EVENT_STATUS_CLIENT, "STATUS_CLIENT" },
96  { EVENT_STATUS_SERVER, "STATUS_SERVER" },
97  { EVENT_GUARD, "GUARD" },
98  { EVENT_STREAM_BANDWIDTH_USED, "STREAM_BW" },
99  { EVENT_CLIENTS_SEEN, "CLIENTS_SEEN" },
100  { EVENT_NEWCONSENSUS, "NEWCONSENSUS" },
101  { EVENT_BUILDTIMEOUT_SET, "BUILDTIMEOUT_SET" },
102  { EVENT_GOT_SIGNAL, "SIGNAL" },
103  { EVENT_CONF_CHANGED, "CONF_CHANGED"},
104  { EVENT_CONN_BW, "CONN_BW" },
105  { EVENT_CELL_STATS, "CELL_STATS" },
106  { EVENT_CIRC_BANDWIDTH_USED, "CIRC_BW" },
107  { EVENT_TRANSPORT_LAUNCHED, "TRANSPORT_LAUNCHED" },
108  { EVENT_HS_DESC, "HS_DESC" },
109  { EVENT_HS_DESC_CONTENT, "HS_DESC_CONTENT" },
110  { EVENT_NETWORK_LIVENESS, "NETWORK_LIVENESS" },
111  { 0, NULL },
112 };
113 
114 /** Given a log severity, return the corresponding control event code. */
115 static inline int
117 {
118  switch (severity) {
119  case LOG_DEBUG: return EVENT_DEBUG_MSG;
120  case LOG_INFO: return EVENT_INFO_MSG;
121  case LOG_NOTICE: return EVENT_NOTICE_MSG;
122  case LOG_WARN: return EVENT_WARN_MSG;
123  case LOG_ERR: return EVENT_ERR_MSG;
124  default: return -1;
125  }
126 }
127 
128 /** Helper: clear bandwidth counters of all origin circuits. */
129 static void
131 {
132  origin_circuit_t *ocirc;
134  if (!CIRCUIT_IS_ORIGIN(circ))
135  continue;
136  ocirc = TO_ORIGIN_CIRCUIT(circ);
137  ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
140  }
141  SMARTLIST_FOREACH_END(circ);
142 }
143 
144 /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
145  * connection's event_mask field. */
146 void
148 {
150  event_mask_t old_mask, new_mask;
151  old_mask = global_event_mask;
152  int any_old_per_sec_events = control_any_per_second_event_enabled();
153 
154  global_event_mask = 0;
155  SMARTLIST_FOREACH(conns, connection_t *, _conn,
156  {
157  if (_conn->type == CONN_TYPE_CONTROL &&
158  STATE_IS_OPEN(_conn->state)) {
159  control_connection_t *conn = TO_CONTROL_CONN(_conn);
160  global_event_mask |= conn->event_mask;
161  }
162  });
163 
164  new_mask = global_event_mask;
165 
166  /* Handle the aftermath. Set up the log callback to tell us only what
167  * we want to hear...*/
169 
170  /* Macro: true if ev was false before and is true now. */
171 #define NEWLY_ENABLED(ev) \
172  (! (old_mask & (ev)) && (new_mask & (ev)))
173 
174  /* ...then, if we've started logging stream or circ bw, clear the
175  * appropriate fields. */
176  if (NEWLY_ENABLED(EVENT_STREAM_BANDWIDTH_USED)) {
177  SMARTLIST_FOREACH(conns, connection_t *, conn,
178  {
179  if (conn->type == CONN_TYPE_AP) {
180  edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
181  edge_conn->n_written = edge_conn->n_read = 0;
182  }
183  });
184  }
185  if (NEWLY_ENABLED(EVENT_CIRC_BANDWIDTH_USED)) {
187  }
188  if (NEWLY_ENABLED(EVENT_BANDWIDTH_USED)) {
189  uint64_t r, w;
191  }
192  if (any_old_per_sec_events != control_any_per_second_event_enabled()) {
194  }
195 
196 #undef NEWLY_ENABLED
197 }
198 
199 /** Given a control event code for a message event, return the corresponding
200  * log severity. */
201 static inline int
203 {
204  switch (event) {
205  case EVENT_DEBUG_MSG: return LOG_DEBUG;
206  case EVENT_INFO_MSG: return LOG_INFO;
207  case EVENT_NOTICE_MSG: return LOG_NOTICE;
208  case EVENT_WARN_MSG: return LOG_WARN;
209  case EVENT_ERR_MSG: return LOG_ERR;
210  default: return -1;
211  }
212 }
213 
214 /** Adjust the log severities that result in control_event_logmsg being called
215  * to match the severity of log messages that any controllers are interested
216  * in. */
217 void
219 {
220  int i;
221  int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
222 
223  for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
224  if (EVENT_IS_INTERESTING(i)) {
225  min_log_event = i;
226  break;
227  }
228  }
229  for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
230  if (EVENT_IS_INTERESTING(i)) {
231  max_log_event = i;
232  break;
233  }
234  }
235  if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
236  if (min_log_event > EVENT_NOTICE_MSG)
237  min_log_event = EVENT_NOTICE_MSG;
238  if (max_log_event < EVENT_ERR_MSG)
239  max_log_event = EVENT_ERR_MSG;
240  }
241  if (min_log_event <= max_log_event)
243  event_to_log_severity(max_log_event),
245  else
248 }
249 
250 /** Return true iff the event with code <b>c</b> is being sent to any current
251  * control connection. This is useful if the amount of work needed to prepare
252  * to call the appropriate control_event_...() function is high.
253  */
254 int
256 {
257  return EVENT_IS_INTERESTING(event);
258 }
259 
260 /** Return true if any event that needs to fire once a second is enabled. */
261 int
263 {
265  EVENT_MASK_(EVENT_BANDWIDTH_USED) |
266  EVENT_MASK_(EVENT_CELL_STATS) |
267  EVENT_MASK_(EVENT_CIRC_BANDWIDTH_USED) |
268  EVENT_MASK_(EVENT_CONN_BW) |
269  EVENT_MASK_(EVENT_STREAM_BANDWIDTH_USED)
270  );
271 }
272 
273 /* The value of 'get_bytes_read()' the previous time that
274  * control_get_bytes_rw_last_sec() as called. */
275 static uint64_t stats_prev_n_read = 0;
276 /* The value of 'get_bytes_written()' the previous time that
277  * control_get_bytes_rw_last_sec() as called. */
278 static uint64_t stats_prev_n_written = 0;
279 
280 /**
281  * Set <b>n_read</b> and <b>n_written</b> to the total number of bytes read
282  * and written by Tor since the last call to this function.
283  *
284  * Call this only from the main thread.
285  */
286 static void
288  uint64_t *n_written)
289 {
290  const uint64_t stats_n_bytes_read = get_bytes_read();
291  const uint64_t stats_n_bytes_written = get_bytes_written();
292 
293  *n_read = stats_n_bytes_read - stats_prev_n_read;
294  *n_written = stats_n_bytes_written - stats_prev_n_written;
295  stats_prev_n_read = stats_n_bytes_read;
296  stats_prev_n_written = stats_n_bytes_written;
297 }
298 
299 /**
300  * Run all the controller events (if any) that are scheduled to trigger once
301  * per second.
302  */
303 void
305 {
307  return;
308 
309  uint64_t bytes_read, bytes_written;
310  control_get_bytes_rw_last_sec(&bytes_read, &bytes_written);
311  control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
312 
317 }
318 
319 /** Represents an event that's queued to be sent to one or more
320  * controllers. */
321 typedef struct queued_event_t {
322  uint16_t event;
323  char *msg;
325 
326 /** Pointer to int. If this is greater than 0, we don't allow new events to be
327  * queued. */
329 
330 /** Holds a smartlist of queued_event_t objects that may need to be sent
331  * to one or more controllers */
333 
334 /** True if the flush_queued_events_event is pending. */
336 
337 /** Lock to protect the above fields. */
339 
340 /** An event that should fire in order to flush the contents of
341  * queued_control_events. */
343 
344 void
345 control_initialize_event_queue(void)
346 {
347  if (queued_control_events == NULL) {
349  }
350 
351  if (flush_queued_events_event == NULL) {
352  struct event_base *b = tor_libevent_get_base();
353  if (b) {
357  }
358  }
359 
360  if (queued_control_events_lock == NULL) {
363  }
364 }
365 
366 static int *
367 get_block_event_queue(void)
368 {
370  if (PREDICT_UNLIKELY(val == NULL)) {
371  val = tor_malloc_zero(sizeof(int));
373  }
374  return val;
375 }
376 
377 /** Helper: inserts an event on the list of events queued to be sent to
378  * one or more controllers, and schedules the events to be flushed if needed.
379  *
380  * This function takes ownership of <b>msg</b>, and may free it.
381  *
382  * We queue these events rather than send them immediately in order to break
383  * the dependency in our callgraph from code that generates events for the
384  * controller, and the network layer at large. Otherwise, nearly every
385  * interesting part of Tor would potentially call every other interesting part
386  * of Tor.
387  */
388 MOCK_IMPL(STATIC void,
389 queue_control_event_string,(uint16_t event, char *msg))
390 {
391  /* This is redundant with checks done elsewhere, but it's a last-ditch
392  * attempt to avoid queueing something we shouldn't have to queue. */
393  if (PREDICT_UNLIKELY( ! EVENT_IS_INTERESTING(event) )) {
394  tor_free(msg);
395  return;
396  }
397 
398  int *block_event_queue = get_block_event_queue();
399  if (*block_event_queue) {
400  tor_free(msg);
401  return;
402  }
403 
404  queued_event_t *ev = tor_malloc(sizeof(*ev));
405  ev->event = event;
406  ev->msg = msg;
407 
408  /* No queueing an event while queueing an event */
409  ++*block_event_queue;
410 
414 
415  int activate_event = 0;
417  activate_event = 1;
419  }
420 
422 
423  --*block_event_queue;
424 
425  /* We just put an event on the queue; mark the queue to be
426  * flushed. We only do this from the main thread for now; otherwise,
427  * we'd need to incur locking overhead in Libevent or use a socket.
428  */
429  if (activate_event) {
432  }
433 }
434 
435 #define queued_event_free(ev) \
436  FREE_AND_NULL(queued_event_t, queued_event_free_, (ev))
437 
438 /** Release all storage held by <b>ev</b>. */
439 static void
441 {
442  if (ev == NULL)
443  return;
444 
445  tor_free(ev->msg);
446  tor_free(ev);
447 }
448 
449 /** Send every queued event to every controller that's interested in it,
450  * and remove the events from the queue. If <b>force</b> is true,
451  * then make all controllers send their data out immediately, since we
452  * may be about to shut down. */
453 static void
455 {
456  /* Make sure that we get all the pending log events, if there are any. */
458 
459  if (PREDICT_UNLIKELY(queued_control_events == NULL)) {
460  return;
461  }
462  smartlist_t *all_conns = get_connection_array();
463  smartlist_t *controllers = smartlist_new();
464  smartlist_t *queued_events;
465 
466  int *block_event_queue = get_block_event_queue();
467  ++*block_event_queue;
468 
470  /* No queueing an event while flushing events. */
472  queued_events = queued_control_events;
475 
476  /* Gather all the controllers that will care... */
477  SMARTLIST_FOREACH_BEGIN(all_conns, connection_t *, conn) {
478  if (conn->type == CONN_TYPE_CONTROL &&
479  !conn->marked_for_close &&
480  conn->state == CONTROL_CONN_STATE_OPEN) {
481  control_connection_t *control_conn = TO_CONTROL_CONN(conn);
482 
483  smartlist_add(controllers, control_conn);
484  }
485  } SMARTLIST_FOREACH_END(conn);
486 
487  SMARTLIST_FOREACH_BEGIN(queued_events, queued_event_t *, ev) {
488  const event_mask_t bit = ((event_mask_t)1) << ev->event;
489  const size_t msg_len = strlen(ev->msg);
491  control_conn) {
492  if (control_conn->event_mask & bit) {
493  connection_buf_add(ev->msg, msg_len, TO_CONN(control_conn));
494  }
495  } SMARTLIST_FOREACH_END(control_conn);
496 
497  queued_event_free(ev);
498  } SMARTLIST_FOREACH_END(ev);
499 
500  if (force) {
502  control_conn) {
503  connection_flush(TO_CONN(control_conn));
504  } SMARTLIST_FOREACH_END(control_conn);
505  }
506 
507  smartlist_free(queued_events);
508  smartlist_free(controllers);
509 
510  --*block_event_queue;
511 }
512 
513 /** Libevent callback: Flushes pending events to controllers that are
514  * interested in them. */
515 static void
517 {
518  (void) event;
519  (void) arg;
521 }
522 
523 /** Send an event to all v1 controllers that are listening for code
524  * <b>event</b>. The event's body is given by <b>msg</b>.
525  *
526  * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
527  * respect to the EXTENDED_EVENTS feature. */
528 MOCK_IMPL(STATIC void,
529 send_control_event_string,(uint16_t event,
530  const char *msg))
531 {
532  tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
533  queue_control_event_string(event, tor_strdup(msg));
534 }
535 
536 /** Helper for send_control_event and control_event_status:
537  * Send an event to all v1 controllers that are listening for code
538  * <b>event</b>. The event's body is created by the printf-style format in
539  * <b>format</b>, and other arguments as provided. */
540 static void
541 send_control_event_impl(uint16_t event,
542  const char *format, va_list ap)
543 {
544  char *buf = NULL;
545  int len;
546 
547  len = tor_vasprintf(&buf, format, ap);
548  if (len < 0) {
549  log_warn(LD_BUG, "Unable to format event for controller.");
550  return;
551  }
552 
553  queue_control_event_string(event, buf);
554 }
555 
556 /** Send an event to all v1 controllers that are listening for code
557  * <b>event</b>. The event's body is created by the printf-style format in
558  * <b>format</b>, and other arguments as provided. */
559 static void
560 send_control_event(uint16_t event,
561  const char *format, ...)
562 {
563  va_list ap;
564  va_start(ap, format);
565  send_control_event_impl(event, format, ap);
566  va_end(ap);
567 }
568 
569 /** Something major has happened to circuit <b>circ</b>: tell any
570  * interested control connections. */
571 int
573  int reason_code)
574 {
575  const char *status;
576  char reasons[64] = "";
577 
578  if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
579  return 0;
580  tor_assert(circ);
581 
582  switch (tp)
583  {
584  case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
585  case CIRC_EVENT_BUILT: status = "BUILT"; break;
586  case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
587  case CIRC_EVENT_FAILED: status = "FAILED"; break;
588  case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
589  default:
590  log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
592  return 0;
593  }
594 
595  if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
596  const char *reason_str = circuit_end_reason_to_control_string(reason_code);
597  char unk_reason_buf[16];
598  if (!reason_str) {
599  tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
600  reason_str = unk_reason_buf;
601  }
602  if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
603  tor_snprintf(reasons, sizeof(reasons),
604  " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
605  } else {
606  tor_snprintf(reasons, sizeof(reasons),
607  " REASON=%s", reason_str);
608  }
609  }
610 
611  {
612  char *circdesc = circuit_describe_status_for_controller(circ);
613  const char *sp = strlen(circdesc) ? " " : "";
614  send_control_event(EVENT_CIRCUIT_STATUS,
615  "650 CIRC %lu %s%s%s%s\r\n",
616  (unsigned long)circ->global_identifier,
617  status, sp,
618  circdesc,
619  reasons);
620  tor_free(circdesc);
621  }
622 
623  return 0;
624 }
625 
626 /** Something minor has happened to circuit <b>circ</b>: tell any
627  * interested control connections. */
628 static int
631  int purpose, const struct timeval *tv)
632 {
633  const char *event_desc;
634  char event_tail[160] = "";
635  if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
636  return 0;
637  tor_assert(circ);
638 
639  switch (e)
640  {
641  case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
642  event_desc = "PURPOSE_CHANGED";
643 
644  {
645  /* event_tail can currently be up to 68 chars long */
646  const char *hs_state_str =
648  tor_snprintf(event_tail, sizeof(event_tail),
649  " OLD_PURPOSE=%s%s%s",
651  (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
652  (hs_state_str != NULL) ? hs_state_str : "");
653  }
654 
655  break;
656  case CIRC_MINOR_EVENT_CANNIBALIZED:
657  event_desc = "CANNIBALIZED";
658 
659  {
660  /* event_tail can currently be up to 130 chars long */
661  const char *hs_state_str =
663  const struct timeval *old_timestamp_began = tv;
664  char tbuf[ISO_TIME_USEC_LEN+1];
665  format_iso_time_nospace_usec(tbuf, old_timestamp_began);
666 
667  tor_snprintf(event_tail, sizeof(event_tail),
668  " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
670  (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
671  (hs_state_str != NULL) ? hs_state_str : "",
672  tbuf);
673  }
674 
675  break;
676  default:
677  log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
679  return 0;
680  }
681 
682  {
683  char *circdesc = circuit_describe_status_for_controller(circ);
684  const char *sp = strlen(circdesc) ? " " : "";
685  send_control_event(EVENT_CIRCUIT_STATUS_MINOR,
686  "650 CIRC_MINOR %lu %s%s%s%s\r\n",
687  (unsigned long)circ->global_identifier,
688  event_desc, sp,
689  circdesc,
690  event_tail);
691  tor_free(circdesc);
692  }
693 
694  return 0;
695 }
696 
697 /**
698  * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
699  * interested controllers.
700  */
701 int
703  int old_purpose)
704 {
706  CIRC_MINOR_EVENT_PURPOSE_CHANGED,
707  old_purpose,
708  NULL);
709 }
710 
711 /**
712  * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
713  * created-time from <b>old_tv_created</b>: tell any interested controllers.
714  */
715 int
717  int old_purpose,
718  const struct timeval *old_tv_created)
719 {
721  CIRC_MINOR_EVENT_CANNIBALIZED,
722  old_purpose,
723  old_tv_created);
724 }
725 
726 /** Something has happened to the stream associated with AP connection
727  * <b>conn</b>: tell any interested control connections. */
728 int
730  int reason_code)
731 {
732  char reason_buf[64];
733  char addrport_buf[64];
734  const char *status;
735  circuit_t *circ;
736  origin_circuit_t *origin_circ = NULL;
737  char buf[256];
738  const char *purpose = "";
739  tor_assert(conn->socks_request);
740 
741  if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
742  return 0;
743 
744  if (tp == STREAM_EVENT_CLOSED &&
746  return 0;
747 
748  write_stream_target_to_buf(conn, buf, sizeof(buf));
749 
750  reason_buf[0] = '\0';
751  switch (tp)
752  {
753  case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
754  case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
755  case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
756  case STREAM_EVENT_FAILED: status = "FAILED"; break;
757  case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
758  case STREAM_EVENT_NEW: status = "NEW"; break;
759  case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
760  case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
761  case STREAM_EVENT_REMAP: status = "REMAP"; break;
762  default:
763  log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
764  return 0;
765  }
766  if (reason_code && (tp == STREAM_EVENT_FAILED ||
767  tp == STREAM_EVENT_CLOSED ||
768  tp == STREAM_EVENT_FAILED_RETRIABLE)) {
769  const char *reason_str = stream_end_reason_to_control_string(reason_code);
770  char *r = NULL;
771  if (!reason_str) {
772  tor_asprintf(&r, " UNKNOWN_%d", reason_code);
773  reason_str = r;
774  }
775  if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
776  tor_snprintf(reason_buf, sizeof(reason_buf),
777  " REASON=END REMOTE_REASON=%s", reason_str);
778  else
779  tor_snprintf(reason_buf, sizeof(reason_buf),
780  " REASON=%s", reason_str);
781  tor_free(r);
782  } else if (reason_code && tp == STREAM_EVENT_REMAP) {
783  switch (reason_code) {
785  strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
786  break;
788  strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
789  break;
790  default:
791  tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
792  reason_code);
793  /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
794  break;
795  }
796  }
797 
798  if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
799  /*
800  * When the control conn is an AF_UNIX socket and we have no address,
801  * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
802  * dnsserv.c.
803  */
804  if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
805  tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
806  ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
807  } else {
808  /*
809  * else leave it blank so control on AF_UNIX doesn't need to make
810  * something up.
811  */
812  addrport_buf[0] = '\0';
813  }
814  } else {
815  addrport_buf[0] = '\0';
816  }
817 
818  if (tp == STREAM_EVENT_NEW_RESOLVE) {
819  purpose = " PURPOSE=DNS_REQUEST";
820  } else if (tp == STREAM_EVENT_NEW) {
821  if (conn->use_begindir) {
822  connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
823  int linked_dir_purpose = -1;
824  if (linked && linked->type == CONN_TYPE_DIR)
825  linked_dir_purpose = linked->purpose;
826  if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
827  purpose = " PURPOSE=DIR_UPLOAD";
828  else
829  purpose = " PURPOSE=DIR_FETCH";
830  } else
831  purpose = " PURPOSE=USER";
832  }
833 
835  if (circ && CIRCUIT_IS_ORIGIN(circ))
836  origin_circ = TO_ORIGIN_CIRCUIT(circ);
837 
838  {
840  const char *sp = strlen(conndesc) ? " " : "";
841  send_control_event(EVENT_STREAM_STATUS,
842  "650 STREAM %"PRIu64" %s %lu %s%s%s%s%s%s\r\n",
843  (ENTRY_TO_CONN(conn)->global_identifier),
844  status,
845  origin_circ?
846  (unsigned long)origin_circ->global_identifier : 0ul,
847  buf, reason_buf, addrport_buf, purpose, sp, conndesc);
848  tor_free(conndesc);
849  }
850 
851  /* XXX need to specify its intended exit, etc? */
852 
853  return 0;
854 }
855 
856 /** Called when the status of an OR connection <b>conn</b> changes: tell any
857  * interested control connections. <b>tp</b> is the new status for the
858  * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
859  * may be the reason why.
860  */
861 int
863  int reason)
864 {
865  int ncircs = 0;
866  const char *status;
867  char name[128];
868  char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
869 
870  if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
871  return 0;
872 
873  switch (tp)
874  {
875  case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
876  case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
877  case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
878  case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
879  case OR_CONN_EVENT_NEW: status = "NEW"; break;
880  default:
881  log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
882  return 0;
883  }
884  if (conn->chan) {
885  ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
886  } else {
887  ncircs = 0;
888  }
889  ncircs += connection_or_get_num_circuits(conn);
890  if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
891  tor_snprintf(ncircs_buf, sizeof(ncircs_buf), " NCIRCS=%d", ncircs);
892  }
893 
894  orconn_target_get_name(name, sizeof(name), conn);
895  send_control_event(EVENT_OR_CONN_STATUS,
896  "650 ORCONN %s %s%s%s%s ID=%"PRIu64"\r\n",
897  name, status,
898  reason ? " REASON=" : "",
900  ncircs_buf,
901  (conn->base_.global_identifier));
902 
903  return 0;
904 }
905 
906 /**
907  * Print out STREAM_BW event for a single conn
908  */
909 int
911 {
912  struct timeval now;
913  char tbuf[ISO_TIME_USEC_LEN+1];
914  if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
915  if (!edge_conn->n_read && !edge_conn->n_written)
916  return 0;
917 
918  tor_gettimeofday(&now);
919  format_iso_time_nospace_usec(tbuf, &now);
920  send_control_event(EVENT_STREAM_BANDWIDTH_USED,
921  "650 STREAM_BW %"PRIu64" %lu %lu %s\r\n",
922  (edge_conn->base_.global_identifier),
923  (unsigned long)edge_conn->n_read,
924  (unsigned long)edge_conn->n_written,
925  tbuf);
926 
927  edge_conn->n_written = edge_conn->n_read = 0;
928  }
929 
930  return 0;
931 }
932 
933 /** A second or more has elapsed: tell any interested control
934  * connections how much bandwidth streams have used. */
935 int
937 {
938  if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
940  edge_connection_t *edge_conn;
941  struct timeval now;
942  char tbuf[ISO_TIME_USEC_LEN+1];
943 
944  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
945  {
946  if (conn->type != CONN_TYPE_AP)
947  continue;
948  edge_conn = TO_EDGE_CONN(conn);
949  if (!edge_conn->n_read && !edge_conn->n_written)
950  continue;
951 
952  tor_gettimeofday(&now);
953  format_iso_time_nospace_usec(tbuf, &now);
954  send_control_event(EVENT_STREAM_BANDWIDTH_USED,
955  "650 STREAM_BW %"PRIu64" %lu %lu %s\r\n",
956  (edge_conn->base_.global_identifier),
957  (unsigned long)edge_conn->n_read,
958  (unsigned long)edge_conn->n_written,
959  tbuf);
960 
961  edge_conn->n_written = edge_conn->n_read = 0;
962  }
963  SMARTLIST_FOREACH_END(conn);
964  }
965 
966  return 0;
967 }
968 
969 /** A second or more has elapsed: tell any interested control connections
970  * how much bandwidth origin circuits have used. */
971 int
973 {
974  if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
975  return 0;
976 
978  if (!CIRCUIT_IS_ORIGIN(circ))
979  continue;
980 
982  }
983  SMARTLIST_FOREACH_END(circ);
984 
985  return 0;
986 }
987 
988 /**
989  * Emit a CIRC_BW event line for a specific circuit.
990  *
991  * This function sets the values it emits to 0, and does not emit
992  * an event if there is no new data to report since the last call.
993  *
994  * Therefore, it may be called at any frequency.
995  */
996 int
998 {
999  struct timeval now;
1000  char tbuf[ISO_TIME_USEC_LEN+1];
1001 
1002  tor_assert(ocirc);
1003 
1004  if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
1005  return 0;
1006 
1007  /* n_read_circ_bw and n_written_circ_bw are always updated
1008  * when there is any new cell on a circuit, and set to 0 after
1009  * the event, below.
1010  *
1011  * Therefore, checking them is sufficient to determine if there
1012  * is new data to report. */
1013  if (!ocirc->n_read_circ_bw && !ocirc->n_written_circ_bw)
1014  return 0;
1015 
1016  tor_gettimeofday(&now);
1017  format_iso_time_nospace_usec(tbuf, &now);
1018  send_control_event(EVENT_CIRC_BANDWIDTH_USED,
1019  "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu TIME=%s "
1020  "DELIVERED_READ=%lu OVERHEAD_READ=%lu "
1021  "DELIVERED_WRITTEN=%lu OVERHEAD_WRITTEN=%lu\r\n",
1022  ocirc->global_identifier,
1023  (unsigned long)ocirc->n_read_circ_bw,
1024  (unsigned long)ocirc->n_written_circ_bw,
1025  tbuf,
1026  (unsigned long)ocirc->n_delivered_read_circ_bw,
1027  (unsigned long)ocirc->n_overhead_read_circ_bw,
1028  (unsigned long)ocirc->n_delivered_written_circ_bw,
1029  (unsigned long)ocirc->n_overhead_written_circ_bw);
1030  ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
1033 
1034  return 0;
1035 }
1036 
1037 /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
1038  * bandwidth counters. */
1039 int
1041 {
1042  const char *conn_type_str;
1043  if (!get_options()->TestingEnableConnBwEvent ||
1044  !EVENT_IS_INTERESTING(EVENT_CONN_BW))
1045  return 0;
1046  if (!conn->n_read_conn_bw && !conn->n_written_conn_bw)
1047  return 0;
1048  switch (conn->type) {
1049  case CONN_TYPE_OR:
1050  conn_type_str = "OR";
1051  break;
1052  case CONN_TYPE_DIR:
1053  conn_type_str = "DIR";
1054  break;
1055  case CONN_TYPE_EXIT:
1056  conn_type_str = "EXIT";
1057  break;
1058  default:
1059  return 0;
1060  }
1061  send_control_event(EVENT_CONN_BW,
1062  "650 CONN_BW ID=%"PRIu64" TYPE=%s "
1063  "READ=%lu WRITTEN=%lu\r\n",
1064  (conn->global_identifier),
1065  conn_type_str,
1066  (unsigned long)conn->n_read_conn_bw,
1067  (unsigned long)conn->n_written_conn_bw);
1068  conn->n_written_conn_bw = conn->n_read_conn_bw = 0;
1069  return 0;
1070 }
1071 
1072 /** A second or more has elapsed: tell any interested control
1073  * connections how much bandwidth connections have used. */
1074 int
1076 {
1077  if (get_options()->TestingEnableConnBwEvent &&
1078  EVENT_IS_INTERESTING(EVENT_CONN_BW)) {
1081  }
1082  return 0;
1083 }
1084 
1085 /** Helper: iterate over cell statistics of <b>circ</b> and sum up added
1086  * cells, removed cells, and waiting times by cell command and direction.
1087  * Store results in <b>cell_stats</b>. Free cell statistics of the
1088  * circuit afterwards. */
1089 void
1090 sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
1091 {
1092  memset(cell_stats, 0, sizeof(cell_stats_t));
1094  const testing_cell_stats_entry_t *, ent) {
1095  tor_assert(ent->command <= CELL_COMMAND_MAX_);
1096  if (!ent->removed && !ent->exitward) {
1097  cell_stats->added_cells_appward[ent->command] += 1;
1098  } else if (!ent->removed && ent->exitward) {
1099  cell_stats->added_cells_exitward[ent->command] += 1;
1100  } else if (!ent->exitward) {
1101  cell_stats->removed_cells_appward[ent->command] += 1;
1102  cell_stats->total_time_appward[ent->command] += ent->waiting_time * 10;
1103  } else {
1104  cell_stats->removed_cells_exitward[ent->command] += 1;
1105  cell_stats->total_time_exitward[ent->command] += ent->waiting_time * 10;
1106  }
1107  } SMARTLIST_FOREACH_END(ent);
1109 }
1110 
1111 /** Helper: append a cell statistics string to <code>event_parts</code>,
1112  * prefixed with <code>key</code>=. Statistics consist of comma-separated
1113  * key:value pairs with lower-case command strings as keys and cell
1114  * numbers or total waiting times as values. A key:value pair is included
1115  * if the entry in <code>include_if_non_zero</code> is not zero, but with
1116  * the (possibly zero) entry from <code>number_to_include</code>. Both
1117  * arrays are expected to have a length of CELL_COMMAND_MAX_ + 1. If no
1118  * entry in <code>include_if_non_zero</code> is positive, no string will
1119  * be added to <code>event_parts</code>. */
1120 void
1121 append_cell_stats_by_command(smartlist_t *event_parts, const char *key,
1122  const uint64_t *include_if_non_zero,
1123  const uint64_t *number_to_include)
1124 {
1125  smartlist_t *key_value_strings = smartlist_new();
1126  int i;
1127  for (i = 0; i <= CELL_COMMAND_MAX_; i++) {
1128  if (include_if_non_zero[i] > 0) {
1129  smartlist_add_asprintf(key_value_strings, "%s:%"PRIu64,
1131  (number_to_include[i]));
1132  }
1133  }
1134  if (smartlist_len(key_value_strings) > 0) {
1135  char *joined = smartlist_join_strings(key_value_strings, ",", 0, NULL);
1136  smartlist_add_asprintf(event_parts, "%s=%s", key, joined);
1137  SMARTLIST_FOREACH(key_value_strings, char *, cp, tor_free(cp));
1138  tor_free(joined);
1139  }
1140  smartlist_free(key_value_strings);
1141 }
1142 
1143 /** Helper: format <b>cell_stats</b> for <b>circ</b> for inclusion in a
1144  * CELL_STATS event and write result string to <b>event_string</b>. */
1145 void
1146 format_cell_stats(char **event_string, circuit_t *circ,
1147  cell_stats_t *cell_stats)
1148 {
1149  smartlist_t *event_parts = smartlist_new();
1150  if (CIRCUIT_IS_ORIGIN(circ)) {
1151  origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1152  smartlist_add_asprintf(event_parts, "ID=%lu",
1153  (unsigned long)ocirc->global_identifier);
1154  } else if (TO_OR_CIRCUIT(circ)->p_chan) {
1155  or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1156  smartlist_add_asprintf(event_parts, "InboundQueue=%lu",
1157  (unsigned long)or_circ->p_circ_id);
1158  smartlist_add_asprintf(event_parts, "InboundConn=%"PRIu64,
1159  (or_circ->p_chan->global_identifier));
1160  append_cell_stats_by_command(event_parts, "InboundAdded",
1161  cell_stats->added_cells_appward,
1162  cell_stats->added_cells_appward);
1163  append_cell_stats_by_command(event_parts, "InboundRemoved",
1164  cell_stats->removed_cells_appward,
1165  cell_stats->removed_cells_appward);
1166  append_cell_stats_by_command(event_parts, "InboundTime",
1167  cell_stats->removed_cells_appward,
1168  cell_stats->total_time_appward);
1169  }
1170  if (circ->n_chan) {
1171  smartlist_add_asprintf(event_parts, "OutboundQueue=%lu",
1172  (unsigned long)circ->n_circ_id);
1173  smartlist_add_asprintf(event_parts, "OutboundConn=%"PRIu64,
1174  (circ->n_chan->global_identifier));
1175  append_cell_stats_by_command(event_parts, "OutboundAdded",
1176  cell_stats->added_cells_exitward,
1177  cell_stats->added_cells_exitward);
1178  append_cell_stats_by_command(event_parts, "OutboundRemoved",
1179  cell_stats->removed_cells_exitward,
1180  cell_stats->removed_cells_exitward);
1181  append_cell_stats_by_command(event_parts, "OutboundTime",
1182  cell_stats->removed_cells_exitward,
1183  cell_stats->total_time_exitward);
1184  }
1185  *event_string = smartlist_join_strings(event_parts, " ", 0, NULL);
1186  SMARTLIST_FOREACH(event_parts, char *, cp, tor_free(cp));
1187  smartlist_free(event_parts);
1188 }
1189 
1190 /** A second or more has elapsed: tell any interested control connection
1191  * how many cells have been processed for a given circuit. */
1192 int
1194 {
1195  cell_stats_t *cell_stats;
1196  char *event_string;
1197  if (!get_options()->TestingEnableCellStatsEvent ||
1198  !EVENT_IS_INTERESTING(EVENT_CELL_STATS))
1199  return 0;
1200  cell_stats = tor_malloc(sizeof(cell_stats_t));
1202  if (!circ->testing_cell_stats)
1203  continue;
1204  sum_up_cell_stats_by_command(circ, cell_stats);
1205  format_cell_stats(&event_string, circ, cell_stats);
1206  send_control_event(EVENT_CELL_STATS,
1207  "650 CELL_STATS %s\r\n", event_string);
1208  tor_free(event_string);
1209  }
1210  SMARTLIST_FOREACH_END(circ);
1211  tor_free(cell_stats);
1212  return 0;
1213 }
1214 
1215 /* about 5 minutes worth. */
1216 #define N_BW_EVENTS_TO_CACHE 300
1217 /* Index into cached_bw_events to next write. */
1218 static int next_measurement_idx = 0;
1219 /* number of entries set in n_measurements */
1220 static int n_measurements = 0;
1221 static struct cached_bw_event_t {
1222  uint32_t n_read;
1223  uint32_t n_written;
1224 } cached_bw_events[N_BW_EVENTS_TO_CACHE];
1225 
1226 /** A second or more has elapsed: tell any interested control
1227  * connections how much bandwidth we used. */
1228 int
1229 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
1230 {
1231  cached_bw_events[next_measurement_idx].n_read = n_read;
1232  cached_bw_events[next_measurement_idx].n_written = n_written;
1233  if (++next_measurement_idx == N_BW_EVENTS_TO_CACHE)
1234  next_measurement_idx = 0;
1235  if (n_measurements < N_BW_EVENTS_TO_CACHE)
1236  ++n_measurements;
1237 
1238  if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
1239  send_control_event(EVENT_BANDWIDTH_USED,
1240  "650 BW %lu %lu\r\n",
1241  (unsigned long)n_read,
1242  (unsigned long)n_written);
1243  }
1244 
1245  return 0;
1246 }
1247 
1248 char *
1249 get_bw_samples(void)
1250 {
1251  int i;
1252  int idx = (next_measurement_idx + N_BW_EVENTS_TO_CACHE - n_measurements)
1253  % N_BW_EVENTS_TO_CACHE;
1254  tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
1255 
1256  smartlist_t *elements = smartlist_new();
1257 
1258  for (i = 0; i < n_measurements; ++i) {
1259  tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
1260  const struct cached_bw_event_t *bwe = &cached_bw_events[idx];
1261 
1262  smartlist_add_asprintf(elements, "%u,%u",
1263  (unsigned)bwe->n_read,
1264  (unsigned)bwe->n_written);
1265 
1266  idx = (idx + 1) % N_BW_EVENTS_TO_CACHE;
1267  }
1268 
1269  char *result = smartlist_join_strings(elements, " ", 0, NULL);
1270 
1271  SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
1272  smartlist_free(elements);
1273 
1274  return result;
1275 }
1276 
1277 /** Called when we are sending a log message to the controllers: suspend
1278  * sending further log messages to the controllers until we're done. Used by
1279  * CONN_LOG_PROTECT. */
1280 void
1282 {
1284 }
1285 
1286 /** We're done sending a log message to the controllers: re-enable controller
1287  * logging. Used by CONN_LOG_PROTECT. */
1288 void
1290 {
1291  if (--disable_log_messages < 0)
1292  tor_assert(0);
1293 }
1294 
1295 /** We got a log message: tell any interested control connections. */
1296 void
1297 control_event_logmsg(int severity, log_domain_mask_t domain, const char *msg)
1298 {
1299  int event;
1300 
1301  /* Don't even think of trying to add stuff to a buffer from a cpuworker
1302  * thread. (See #25987 for plan to fix.) */
1303  if (! in_main_thread())
1304  return;
1305 
1307  return;
1308 
1309  if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
1310  severity <= LOG_NOTICE) {
1311  char *esc = esc_for_log(msg);
1313  control_event_general_status(severity, "BUG REASON=%s", esc);
1315  tor_free(esc);
1316  }
1317 
1318  event = log_severity_to_event(severity);
1319  if (event >= 0 && EVENT_IS_INTERESTING(event)) {
1320  char *b = NULL;
1321  const char *s;
1322  if (strchr(msg, '\n')) {
1323  char *cp;
1324  b = tor_strdup(msg);
1325  for (cp = b; *cp; ++cp)
1326  if (*cp == '\r' || *cp == '\n')
1327  *cp = ' ';
1328  }
1329  switch (severity) {
1330  case LOG_DEBUG: s = "DEBUG"; break;
1331  case LOG_INFO: s = "INFO"; break;
1332  case LOG_NOTICE: s = "NOTICE"; break;
1333  case LOG_WARN: s = "WARN"; break;
1334  case LOG_ERR: s = "ERR"; break;
1335  default: s = "UnknownLogSeverity"; break;
1336  }
1338  send_control_event(event, "650 %s %s\r\n", s, b?b:msg);
1339  if (severity == LOG_ERR) {
1340  /* Force a flush, since we may be about to die horribly */
1342  }
1344  tor_free(b);
1345  }
1346 }
1347 
1348 /**
1349  * Logging callback: called when there is a queued pending log callback.
1350  */
1351 void
1353 {
1354  if (! in_main_thread()) {
1355  /* We can't handle this case yet, since we're using a
1356  * mainloop_event_t to invoke queued_events_flush_all. We ought to
1357  * use a different mechanism instead: see #25987.
1358  **/
1359  return;
1360  }
1363 }
1364 
1365 /** Called whenever we receive new router descriptors: tell any
1366  * interested control connections. <b>routers</b> is a list of
1367  * routerinfo_t's.
1368  */
1369 int
1371 {
1372  char *msg;
1373 
1374  if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
1375  return 0;
1376 
1377  {
1378  smartlist_t *names = smartlist_new();
1379  char *ids;
1380  SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
1381  char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
1383  smartlist_add(names, b);
1384  });
1385  ids = smartlist_join_strings(names, " ", 0, NULL);
1386  tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
1387  send_control_event_string(EVENT_NEW_DESC, msg);
1388  tor_free(ids);
1389  tor_free(msg);
1390  SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
1391  smartlist_free(names);
1392  }
1393  return 0;
1394 }
1395 
1396 /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
1397  * <b>expires</b> values less than 3 are special; see connection_edge.c. If
1398  * <b>error</b> is non-NULL, it is an error code describing the failure
1399  * mode of the mapping.
1400  */
1401 int
1402 control_event_address_mapped(const char *from, const char *to, time_t expires,
1403  const char *error, const int cached)
1404 {
1405  if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
1406  return 0;
1407 
1408  if (expires < 3 || expires == TIME_MAX)
1409  send_control_event(EVENT_ADDRMAP,
1410  "650 ADDRMAP %s %s NEVER %s%s"
1411  "CACHED=\"%s\"\r\n",
1412  from, to, error?error:"", error?" ":"",
1413  cached?"YES":"NO");
1414  else {
1415  char buf[ISO_TIME_LEN+1];
1416  char buf2[ISO_TIME_LEN+1];
1417  format_local_iso_time(buf,expires);
1418  format_iso_time(buf2,expires);
1419  send_control_event(EVENT_ADDRMAP,
1420  "650 ADDRMAP %s %s \"%s\""
1421  " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
1422  from, to, buf,
1423  error?error:"", error?" ":"",
1424  buf2, cached?"YES":"NO");
1425  }
1426 
1427  return 0;
1428 }
1429 /** The network liveness has changed; this is called from circuitstats.c
1430  * whenever we receive a cell, or when timeout expires and we assume the
1431  * network is down. */
1432 int
1434 {
1435  if (liveness > 0) {
1436  if (get_cached_network_liveness() <= 0) {
1437  /* Update cached liveness */
1438  set_cached_network_liveness(1);
1439  log_debug(LD_CONTROL, "Sending NETWORK_LIVENESS UP");
1440  send_control_event_string(EVENT_NETWORK_LIVENESS,
1441  "650 NETWORK_LIVENESS UP\r\n");
1442  }
1443  /* else was already live, no-op */
1444  } else {
1445  if (get_cached_network_liveness() > 0) {
1446  /* Update cached liveness */
1447  set_cached_network_liveness(0);
1448  log_debug(LD_CONTROL, "Sending NETWORK_LIVENESS DOWN");
1449  send_control_event_string(EVENT_NETWORK_LIVENESS,
1450  "650 NETWORK_LIVENESS DOWN\r\n");
1451  }
1452  /* else was already dead, no-op */
1453  }
1454 
1455  return 0;
1456 }
1457 
1458 /** Helper function for NS-style events. Constructs and sends an event
1459  * of type <b>event</b> with string <b>event_string</b> out of the set of
1460  * networkstatuses <b>statuses</b>. Currently it is used for NS events
1461  * and NEWCONSENSUS events. */
1462 static int
1464  uint16_t event,
1465  const char *event_string)
1466 {
1467  smartlist_t *strs;
1468  char *s, *esc = NULL;
1469  if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
1470  return 0;
1471 
1472  strs = smartlist_new();
1473  smartlist_add_strdup(strs, "650+");
1474  smartlist_add_strdup(strs, event_string);
1475  smartlist_add_strdup(strs, "\r\n");
1476  SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
1477  {
1479  if (!s) continue;
1480  smartlist_add(strs, s);
1481  });
1482 
1483  s = smartlist_join_strings(strs, "", 0, NULL);
1484  write_escaped_data(s, strlen(s), &esc);
1485  SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
1486  smartlist_free(strs);
1487  tor_free(s);
1488  send_control_event_string(event, esc);
1490  "650 OK\r\n");
1491 
1492  tor_free(esc);
1493  return 0;
1494 }
1495 
1496 /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
1497  * an NS event to any controller that cares. */
1498 int
1500 {
1501  return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
1502 }
1503 
1504 /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
1505  * event consisting of an NS-style line for each relay in the consensus. */
1506 int
1508 {
1509  if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
1510  return 0;
1512  consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
1513 }
1514 
1515 /** Called when we compute a new circuitbuildtimeout */
1516 int
1518  const char *args)
1519 {
1520  const char *type_string = NULL;
1521 
1522  if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
1523  return 0;
1524 
1525  switch (type) {
1526  case BUILDTIMEOUT_SET_EVENT_COMPUTED:
1527  type_string = "COMPUTED";
1528  break;
1529  case BUILDTIMEOUT_SET_EVENT_RESET:
1530  type_string = "RESET";
1531  break;
1532  case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
1533  type_string = "SUSPENDED";
1534  break;
1535  case BUILDTIMEOUT_SET_EVENT_DISCARD:
1536  type_string = "DISCARD";
1537  break;
1538  case BUILDTIMEOUT_SET_EVENT_RESUME:
1539  type_string = "RESUME";
1540  break;
1541  default:
1542  type_string = "UNKNOWN";
1543  break;
1544  }
1545 
1546  send_control_event(EVENT_BUILDTIMEOUT_SET,
1547  "650 BUILDTIMEOUT_SET %s %s\r\n",
1548  type_string, args);
1549 
1550  return 0;
1551 }
1552 
1553 /** Called when a signal has been processed from signal_callback */
1554 int
1555 control_event_signal(uintptr_t signal_num)
1556 {
1557  const char *signal_string = NULL;
1558 
1559  if (!control_event_is_interesting(EVENT_GOT_SIGNAL))
1560  return 0;
1561 
1562  switch (signal_num) {
1563  case SIGHUP:
1564  signal_string = "RELOAD";
1565  break;
1566  case SIGUSR1:
1567  signal_string = "DUMP";
1568  break;
1569  case SIGUSR2:
1570  signal_string = "DEBUG";
1571  break;
1572  case SIGNEWNYM:
1573  signal_string = "NEWNYM";
1574  break;
1575  case SIGCLEARDNSCACHE:
1576  signal_string = "CLEARDNSCACHE";
1577  break;
1578  case SIGHEARTBEAT:
1579  signal_string = "HEARTBEAT";
1580  break;
1581  default:
1582  log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
1583  (unsigned long)signal_num);
1584  return -1;
1585  }
1586 
1587  send_control_event(EVENT_GOT_SIGNAL, "650 SIGNAL %s\r\n",
1588  signal_string);
1589  return 0;
1590 }
1591 
1592 /** Called when a single local_routerstatus_t has changed: Sends an NS event
1593  * to any controller that cares. */
1594 int
1596 {
1597  smartlist_t *statuses;
1598  int r;
1599 
1600  if (!EVENT_IS_INTERESTING(EVENT_NS))
1601  return 0;
1602 
1603  statuses = smartlist_new();
1604  smartlist_add(statuses, (void*)rs);
1606  smartlist_free(statuses);
1607  return r;
1608 }
1609 
1610 /** Our own router descriptor has changed; tell any controllers that care.
1611  */
1612 int
1614 {
1615  send_control_event(EVENT_DESCCHANGED, "650 DESCCHANGED\r\n");
1616  return 0;
1617 }
1618 
1619 /** Helper: sends a status event where <b>type</b> is one of
1620  * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
1621  * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
1622  * string corresponding to <b>args</b>. */
1623 static int
1624 control_event_status(int type, int severity, const char *format, va_list args)
1625 {
1626  char *user_buf = NULL;
1627  char format_buf[160];
1628  const char *status, *sev;
1629 
1630  switch (type) {
1631  case EVENT_STATUS_GENERAL:
1632  status = "STATUS_GENERAL";
1633  break;
1634  case EVENT_STATUS_CLIENT:
1635  status = "STATUS_CLIENT";
1636  break;
1637  case EVENT_STATUS_SERVER:
1638  status = "STATUS_SERVER";
1639  break;
1640  default:
1641  log_warn(LD_BUG, "Unrecognized status type %d", type);
1642  return -1;
1643  }
1644  switch (severity) {
1645  case LOG_NOTICE:
1646  sev = "NOTICE";
1647  break;
1648  case LOG_WARN:
1649  sev = "WARN";
1650  break;
1651  case LOG_ERR:
1652  sev = "ERR";
1653  break;
1654  default:
1655  log_warn(LD_BUG, "Unrecognized status severity %d", severity);
1656  return -1;
1657  }
1658  if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
1659  status, sev)<0) {
1660  log_warn(LD_BUG, "Format string too long.");
1661  return -1;
1662  }
1663  if (tor_vasprintf(&user_buf, format, args)<0) {
1664  log_warn(LD_BUG, "Failed to create user buffer.");
1665  return -1;
1666  }
1667 
1668  send_control_event(type, "%s %s\r\n", format_buf, user_buf);
1669  tor_free(user_buf);
1670  return 0;
1671 }
1672 
1673 #ifndef COCCI
1674 #define CONTROL_EVENT_STATUS_BODY(event, sev) \
1675  int r; \
1676  do { \
1677  va_list ap; \
1678  if (!EVENT_IS_INTERESTING(event)) \
1679  return 0; \
1680  \
1681  va_start(ap, format); \
1682  r = control_event_status((event), (sev), format, ap); \
1683  va_end(ap); \
1684  } while (0)
1685 #endif /* !defined(COCCI) */
1686 
1687 /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
1688  * by formatting the arguments using the printf-style <b>format</b>. */
1689 int
1690 control_event_general_status(int severity, const char *format, ...)
1691 {
1692  CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, severity);
1693  return r;
1694 }
1695 
1696 /** Format and send an EVENT_STATUS_GENERAL LOG_ERR event, and flush it to the
1697  * controller(s) immediately. */
1698 int
1699 control_event_general_error(const char *format, ...)
1700 {
1701  CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, LOG_ERR);
1702  /* Force a flush, since we may be about to die horribly */
1704  return r;
1705 }
1706 
1707 /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
1708  * by formatting the arguments using the printf-style <b>format</b>. */
1709 int
1710 control_event_client_status(int severity, const char *format, ...)
1711 {
1712  CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, severity);
1713  return r;
1714 }
1715 
1716 /** Format and send an EVENT_STATUS_CLIENT LOG_ERR event, and flush it to the
1717  * controller(s) immediately. */
1718 int
1719 control_event_client_error(const char *format, ...)
1720 {
1721  CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, LOG_ERR);
1722  /* Force a flush, since we may be about to die horribly */
1724  return r;
1725 }
1726 
1727 /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
1728  * by formatting the arguments using the printf-style <b>format</b>. */
1729 int
1730 control_event_server_status(int severity, const char *format, ...)
1731 {
1732  CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, severity);
1733  return r;
1734 }
1735 
1736 /** Format and send an EVENT_STATUS_SERVER LOG_ERR event, and flush it to the
1737  * controller(s) immediately. */
1738 int
1739 control_event_server_error(const char *format, ...)
1740 {
1741  CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, LOG_ERR);
1742  /* Force a flush, since we may be about to die horribly */
1744  return r;
1745 }
1746 
1747 /** Called when the status of an entry guard with the given <b>nickname</b>
1748  * and identity <b>digest</b> has changed to <b>status</b>: tells any
1749  * controllers that care. */
1750 int
1751 control_event_guard(const char *nickname, const char *digest,
1752  const char *status)
1753 {
1754  char hbuf[HEX_DIGEST_LEN+1];
1755  base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
1756  if (!EVENT_IS_INTERESTING(EVENT_GUARD))
1757  return 0;
1758 
1759  {
1760  char buf[MAX_VERBOSE_NICKNAME_LEN+1];
1761  const node_t *node = node_get_by_id(digest);
1762  if (node) {
1763  node_get_verbose_nickname(node, buf);
1764  } else {
1765  tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
1766  }
1767  send_control_event(EVENT_GUARD,
1768  "650 GUARD ENTRY %s %s\r\n", buf, status);
1769  }
1770  return 0;
1771 }
1772 
1773 /** Called when a configuration option changes. This is generally triggered
1774  * by SETCONF requests and RELOAD/SIGHUP signals. The <b>changes</b> are
1775  * a linked list of configuration key-values.
1776  * <b>changes</b> can be NULL, meaning "no changes".
1777  */
1778 void
1780 {
1781  char *result;
1782  smartlist_t *lines;
1783  if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) || !changes) {
1784  return;
1785  }
1786  lines = smartlist_new();
1787  for (const config_line_t *line = changes; line; line = line->next) {
1788  if (line->value == NULL) {
1789  smartlist_add_asprintf(lines, "650-%s", line->key);
1790  } else {
1791  smartlist_add_asprintf(lines, "650-%s=%s", line->key, line->value);
1792  }
1793  }
1794  result = smartlist_join_strings(lines, "\r\n", 0, NULL);
1795  send_control_event(EVENT_CONF_CHANGED,
1796  "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
1797  tor_free(result);
1798  SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1799  smartlist_free(lines);
1800 }
1801 
1802 /** We just generated a new summary of which countries we've seen clients
1803  * from recently. Send a copy to the controller in case it wants to
1804  * display it for the user. */
1805 void
1806 control_event_clients_seen(const char *controller_str)
1807 {
1808  send_control_event(EVENT_CLIENTS_SEEN,
1809  "650 CLIENTS_SEEN %s\r\n", controller_str);
1810 }
1811 
1812 /** A new pluggable transport called <b>transport_name</b> was
1813  * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
1814  * "server" or "client" depending on the mode of the pluggable
1815  * transport.
1816  * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
1817  */
1818 void
1819 control_event_transport_launched(const char *mode, const char *transport_name,
1820  tor_addr_t *addr, uint16_t port)
1821 {
1822  send_control_event(EVENT_TRANSPORT_LAUNCHED,
1823  "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
1824  mode, transport_name, fmt_addr(addr), port);
1825 }
1826 
1827 /** A pluggable transport called <b>pt_name</b> has emitted a log message
1828  * found in <b>message</b> at <b>severity</b> log level. */
1829 void
1830 control_event_pt_log(const char *log)
1831 {
1832  send_control_event(EVENT_PT_LOG,
1833  "650 PT_LOG %s\r\n",
1834  log);
1835 }
1836 
1837 /** A pluggable transport has emitted a STATUS message found in
1838  * <b>status</b>. */
1839 void
1840 control_event_pt_status(const char *status)
1841 {
1842  send_control_event(EVENT_PT_STATUS,
1843  "650 PT_STATUS %s\r\n",
1844  status);
1845 }
1846 
1847 /** Convert rendezvous auth type to string for HS_DESC control events
1848  */
1849 const char *
1851 {
1852  const char *str;
1853 
1854  switch (auth_type) {
1855  case REND_NO_AUTH:
1856  str = "NO_AUTH";
1857  break;
1858  case REND_BASIC_AUTH:
1859  str = "BASIC_AUTH";
1860  break;
1861  case REND_STEALTH_AUTH:
1862  str = "STEALTH_AUTH";
1863  break;
1864  default:
1865  str = "UNKNOWN";
1866  }
1867 
1868  return str;
1869 }
1870 
1871 /** Return either the onion address if the given pointer is a non empty
1872  * string else the unknown string. */
1873 static const char *
1874 rend_hsaddress_str_or_unknown(const char *onion_address)
1875 {
1876  static const char *str_unknown = "UNKNOWN";
1877  const char *str_ret = str_unknown;
1878 
1879  /* No valid pointer, unknown it is. */
1880  if (!onion_address) {
1881  goto end;
1882  }
1883  /* Empty onion address thus we don't know, unknown it is. */
1884  if (onion_address[0] == '\0') {
1885  goto end;
1886  }
1887  /* All checks are good so return the given onion address. */
1888  str_ret = onion_address;
1889 
1890  end:
1891  return str_ret;
1892 }
1893 
1894 /** send HS_DESC requested event.
1895  *
1896  * <b>rend_query</b> is used to fetch requested onion address and auth type.
1897  * <b>hs_dir</b> is the description of contacting hs directory.
1898  * <b>desc_id_base32</b> is the ID of requested hs descriptor.
1899  * <b>hsdir_index</b> is the HSDir fetch index value for v3, an hex string.
1900  */
1901 void
1902 control_event_hs_descriptor_requested(const char *onion_address,
1903  rend_auth_type_t auth_type,
1904  const char *id_digest,
1905  const char *desc_id,
1906  const char *hsdir_index)
1907 {
1908  char *hsdir_index_field = NULL;
1909 
1910  if (BUG(!id_digest || !desc_id)) {
1911  return;
1912  }
1913 
1914  if (hsdir_index) {
1915  tor_asprintf(&hsdir_index_field, " HSDIR_INDEX=%s", hsdir_index);
1916  }
1917 
1918  send_control_event(EVENT_HS_DESC,
1919  "650 HS_DESC REQUESTED %s %s %s %s%s\r\n",
1920  rend_hsaddress_str_or_unknown(onion_address),
1921  rend_auth_type_to_string(auth_type),
1922  node_describe_longname_by_id(id_digest),
1923  desc_id,
1924  hsdir_index_field ? hsdir_index_field : "");
1925  tor_free(hsdir_index_field);
1926 }
1927 
1928 /** send HS_DESC CREATED event when a local service generates a descriptor.
1929  *
1930  * <b>onion_address</b> is service address.
1931  * <b>desc_id</b> is the descriptor ID.
1932  * <b>replica</b> is the the descriptor replica number. If it is negative, it
1933  * is ignored.
1934  */
1935 void
1936 control_event_hs_descriptor_created(const char *onion_address,
1937  const char *desc_id,
1938  int replica)
1939 {
1940  char *replica_field = NULL;
1941 
1942  if (BUG(!onion_address || !desc_id)) {
1943  return;
1944  }
1945 
1946  if (replica >= 0) {
1947  tor_asprintf(&replica_field, " REPLICA=%d", replica);
1948  }
1949 
1950  send_control_event(EVENT_HS_DESC,
1951  "650 HS_DESC CREATED %s UNKNOWN UNKNOWN %s%s\r\n",
1952  onion_address, desc_id,
1953  replica_field ? replica_field : "");
1954  tor_free(replica_field);
1955 }
1956 
1957 /** send HS_DESC upload event.
1958  *
1959  * <b>onion_address</b> is service address.
1960  * <b>hs_dir</b> is the description of contacting hs directory.
1961  * <b>desc_id</b> is the ID of requested hs descriptor.
1962  */
1963 void
1964 control_event_hs_descriptor_upload(const char *onion_address,
1965  const char *id_digest,
1966  const char *desc_id,
1967  const char *hsdir_index)
1968 {
1969  char *hsdir_index_field = NULL;
1970 
1971  if (BUG(!onion_address || !id_digest || !desc_id)) {
1972  return;
1973  }
1974 
1975  if (hsdir_index) {
1976  tor_asprintf(&hsdir_index_field, " HSDIR_INDEX=%s", hsdir_index);
1977  }
1978 
1979  send_control_event(EVENT_HS_DESC,
1980  "650 HS_DESC UPLOAD %s UNKNOWN %s %s%s\r\n",
1981  onion_address,
1982  node_describe_longname_by_id(id_digest),
1983  desc_id,
1984  hsdir_index_field ? hsdir_index_field : "");
1985  tor_free(hsdir_index_field);
1986 }
1987 
1988 /** send HS_DESC event after got response from hs directory.
1989  *
1990  * NOTE: this is an internal function used by following functions:
1991  * control_event_hsv2_descriptor_received
1992  * control_event_hsv2_descriptor_failed
1993  * control_event_hsv3_descriptor_failed
1994  *
1995  * So do not call this function directly.
1996  */
1997 static void
1999  const char *onion_address,
2000  const char *desc_id,
2001  rend_auth_type_t auth_type,
2002  const char *hsdir_id_digest,
2003  const char *reason)
2004 {
2005  char *reason_field = NULL;
2006 
2007  if (BUG(!action || !onion_address)) {
2008  return;
2009  }
2010 
2011  if (reason) {
2012  tor_asprintf(&reason_field, " REASON=%s", reason);
2013  }
2014 
2015  send_control_event(EVENT_HS_DESC,
2016  "650 HS_DESC %s %s %s %s%s%s\r\n",
2017  action,
2018  rend_hsaddress_str_or_unknown(onion_address),
2019  rend_auth_type_to_string(auth_type),
2020  hsdir_id_digest ?
2021  node_describe_longname_by_id(hsdir_id_digest) :
2022  "UNKNOWN",
2023  desc_id ? desc_id : "",
2024  reason_field ? reason_field : "");
2025 
2026  tor_free(reason_field);
2027 }
2028 
2029 /** send HS_DESC event after got response from hs directory.
2030  *
2031  * NOTE: this is an internal function used by following functions:
2032  * control_event_hs_descriptor_uploaded
2033  * control_event_hs_descriptor_upload_failed
2034  *
2035  * So do not call this function directly.
2036  */
2037 void
2039  const char *onion_address,
2040  const char *id_digest,
2041  const char *reason)
2042 {
2043  char *reason_field = NULL;
2044 
2045  if (BUG(!action || !id_digest)) {
2046  return;
2047  }
2048 
2049  if (reason) {
2050  tor_asprintf(&reason_field, " REASON=%s", reason);
2051  }
2052 
2053  send_control_event(EVENT_HS_DESC,
2054  "650 HS_DESC %s %s UNKNOWN %s%s\r\n",
2055  action,
2056  rend_hsaddress_str_or_unknown(onion_address),
2057  node_describe_longname_by_id(id_digest),
2058  reason_field ? reason_field : "");
2059 
2060  tor_free(reason_field);
2061 }
2062 
2063 /** For an HS descriptor query <b>rend_data</b>, using the
2064  * <b>onion_address</b> and HSDir fingerprint <b>hsdir_fp</b>, find out
2065  * which descriptor ID in the query is the right one.
2066  *
2067  * Return a pointer of the binary descriptor ID found in the query's object
2068  * or NULL if not found. */
2069 static const char *
2070 get_desc_id_from_query(const rend_data_t *rend_data, const char *hsdir_fp)
2071 {
2072  int replica;
2073  const char *desc_id = NULL;
2074  const rend_data_v2_t *rend_data_v2 = TO_REND_DATA_V2(rend_data);
2075 
2076  /* Possible if the fetch was done using a descriptor ID. This means that
2077  * the HSFETCH command was used. */
2078  if (!tor_digest_is_zero(rend_data_v2->desc_id_fetch)) {
2079  desc_id = rend_data_v2->desc_id_fetch;
2080  goto end;
2081  }
2082 
2083  /* Without a directory fingerprint at this stage, we can't do much. */
2084  if (hsdir_fp == NULL) {
2085  goto end;
2086  }
2087 
2088  /* OK, we have an onion address so now let's find which descriptor ID
2089  * is the one associated with the HSDir fingerprint. */
2090  for (replica = 0; replica < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
2091  replica++) {
2092  const char *digest = rend_data_get_desc_id(rend_data, replica, NULL);
2093 
2094  SMARTLIST_FOREACH_BEGIN(rend_data->hsdirs_fp, char *, fingerprint) {
2095  if (tor_memcmp(fingerprint, hsdir_fp, DIGEST_LEN) == 0) {
2096  /* Found it! This descriptor ID is the right one. */
2097  desc_id = digest;
2098  goto end;
2099  }
2100  } SMARTLIST_FOREACH_END(fingerprint);
2101  }
2102 
2103  end:
2104  return desc_id;
2105 }
2106 
2107 /** send HS_DESC RECEIVED event
2108  *
2109  * called when we successfully received a hidden service descriptor.
2110  */
2111 void
2112 control_event_hsv2_descriptor_received(const char *onion_address,
2113  const rend_data_t *rend_data,
2114  const char *hsdir_id_digest)
2115 {
2116  char *desc_id_field = NULL;
2117  const char *desc_id;
2118 
2119  if (BUG(!rend_data || !hsdir_id_digest || !onion_address)) {
2120  return;
2121  }
2122 
2123  desc_id = get_desc_id_from_query(rend_data, hsdir_id_digest);
2124  if (desc_id != NULL) {
2125  char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
2126  /* Set the descriptor ID digest to base32 so we can send it. */
2127  base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_id,
2128  DIGEST_LEN);
2129  /* Extra whitespace is needed before the value. */
2130  tor_asprintf(&desc_id_field, " %s", desc_id_base32);
2131  }
2132 
2133  event_hs_descriptor_receive_end("RECEIVED", onion_address, desc_id_field,
2134  TO_REND_DATA_V2(rend_data)->auth_type,
2135  hsdir_id_digest, NULL);
2136  tor_free(desc_id_field);
2137 }
2138 
2139 /* Send HS_DESC RECEIVED event
2140  *
2141  * Called when we successfully received a hidden service descriptor. */
2142 void
2143 control_event_hsv3_descriptor_received(const char *onion_address,
2144  const char *desc_id,
2145  const char *hsdir_id_digest)
2146 {
2147  char *desc_id_field = NULL;
2148 
2149  if (BUG(!onion_address || !desc_id || !hsdir_id_digest)) {
2150  return;
2151  }
2152 
2153  /* Because DescriptorID is an optional positional value, we need to add a
2154  * whitespace before in order to not be next to the HsDir value. */
2155  tor_asprintf(&desc_id_field, " %s", desc_id);
2156 
2157  event_hs_descriptor_receive_end("RECEIVED", onion_address, desc_id_field,
2158  REND_NO_AUTH, hsdir_id_digest, NULL);
2159  tor_free(desc_id_field);
2160 }
2161 
2162 /** send HS_DESC UPLOADED event
2163  *
2164  * called when we successfully uploaded a hidden service descriptor.
2165  */
2166 void
2168  const char *onion_address)
2169 {
2170  if (BUG(!id_digest)) {
2171  return;
2172  }
2173 
2174  control_event_hs_descriptor_upload_end("UPLOADED", onion_address,
2175  id_digest, NULL);
2176 }
2177 
2178 /** Send HS_DESC event to inform controller that query <b>rend_data</b>
2179  * failed to retrieve hidden service descriptor from directory identified by
2180  * <b>id_digest</b>. If NULL, "UNKNOWN" is used. If <b>reason</b> is not NULL,
2181  * add it to REASON= field.
2182  */
2183 void
2185  const char *hsdir_id_digest,
2186  const char *reason)
2187 {
2188  char *desc_id_field = NULL;
2189  const char *desc_id;
2190 
2191  if (BUG(!rend_data)) {
2192  return;
2193  }
2194 
2195  desc_id = get_desc_id_from_query(rend_data, hsdir_id_digest);
2196  if (desc_id != NULL) {
2197  char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
2198  /* Set the descriptor ID digest to base32 so we can send it. */
2199  base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_id,
2200  DIGEST_LEN);
2201  /* Extra whitespace is needed before the value. */
2202  tor_asprintf(&desc_id_field, " %s", desc_id_base32);
2203  }
2204 
2206  desc_id_field,
2207  TO_REND_DATA_V2(rend_data)->auth_type,
2208  hsdir_id_digest, reason);
2209  tor_free(desc_id_field);
2210 }
2211 
2212 /** Send HS_DESC event to inform controller that the query to
2213  * <b>onion_address</b> failed to retrieve hidden service descriptor
2214  * <b>desc_id</b> from directory identified by <b>hsdir_id_digest</b>. If
2215  * NULL, "UNKNOWN" is used. If <b>reason</b> is not NULL, add it to REASON=
2216  * field. */
2217 void
2218 control_event_hsv3_descriptor_failed(const char *onion_address,
2219  const char *desc_id,
2220  const char *hsdir_id_digest,
2221  const char *reason)
2222 {
2223  char *desc_id_field = NULL;
2224 
2225  if (BUG(!onion_address || !desc_id || !reason)) {
2226  return;
2227  }
2228 
2229  /* Because DescriptorID is an optional positional value, we need to add a
2230  * whitespace before in order to not be next to the HsDir value. */
2231  tor_asprintf(&desc_id_field, " %s", desc_id);
2232 
2233  event_hs_descriptor_receive_end("FAILED", onion_address, desc_id_field,
2234  REND_NO_AUTH, hsdir_id_digest, reason);
2235  tor_free(desc_id_field);
2236 }
2237 
2238 /** Send HS_DESC_CONTENT event after completion of a successful fetch
2239  * from hs directory. If <b>hsdir_id_digest</b> is NULL, it is replaced
2240  * by "UNKNOWN". If <b>content</b> is NULL, it is replaced by an empty
2241  * string. The <b>onion_address</b> or <b>desc_id</b> set to NULL will
2242  * not trigger the control event. */
2243 void
2244 control_event_hs_descriptor_content(const char *onion_address,
2245  const char *desc_id,
2246  const char *hsdir_id_digest,
2247  const char *content)
2248 {
2249  static const char *event_name = "HS_DESC_CONTENT";
2250  char *esc_content = NULL;
2251 
2252  if (!onion_address || !desc_id) {
2253  log_warn(LD_BUG, "Called with onion_address==%p, desc_id==%p, ",
2254  onion_address, desc_id);
2255  return;
2256  }
2257 
2258  if (content == NULL) {
2259  /* Point it to empty content so it can still be escaped. */
2260  content = "";
2261  }
2262  write_escaped_data(content, strlen(content), &esc_content);
2263 
2264  send_control_event(EVENT_HS_DESC_CONTENT,
2265  "650+%s %s %s %s\r\n%s650 OK\r\n",
2266  event_name,
2267  rend_hsaddress_str_or_unknown(onion_address),
2268  desc_id,
2269  hsdir_id_digest ?
2270  node_describe_longname_by_id(hsdir_id_digest) :
2271  "UNKNOWN",
2272  esc_content);
2273  tor_free(esc_content);
2274 }
2275 
2276 /** Send HS_DESC event to inform controller upload of hidden service
2277  * descriptor identified by <b>id_digest</b> failed. If <b>reason</b>
2278  * is not NULL, add it to REASON= field.
2279  */
2280 void
2282  const char *onion_address,
2283  const char *reason)
2284 {
2285  if (BUG(!id_digest)) {
2286  return;
2287  }
2288  control_event_hs_descriptor_upload_end("FAILED", onion_address,
2289  id_digest, reason);
2290 }
2291 
2292 void
2293 control_events_free_all(void)
2294 {
2295  smartlist_t *queued_events = NULL;
2296 
2297  stats_prev_n_read = stats_prev_n_written = 0;
2298 
2302  queued_events = queued_control_events;
2303  queued_control_events = NULL;
2305  }
2306  if (queued_events) {
2307  SMARTLIST_FOREACH(queued_events, queued_event_t *, ev,
2308  queued_event_free(ev));
2309  smartlist_free(queued_events);
2310  }
2312  mainloop_event_free(flush_queued_events_event);
2314  }
2315  global_event_mask = 0;
2317 }
2318 
2319 #ifdef TOR_UNIT_TESTS
2320 /* For testing: change the value of global_event_mask */
2321 void
2322 control_testing_set_global_event_mask(uint64_t mask)
2323 {
2324  global_event_mask = mask;
2325 }
2326 #endif /* defined(TOR_UNIT_TESTS) */
int control_event_circ_bandwidth_used(void)
uint64_t global_identifier
Definition: channel.h:197
smartlist_t * get_connection_array(void)
Definition: mainloop.c:452
void control_event_clients_seen(const char *controller_str)
int control_event_conn_bandwidth_used(void)
static tor_mutex_t * queued_control_events_lock
Header file for channeltls.c.
Header for confline.c.
static void clear_circ_bw_fields(void)
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)
channel_t * n_chan
Definition: circuit_st.h:68
smartlist_t * testing_cell_stats
Definition: circuit_st.h:211
void tor_mutex_release(tor_mutex_t *m)
int write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
Definition: control_fmt.c:32
Definition: node_st.h:33
void control_event_hs_descriptor_created(const char *onion_address, const char *desc_id, int replica)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define TO_CONN(c)
Definition: or.h:735
int connection_flush(connection_t *conn)
Definition: connection.c:4260
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
Header file for command.c.
void format_local_iso_time(char *buf, time_t t)
Definition: time_fmt.c:285
uint32_t n_written_conn_bw
unsigned int purpose
Definition: connection_st.h:51
Header file for connection.c.
STATIC void queue_control_event_string(uint16_t event, char *msg)
static void static int static void const struct control_event_t control_event_table[]
void smartlist_add_strdup(struct smartlist_t *sl, const char *string)
#define CIRCUIT_IS_ORIGIN(c)
Definition: circuitlist.h:146
int control_event_circuit_cell_stats(void)
#define STATE_IS_OPEN(s)
void control_event_hs_descriptor_upload_end(const char *action, const char *onion_address, const char *id_digest, const char *reason)
#define END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
Definition: or.h:279
static uint64_t stats_n_bytes_written
Definition: mainloop.c:141
static void control_get_bytes_rw_last_sec(uint64_t *r, uint64_t *w)
#define LOG_INFO
Definition: log.h:45
Header file for describe.c.
Header file for nodelist.c.
Header file for directory.c.
void format_cell_stats(char **event_string, circuit_t *circ, cell_stats_t *cell_stats)
int tor_vasprintf(char **strp, const char *fmt, va_list args)
Definition: printf.c:96
void smartlist_add(smartlist_t *sl, void *element)
Header file for control_fmt.c.
const char * circuit_purpose_to_controller_hs_state_string(uint8_t purpose)
Definition: circuitlist.c:841
const char * cell_command_to_string(uint8_t command)
Definition: command.c:88
#define CONTROL_CONN_STATE_OPEN
Definition: control.h:19
OR connection structure.
void circuit_clear_testing_cell_stats(circuit_t *circ)
Definition: circuitlist.c:1109
#define REND_DESC_ID_V2_LEN_BASE32
Definition: or.h:354
int circuit_count_pending_on_channel(channel_t *chan)
Definition: circuitlist.c:607
static tor_threadlocal_t block_event_queue_flag
Header file for config.c.
control_connection_t * TO_CONTROL_CONN(connection_t *c)
Definition: control.c:67
uint32_t n_delivered_read_circ_bw
#define CONN_TYPE_OR
Definition: connection.h:24
char * networkstatus_getinfo_helper_single(const routerstatus_t *rs)
static event_mask_t global_event_mask
const or_options_t * get_options(void)
Definition: config.c:944
#define tor_assert(expr)
Definition: util_bug.h:102
int control_event_stream_bandwidth(edge_connection_t *edge_conn)
void base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:60
void format_iso_time_nospace_usec(char *buf, const struct timeval *tv)
Definition: time_fmt.c:323
uint32_t n_overhead_read_circ_bw
stream_status_event_t
void tor_gettimeofday(struct timeval *timeval)
int control_event_signal(uintptr_t signal_num)
static void static int static void send_control_event(uint16_t event, const char *format,...) CHECK_PRINTF(2
void control_event_pt_status(const char *status)
uint32_t n_overhead_written_circ_bw
uint64_t get_bytes_written(void)
Definition: mainloop.c:474
void control_event_transport_launched(const char *mode, const char *transport_name, tor_addr_t *addr, uint16_t port)
char desc_id_fetch[DIGEST_LEN]
Definition: or.h:454
int control_event_client_error(const char *format,...)
#define tor_free(p)
Definition: malloc.h:52
void enable_control_logging(void)
static void queued_events_flush_all(int force)
#define tor_fragile_assert()
Definition: util_bug.h:246
void control_event_logmsg(int severity, log_domain_mask_t domain, const char *msg)
const char * name
Definition: config.c:2459
#define LOG_NOTICE
Definition: log.h:50
Header file for mainloop.c.
static mainloop_event_t * flush_queued_events_event
void mainloop_event_activate(mainloop_event_t *event)
smartlist_t * smartlist_new(void)
int control_event_descriptors_changed(smartlist_t *routers)
const char * rend_data_get_desc_id(const rend_data_t *rend_data, uint8_t replica, size_t *len_out)
Definition: hs_common.c:545
int in_main_thread(void)
Definition: or.h:923
int control_event_stream_bandwidth_used(void)
int control_event_circ_bandwidth_used_for_circ(origin_circuit_t *ocirc)
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)
edge_connection_t * TO_EDGE_CONN(connection_t *c)
#define STATIC
Definition: testsupport.h:32
rend_auth_type_t
Definition: or.h:402
int control_event_newconsensus(const networkstatus_t *consensus)
#define END_CIRC_REASON_FLAG_REMOTE
Definition: or.h:328
#define ENTRY_TO_CONN(c)
Definition: or.h:738
static void static int control_event_status(int type, int severity, const char *format, va_list args) CHECK_PRINTF(3
smartlist_t * circuit_get_global_list(void)
Definition: circuitlist.c:692
int control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
void flush_pending_log_callbacks(void)
Definition: log.c:1073
void orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
Definition: control_fmt.c:54
int tor_threadlocal_init(tor_threadlocal_t *threadlocal)
buildtimeout_set_event_t
void control_event_hs_descriptor_uploaded(const char *id_digest, const char *onion_address)
int control_event_general_status(int severity, const char *format,...)
void router_get_verbose_nickname(char *buf, const routerinfo_t *router)
Definition: describe.c:226
#define LD_CONTROL
Definition: log.h:80
uint32_t n_delivered_written_circ_bw
#define MAX_VERBOSE_NICKNAME_LEN
Definition: or.h:119
void control_per_second_events(void)
const char * rend_auth_type_to_string(rend_auth_type_t auth_type)
const char * circuit_end_reason_to_control_string(int reason)
Definition: reasons.c:324
int tor_memcmp(const void *a, const void *b, size_t len)
Definition: di_ops.c:31
void sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
const char * stream_end_reason_to_control_string(int reason)
Definition: reasons.c:28
void control_update_global_event_mask(void)
#define DIGEST_LEN
Definition: digest_sizes.h:20
Origin circuit structure.
static void send_control_event_impl(uint16_t event, const char *format, va_list ap) CHECK_PRINTF(2
size_t write_escaped_data(const char *data, size_t len, char **out)
Definition: control_proto.c:69
void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern,...)
Definition: smartlist.c:36
channel_tls_t * chan
static int disable_log_messages
int control_event_general_error(const char *format,...)
int control_event_circuit_purpose_changed(origin_circuit_t *circ, int old_purpose)
char * entry_connection_describe_status_for_controller(const entry_connection_t *conn)
Definition: control_fmt.c:170
Master header file for Tor-specific functionality.
int connection_or_get_num_circuits(or_connection_t *conn)
void change_callback_log_severity(int loglevelMin, int loglevelMax, log_callback cb)
Definition: log.c:1054
void control_event_hs_descriptor_content(const char *onion_address, const char *desc_id, const char *hsdir_id_digest, const char *content)
#define ANY_EVENT_IS_INTERESTING(e)
static int event_to_log_severity(int event)
int control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp, int reason)
int control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp, int reason_code)
void node_get_verbose_nickname(const node_t *node, char *verbose_name_out)
Definition: nodelist.c:1384
#define END_STREAM_REASON_FLAG_REMOTE
Definition: or.h:276
static const char * rend_hsaddress_str_or_unknown(const char *onion_address)
const node_t * node_get_by_id(const char *identity_digest)
Definition: nodelist.c:223
circid_t p_circ_id
Definition: or_circuit_st.h:33
#define LOG_WARN
Definition: log.h:53
Entry connection structure.
uint32_t n_written_circ_bw
struct event_base * tor_libevent_get_base(void)
static int flush_queued_event_pending
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:478
#define CONN_TYPE_CONTROL
Definition: connection.h:40
#define DIR_PURPOSE_IS_UPLOAD(p)
Definition: directory.h:82
char * circuit_describe_status_for_controller(origin_circuit_t *circ)
Definition: control_fmt.c:73
static int log_severity_to_event(int severity)
static void flush_queued_events_cb(mainloop_event_t *event, void *arg)
Header file for circuitlist.c.
void tor_threadlocal_set(tor_threadlocal_t *threadlocal, void *value)
int control_event_client_status(int severity, const char *format,...)
uint64_t get_bytes_read(void)
Definition: mainloop.c:464
#define REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS
Definition: or.h:348
void control_event_hsv2_descriptor_received(const char *onion_address, const rend_data_t *rend_data, const char *hsdir_id_digest)
int tor_digest_is_zero(const char *digest)
Definition: util_string.c:96
uint32_t n_read_conn_bw
smartlist_t * hsdirs_fp
Definition: or.h:424
#define LOG_ERR
Definition: log.h:56
unsigned int type
Definition: connection_st.h:50
int control_event_network_liveness_update(int liveness)
static const char * get_desc_id_from_query(const rend_data_t *rend_data, const char *hsdir_fp)
#define HEX_DIGEST_LEN
Definition: crypto_digest.h:35
#define ENTRY_TO_EDGE_CONN(c)
void control_adjust_event_log_severity(void)
int control_event_networkstatus_changed_single(const routerstatus_t *rs)
uint64_t global_identifier
Header file for connection_edge.c.
origin_circuit_t * TO_ORIGIN_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:166
#define REMAP_STREAM_SOURCE_CACHE
static int control_event_circuit_status_minor(origin_circuit_t *circ, circuit_status_minor_event_t e, int purpose, const struct timeval *tv)
channel_t * p_chan
Definition: or_circuit_st.h:37
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
void format_iso_time(char *buf, time_t t)
Definition: time_fmt.c:295
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition: smartlist.c:279
const char * rend_data_get_address(const rend_data_t *rend_data)
Definition: hs_common.c:527
const char * node_describe_longname_by_id(const char *id_digest)
Definition: control_fmt.c:269
#define SMARTLIST_FOREACH(sl, type, var, cmd)
static uint64_t stats_n_bytes_read
Definition: mainloop.c:139
uint64_t log_domain_mask_t
Definition: logging_types.h:21
mainloop_event_t * mainloop_event_new(void(*cb)(mainloop_event_t *, void *), void *userdata)
void disable_control_logging(void)
smartlist_t * routerstatus_list
#define fmt_addr(a)
Definition: address.h:211
int control_event_is_interesting(int event)
STATIC void send_control_event_string(uint16_t event, const char *msg)
#define CONN_TYPE_EXIT
Definition: connection.h:26
void control_event_pt_log(const char *log)
Controller connection structure.
or_circuit_t * TO_OR_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:154
void control_event_logmsg_pending(void)
Header file for control.c.
void tor_mutex_acquire(tor_mutex_t *m)
void control_event_hs_descriptor_upload_failed(const char *id_digest, const char *onion_address, const char *reason)
static int control_event_networkstatus_changed_helper(smartlist_t *statuses, uint16_t event, const char *event_string)
tor_mutex_t * tor_mutex_new(void)
Definition: compat_mutex.c:17
void control_event_hsv3_descriptor_failed(const char *onion_address, const char *desc_id, const char *hsdir_id_digest, const char *reason)
void rescan_periodic_events(const or_options_t *options)
Definition: mainloop.c:1590
#define LOG_DEBUG
Definition: log.h:42
const char * circuit_purpose_to_controller_string(uint8_t purpose)
Definition: circuitlist.c:780
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)
#define REMAP_STREAM_SOURCE_EXIT
circid_t n_circ_id
Definition: circuit_st.h:77
int control_any_per_second_event_enabled(void)
static void queued_event_free_(queued_event_t *ev)
Header file for control_proto.c.
int control_event_server_error(const char *format,...)
Header file for reasons.c.
void * tor_threadlocal_get(tor_threadlocal_t *threadlocal)
#define CONN_TYPE_DIR
Definition: connection.h:35
circuit_t * circuit_get_by_edge_conn(edge_connection_t *conn)
Definition: circuitlist.c:1578
Header file for connection_or.c.
int control_event_server_status(int severity, const char *format,...)
char * esc_for_log(const char *s)
Definition: escape.c:30
void control_event_conf_changed(const config_line_t *changes)
int control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp, int reason_code)
Header for compat_libevent.c.
#define CONN_TYPE_AP
Definition: connection.h:31
or_conn_status_event_t
Definition: orconn_event.h:59
socks_request_t * socks_request
Header file for control_events.c.
void control_event_hs_descriptor_upload(const char *onion_address, const char *id_digest, const char *desc_id, const char *hsdir_index)
const char * orconn_end_reason_to_control_string(int r)
Definition: reasons.c:225
int control_event_guard(const char *nickname, const char *digest, const char *status)
#define EVENT_IS_INTERESTING(e)
int control_event_address_mapped(const char *from, const char *to, time_t expires, const char *error, const int cached)
Header file for networkstatus.c.
#define LD_BUG
Definition: log.h:86
int control_event_my_descriptor_changed(void)
circuit_status_minor_event_t
int control_event_networkstatus_changed(smartlist_t *statuses)
static smartlist_t * queued_control_events
int control_event_circuit_cannibalized(origin_circuit_t *circ, int old_purpose, const struct timeval *old_tv_created)
int control_event_buildtimeout_set(buildtimeout_set_event_t type, const char *args)
circuit_status_event_t
Definition: ocirc_event.h:19
Networkstatus consensus/vote structure.
void control_event_hsv2_descriptor_failed(const rend_data_t *rend_data, const char *hsdir_id_digest, const char *reason)
int control_event_conn_bandwidth(connection_t *conn)