Tor  0.4.8.0-alpha-dev
channel.c
Go to the documentation of this file.
1 /* * Copyright (c) 2012-2021, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
3 
4 /**
5  * \file channel.c
6  *
7  * \brief OR/OP-to-OR channel abstraction layer. A channel's job is to
8  * transfer cells from Tor instance to Tor instance. Currently, there is only
9  * one implementation of the channel abstraction: in channeltls.c.
10  *
11  * Channels are a higher-level abstraction than or_connection_t: In general,
12  * any means that two Tor relays use to exchange cells, or any means that a
13  * relay and a client use to exchange cells, is a channel.
14  *
15  * Channels differ from pluggable transports in that they do not wrap an
16  * underlying protocol over which cells are transmitted: they <em>are</em> the
17  * underlying protocol.
18  *
19  * This module defines the generic parts of the channel_t interface, and
20  * provides the machinery necessary for specialized implementations to be
21  * created. At present, there is one specialized implementation in
22  * channeltls.c, which uses connection_or.c to send cells over a TLS
23  * connection.
24  *
25  * Every channel implementation is responsible for being able to transmit
26  * cells that are passed to it
27  *
28  * For *inbound* cells, the entry point is: channel_process_cell(). It takes a
29  * cell and will pass it to the cell handler set by
30  * channel_set_cell_handlers(). Currently, this is passed back to the command
31  * subsystem which is command_process_cell().
32  *
33  * NOTE: For now, the separation between channels and specialized channels
34  * (like channeltls) is not that well defined. So the channeltls layer calls
35  * channel_process_cell() which originally comes from the connection subsystem.
36  * This should be hopefully be fixed with #23993.
37  *
38  * For *outbound* cells, the entry point is: channel_write_packed_cell().
39  * Only packed cells are dequeued from the circuit queue by the scheduler
40  * which uses channel_flush_from_first_active_circuit() to decide which cells
41  * to flush from which circuit on the channel. They are then passed down to
42  * the channel subsystem. This calls the low layer with the function pointer
43  * .write_packed_cell().
44  *
45  * Each specialized channel (currently only channeltls_t) MUST implement a
46  * series of function found in channel_t. See channel.h for more
47  * documentation.
48  **/
49 
50 /*
51  * Define this so channel.h gives us things only channel_t subclasses
52  * should touch.
53  */
54 #define CHANNEL_OBJECT_PRIVATE
55 
56 /* This one's for stuff only channel.c and the test suite should see */
57 #define CHANNEL_FILE_PRIVATE
58 
59 #include "core/or/or.h"
60 #include "app/config/config.h"
61 #include "core/mainloop/mainloop.h"
62 #include "core/or/channel.h"
63 #include "core/or/channelpadding.h"
64 #include "core/or/channeltls.h"
65 #include "core/or/circuitbuild.h"
66 #include "core/or/circuitlist.h"
67 #include "core/or/circuitmux.h"
68 #include "core/or/circuitstats.h"
69 #include "core/or/connection_or.h" /* For var_cell_free() */
70 #include "core/or/dos.h"
71 #include "core/or/relay.h"
72 #include "core/or/scheduler.h"
74 #include "feature/hs/hs_service.h"
79 #include "feature/relay/router.h"
81 #include "feature/stats/rephist.h"
82 #include "lib/evloop/timers.h"
83 #include "lib/time/compat_time.h"
84 
85 #include "core/or/cell_queue_st.h"
86 
87 /* Global lists of channels */
88 
89 /* All channel_t instances */
90 static smartlist_t *all_channels = NULL;
91 
92 /* All channel_t instances not in ERROR or CLOSED states */
93 static smartlist_t *active_channels = NULL;
94 
95 /* All channel_t instances in ERROR or CLOSED states */
96 static smartlist_t *finished_channels = NULL;
97 
98 /* All channel_listener_t instances */
99 static smartlist_t *all_listeners = NULL;
100 
101 /* All channel_listener_t instances in LISTENING state */
102 static smartlist_t *active_listeners = NULL;
103 
104 /* All channel_listener_t instances in LISTENING state */
105 static smartlist_t *finished_listeners = NULL;
106 
107 /** Map from channel->global_identifier to channel. Contains the same
108  * elements as all_channels. */
109 static HT_HEAD(channel_gid_map, channel_t) channel_gid_map = HT_INITIALIZER();
110 
111 static unsigned
112 channel_id_hash(const channel_t *chan)
113 {
114  return (unsigned) chan->global_identifier;
115 }
116 static int
117 channel_id_eq(const channel_t *a, const channel_t *b)
118 {
119  return a->global_identifier == b->global_identifier;
120 }
121 HT_PROTOTYPE(channel_gid_map, channel_t, gidmap_node,
122  channel_id_hash, channel_id_eq);
123 HT_GENERATE2(channel_gid_map, channel_t, gidmap_node,
124  channel_id_hash, channel_id_eq,
126 
127 HANDLE_IMPL(channel, channel_t,)
128 
129 /* Counter for ID numbers */
130 static uint64_t n_channels_allocated = 0;
131 
132 /* Digest->channel map
133  *
134  * Similar to the one used in connection_or.c, this maps from the identity
135  * digest of a remote endpoint to a channel_t to that endpoint. Channels
136  * should be placed here when registered and removed when they close or error.
137  * If more than one channel exists, follow the next_with_same_id pointer
138  * as a linked list.
139  */
140 static HT_HEAD(channel_idmap, channel_idmap_entry_t) channel_identity_map =
141  HT_INITIALIZER();
142 
143 typedef struct channel_idmap_entry_t {
144  HT_ENTRY(channel_idmap_entry_t) node;
145  uint8_t digest[DIGEST_LEN];
146  TOR_LIST_HEAD(channel_list_t, channel_t) channel_list;
147 } channel_idmap_entry_t;
148 
149 static inline unsigned
150 channel_idmap_hash(const channel_idmap_entry_t *ent)
151 {
152  return (unsigned) siphash24g(ent->digest, DIGEST_LEN);
153 }
154 
155 static inline int
156 channel_idmap_eq(const channel_idmap_entry_t *a,
157  const channel_idmap_entry_t *b)
158 {
159  return tor_memeq(a->digest, b->digest, DIGEST_LEN);
160 }
161 
162 HT_PROTOTYPE(channel_idmap, channel_idmap_entry_t, node, channel_idmap_hash,
163  channel_idmap_eq);
164 HT_GENERATE2(channel_idmap, channel_idmap_entry_t, node, channel_idmap_hash,
165  channel_idmap_eq, 0.5, tor_reallocarray_, tor_free_);
166 
167 /* Functions to maintain the digest map */
168 static void channel_remove_from_digest_map(channel_t *chan);
169 
170 static void channel_force_xfree(channel_t *chan);
171 static void channel_free_list(smartlist_t *channels,
172  int mark_for_close);
173 static void channel_listener_free_list(smartlist_t *channels,
174  int mark_for_close);
176 
177 /***********************************
178  * Channel state utility functions *
179  **********************************/
180 
181 /**
182  * Indicate whether a given channel state is valid.
183  */
184 int
186 {
187  int is_valid;
188 
189  switch (state) {
192  case CHANNEL_STATE_ERROR:
193  case CHANNEL_STATE_MAINT:
195  case CHANNEL_STATE_OPEN:
196  is_valid = 1;
197  break;
198  case CHANNEL_STATE_LAST:
199  default:
200  is_valid = 0;
201  }
202 
203  return is_valid;
204 }
205 
206 /**
207  * Indicate whether a given channel listener state is valid.
208  */
209 int
211 {
212  int is_valid;
213 
214  switch (state) {
219  is_valid = 1;
220  break;
222  default:
223  is_valid = 0;
224  }
225 
226  return is_valid;
227 }
228 
229 /**
230  * Indicate whether a channel state transition is valid.
231  *
232  * This function takes two channel states and indicates whether a
233  * transition between them is permitted (see the state definitions and
234  * transition table in or.h at the channel_state_t typedef).
235  */
236 int
238 {
239  int is_valid;
240 
241  switch (from) {
243  is_valid = (to == CHANNEL_STATE_OPENING);
244  break;
246  is_valid = (to == CHANNEL_STATE_CLOSED ||
247  to == CHANNEL_STATE_ERROR);
248  break;
249  case CHANNEL_STATE_ERROR:
250  is_valid = 0;
251  break;
252  case CHANNEL_STATE_MAINT:
253  is_valid = (to == CHANNEL_STATE_CLOSING ||
254  to == CHANNEL_STATE_ERROR ||
255  to == CHANNEL_STATE_OPEN);
256  break;
258  is_valid = (to == CHANNEL_STATE_CLOSING ||
259  to == CHANNEL_STATE_ERROR ||
260  to == CHANNEL_STATE_OPEN);
261  break;
262  case CHANNEL_STATE_OPEN:
263  is_valid = (to == CHANNEL_STATE_CLOSING ||
264  to == CHANNEL_STATE_ERROR ||
265  to == CHANNEL_STATE_MAINT);
266  break;
267  case CHANNEL_STATE_LAST:
268  default:
269  is_valid = 0;
270  }
271 
272  return is_valid;
273 }
274 
275 /**
276  * Indicate whether a channel listener state transition is valid.
277  *
278  * This function takes two channel listener states and indicates whether a
279  * transition between them is permitted (see the state definitions and
280  * transition table in or.h at the channel_listener_state_t typedef).
281  */
282 int
285 {
286  int is_valid;
287 
288  switch (from) {
290  is_valid = (to == CHANNEL_LISTENER_STATE_LISTENING);
291  break;
293  is_valid = (to == CHANNEL_LISTENER_STATE_CLOSED ||
295  break;
297  is_valid = 0;
298  break;
300  is_valid = (to == CHANNEL_LISTENER_STATE_CLOSING ||
302  break;
304  default:
305  is_valid = 0;
306  }
307 
308  return is_valid;
309 }
310 
311 /**
312  * Return a human-readable description for a channel state.
313  */
314 const char *
316 {
317  const char *descr;
318 
319  switch (state) {
321  descr = "closed";
322  break;
324  descr = "closing";
325  break;
326  case CHANNEL_STATE_ERROR:
327  descr = "channel error";
328  break;
329  case CHANNEL_STATE_MAINT:
330  descr = "temporarily suspended for maintenance";
331  break;
333  descr = "opening";
334  break;
335  case CHANNEL_STATE_OPEN:
336  descr = "open";
337  break;
338  case CHANNEL_STATE_LAST:
339  default:
340  descr = "unknown or invalid channel state";
341  }
342 
343  return descr;
344 }
345 
346 /**
347  * Return a human-readable description for a channel listener state.
348  */
349 const char *
351 {
352  const char *descr;
353 
354  switch (state) {
356  descr = "closed";
357  break;
359  descr = "closing";
360  break;
362  descr = "channel listener error";
363  break;
365  descr = "listening";
366  break;
368  default:
369  descr = "unknown or invalid channel listener state";
370  }
371 
372  return descr;
373 }
374 
375 /***************************************
376  * Channel registration/unregistration *
377  ***************************************/
378 
379 /**
380  * Register a channel.
381  *
382  * This function registers a newly created channel in the global lists/maps
383  * of active channels.
384  */
385 void
387 {
388  tor_assert(chan);
390 
391  /* No-op if already registered */
392  if (chan->registered) return;
393 
394  log_debug(LD_CHANNEL,
395  "Registering channel %p (ID %"PRIu64 ") "
396  "in state %s (%d) with digest %s",
397  chan, (chan->global_identifier),
398  channel_state_to_string(chan->state), chan->state,
400 
401  /* Make sure we have all_channels, then add it */
402  if (!all_channels) all_channels = smartlist_new();
403  smartlist_add(all_channels, chan);
404  channel_t *oldval = HT_REPLACE(channel_gid_map, &channel_gid_map, chan);
405  tor_assert(! oldval);
406 
407  /* Is it finished? */
408  if (CHANNEL_FINISHED(chan)) {
409  /* Put it in the finished list, creating it if necessary */
410  if (!finished_channels) finished_channels = smartlist_new();
411  smartlist_add(finished_channels, chan);
413  } else {
414  /* Put it in the active list, creating it if necessary */
415  if (!active_channels) active_channels = smartlist_new();
416  smartlist_add(active_channels, chan);
417 
418  if (!CHANNEL_IS_CLOSING(chan)) {
419  /* It should have a digest set */
420  if (!tor_digest_is_zero(chan->identity_digest)) {
421  /* Yeah, we're good, add it to the map */
423  } else {
424  log_info(LD_CHANNEL,
425  "Channel %p (global ID %"PRIu64 ") "
426  "in state %s (%d) registered with no identity digest",
427  chan, (chan->global_identifier),
428  channel_state_to_string(chan->state), chan->state);
429  }
430  }
431  }
432 
433  /* Mark it as registered */
434  chan->registered = 1;
435 }
436 
437 /**
438  * Unregister a channel.
439  *
440  * This function removes a channel from the global lists and maps and is used
441  * when freeing a closed/errored channel.
442  */
443 void
445 {
446  tor_assert(chan);
447 
448  /* No-op if not registered */
449  if (!(chan->registered)) return;
450 
451  /* Is it finished? */
452  if (CHANNEL_FINISHED(chan)) {
453  /* Get it out of the finished list */
454  if (finished_channels) smartlist_remove(finished_channels, chan);
455  } else {
456  /* Get it out of the active list */
457  if (active_channels) smartlist_remove(active_channels, chan);
458  }
459 
460  /* Get it out of all_channels */
461  if (all_channels) smartlist_remove(all_channels, chan);
462  channel_t *oldval = HT_REMOVE(channel_gid_map, &channel_gid_map, chan);
463  tor_assert(oldval == NULL || oldval == chan);
464 
465  /* Mark it as unregistered */
466  chan->registered = 0;
467 
468  /* Should it be in the digest map? */
469  if (!tor_digest_is_zero(chan->identity_digest) &&
470  !(CHANNEL_CONDEMNED(chan))) {
471  /* Remove it */
473  }
474 }
475 
476 /**
477  * Register a channel listener.
478  *
479  * This function registers a newly created channel listener in the global
480  * lists/maps of active channel listeners.
481  */
482 void
484 {
485  tor_assert(chan_l);
486 
487  /* No-op if already registered */
488  if (chan_l->registered) return;
489 
490  log_debug(LD_CHANNEL,
491  "Registering channel listener %p (ID %"PRIu64 ") "
492  "in state %s (%d)",
493  chan_l, (chan_l->global_identifier),
495  chan_l->state);
496 
497  /* Make sure we have all_listeners, then add it */
498  if (!all_listeners) all_listeners = smartlist_new();
499  smartlist_add(all_listeners, chan_l);
500 
501  /* Is it finished? */
502  if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
503  chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
504  /* Put it in the finished list, creating it if necessary */
505  if (!finished_listeners) finished_listeners = smartlist_new();
506  smartlist_add(finished_listeners, chan_l);
507  } else {
508  /* Put it in the active list, creating it if necessary */
509  if (!active_listeners) active_listeners = smartlist_new();
510  smartlist_add(active_listeners, chan_l);
511  }
512 
513  /* Mark it as registered */
514  chan_l->registered = 1;
515 }
516 
517 /**
518  * Unregister a channel listener.
519  *
520  * This function removes a channel listener from the global lists and maps
521  * and is used when freeing a closed/errored channel listener.
522  */
523 void
525 {
526  tor_assert(chan_l);
527 
528  /* No-op if not registered */
529  if (!(chan_l->registered)) return;
530 
531  /* Is it finished? */
532  if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
533  chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
534  /* Get it out of the finished list */
535  if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
536  } else {
537  /* Get it out of the active list */
538  if (active_listeners) smartlist_remove(active_listeners, chan_l);
539  }
540 
541  /* Get it out of all_listeners */
542  if (all_listeners) smartlist_remove(all_listeners, chan_l);
543 
544  /* Mark it as unregistered */
545  chan_l->registered = 0;
546 }
547 
548 /*********************************
549  * Channel digest map maintenance
550  *********************************/
551 
552 /**
553  * Add a channel to the digest map.
554  *
555  * This function adds a channel to the digest map and inserts it into the
556  * correct linked list if channels with that remote endpoint identity digest
557  * already exist.
558  */
559 STATIC void
561 {
562  channel_idmap_entry_t *ent, search;
563 
564  tor_assert(chan);
565 
566  /* Assert that the state makes sense */
567  tor_assert(!CHANNEL_CONDEMNED(chan));
568 
569  /* Assert that there is a digest */
571 
572  memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
573  ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
574  if (! ent) {
575  ent = tor_malloc(sizeof(channel_idmap_entry_t));
576  memcpy(ent->digest, chan->identity_digest, DIGEST_LEN);
577  TOR_LIST_INIT(&ent->channel_list);
578  HT_INSERT(channel_idmap, &channel_identity_map, ent);
579  }
580  TOR_LIST_INSERT_HEAD(&ent->channel_list, chan, next_with_same_id);
581 
582  log_debug(LD_CHANNEL,
583  "Added channel %p (global ID %"PRIu64 ") "
584  "to identity map in state %s (%d) with digest %s",
585  chan, (chan->global_identifier),
586  channel_state_to_string(chan->state), chan->state,
588 }
589 
590 /**
591  * Remove a channel from the digest map.
592  *
593  * This function removes a channel from the digest map and the linked list of
594  * channels for that digest if more than one exists.
595  */
596 static void
598 {
599  channel_idmap_entry_t *ent, search;
600 
601  tor_assert(chan);
602 
603  /* Assert that there is a digest */
605 
606  /* Pull it out of its list, wherever that list is */
607  TOR_LIST_REMOVE(chan, next_with_same_id);
608 
609  memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
610  ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
611 
612  /* Look for it in the map */
613  if (ent) {
614  /* Okay, it's here */
615 
616  if (TOR_LIST_EMPTY(&ent->channel_list)) {
617  HT_REMOVE(channel_idmap, &channel_identity_map, ent);
618  tor_free(ent);
619  }
620 
621  log_debug(LD_CHANNEL,
622  "Removed channel %p (global ID %"PRIu64 ") from "
623  "identity map in state %s (%d) with digest %s",
624  chan, (chan->global_identifier),
625  channel_state_to_string(chan->state), chan->state,
627  } else {
628  /* Shouldn't happen */
629  log_warn(LD_BUG,
630  "Trying to remove channel %p (global ID %"PRIu64 ") with "
631  "digest %s from identity map, but couldn't find any with "
632  "that digest",
633  chan, (chan->global_identifier),
635  }
636 }
637 
638 /****************************
639  * Channel lookup functions *
640  ***************************/
641 
642 /**
643  * Find channel by global ID.
644  *
645  * This function searches for a channel by the global_identifier assigned
646  * at initialization time. This identifier is unique for the lifetime of the
647  * Tor process.
648  */
649 channel_t *
650 channel_find_by_global_id(uint64_t global_identifier)
651 {
652  channel_t lookup;
653  channel_t *rv = NULL;
654 
655  lookup.global_identifier = global_identifier;
656  rv = HT_FIND(channel_gid_map, &channel_gid_map, &lookup);
657  if (rv) {
658  tor_assert(rv->global_identifier == global_identifier);
659  }
660 
661  return rv;
662 }
663 
664 /** Return true iff <b>chan</b> matches <b>rsa_id_digest</b> and <b>ed_id</b>.
665  * as its identity keys. If either is NULL, do not check for a match. */
666 int
668  const char *rsa_id_digest,
669  const ed25519_public_key_t *ed_id)
670 {
671  if (BUG(!chan))
672  return 0;
673  if (rsa_id_digest) {
674  if (tor_memneq(rsa_id_digest, chan->identity_digest, DIGEST_LEN))
675  return 0;
676  }
677  if (ed_id) {
678  if (tor_memneq(ed_id->pubkey, chan->ed25519_identity.pubkey,
680  return 0;
681  }
682  return 1;
683 }
684 
685 /**
686  * Find channel by RSA/Ed25519 identity of of the remote endpoint.
687  *
688  * This function looks up a channel by the digest of its remote endpoint's RSA
689  * identity key. If <b>ed_id</b> is provided and nonzero, only a channel
690  * matching the <b>ed_id</b> will be returned.
691  *
692  * It's possible that more than one channel to a given endpoint exists. Use
693  * channel_next_with_rsa_identity() to walk the list of channels; make sure
694  * to test for Ed25519 identity match too (as appropriate)
695  */
696 channel_t *
697 channel_find_by_remote_identity(const char *rsa_id_digest,
698  const ed25519_public_key_t *ed_id)
699 {
700  channel_t *rv = NULL;
701  channel_idmap_entry_t *ent, search;
702 
703  tor_assert(rsa_id_digest); /* For now, we require that every channel have
704  * an RSA identity, and that every lookup
705  * contain an RSA identity */
706  if (ed_id && ed25519_public_key_is_zero(ed_id)) {
707  /* Treat zero as meaning "We don't care about the presence or absence of
708  * an Ed key", not "There must be no Ed key". */
709  ed_id = NULL;
710  }
711 
712  memcpy(search.digest, rsa_id_digest, DIGEST_LEN);
713  ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
714  if (ent) {
715  rv = TOR_LIST_FIRST(&ent->channel_list);
716  }
717  while (rv && ! channel_remote_identity_matches(rv, rsa_id_digest, ed_id)) {
719  }
720 
721  return rv;
722 }
723 
724 /**
725  * Get next channel with digest.
726  *
727  * This function takes a channel and finds the next channel in the list
728  * with the same digest.
729  */
730 channel_t *
732 {
733  tor_assert(chan);
734 
735  return TOR_LIST_NEXT(chan, next_with_same_id);
736 }
737 
738 /**
739  * Relays run this once an hour to look over our list of channels to other
740  * relays. It prints out some statistics if there are multiple connections
741  * to many relays.
742  *
743  * This function is similar to connection_or_set_bad_connections(),
744  * and probably could be adapted to replace it, if it was modified to actually
745  * take action on any of these connections.
746  */
747 void
749 {
750  channel_idmap_entry_t **iter;
751  channel_t *chan;
752  int total_dirauth_connections = 0, total_dirauths = 0;
753  int total_relay_connections = 0, total_relays = 0, total_canonical = 0;
754  int total_half_canonical = 0;
755  int total_gt_one_connection = 0, total_gt_two_connections = 0;
756  int total_gt_four_connections = 0;
757 
758  HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
759  int connections_to_relay = 0;
760  const char *id_digest = (char *) (*iter)->digest;
761 
762  /* Only consider relay connections */
763  if (!connection_or_digest_is_known_relay(id_digest))
764  continue;
765 
766  total_relays++;
767 
768  const bool is_dirauth = router_digest_is_trusted_dir(id_digest);
769  if (is_dirauth)
770  total_dirauths++;
771 
772  for (chan = TOR_LIST_FIRST(&(*iter)->channel_list); chan;
773  chan = channel_next_with_rsa_identity(chan)) {
774 
775  if (CHANNEL_CONDEMNED(chan) || !CHANNEL_IS_OPEN(chan))
776  continue;
777 
778  connections_to_relay++;
779  total_relay_connections++;
780  if (is_dirauth)
781  total_dirauth_connections++;
782 
783  if (chan->is_canonical(chan)) total_canonical++;
784 
785  if (!chan->is_canonical_to_peer && chan->is_canonical(chan)) {
786  total_half_canonical++;
787  }
788  }
789 
790  if (connections_to_relay > 1) total_gt_one_connection++;
791  if (connections_to_relay > 2) total_gt_two_connections++;
792  if (connections_to_relay > 4) total_gt_four_connections++;
793  }
794 
795  /* Don't bother warning about excessive connections unless we have
796  * at least this many connections, total.
797  */
798 #define MIN_RELAY_CONNECTIONS_TO_WARN 25
799  /* If the average number of connections for a regular relay is more than
800  * this, that's too high.
801  */
802 #define MAX_AVG_RELAY_CONNECTIONS 1.5
803  /* If the average number of connections for a dirauth is more than
804  * this, that's too high.
805  */
806 #define MAX_AVG_DIRAUTH_CONNECTIONS 4
807 
808  /* How many connections total would be okay, given the number of
809  * relays and dirauths that we have connections to? */
810  const int max_tolerable_connections = (int)(
811  (total_relays-total_dirauths) * MAX_AVG_RELAY_CONNECTIONS +
812  total_dirauths * MAX_AVG_DIRAUTH_CONNECTIONS);
813 
814  /* If we average 1.5 or more connections per relay, something is wrong */
815  if (total_relays > MIN_RELAY_CONNECTIONS_TO_WARN &&
816  total_relay_connections > max_tolerable_connections) {
817  log_notice(LD_OR,
818  "Your relay has a very large number of connections to other relays. "
819  "Is your outbound address the same as your relay address? "
820  "Found %d connections to authorities, %d connections to %d relays. "
821  "Found %d current canonical connections, "
822  "in %d of which we were a non-canonical peer. "
823  "%d relays had more than 1 connection, %d had more than 2, and "
824  "%d had more than 4 connections.",
825  total_dirauth_connections, total_relay_connections,
826  total_relays, total_canonical, total_half_canonical,
827  total_gt_one_connection, total_gt_two_connections,
828  total_gt_four_connections);
829  } else {
830  log_info(LD_OR, "Performed connection pruning. "
831  "Found %d connections to authorities, %d connections to %d relays. "
832  "Found %d current canonical connections, "
833  "in %d of which we were a non-canonical peer. "
834  "%d relays had more than 1 connection, %d had more than 2, and "
835  "%d had more than 4 connections.",
836  total_dirauth_connections, total_relay_connections,
837  total_relays, total_canonical, total_half_canonical,
838  total_gt_one_connection, total_gt_two_connections,
839  total_gt_four_connections);
840  }
841 }
842 
843 /**
844  * Initialize a channel.
845  *
846  * This function should be called by subclasses to set up some per-channel
847  * variables. I.e., this is the superclass constructor. Before this, the
848  * channel should be allocated with tor_malloc_zero().
849  */
850 void
852 {
853  tor_assert(chan);
854 
855  /* Assign an ID and bump the counter */
856  chan->global_identifier = ++n_channels_allocated;
857 
858  /* Init timestamp */
859  chan->timestamp_last_had_circuits = time(NULL);
860 
861  /* Warn about exhausted circuit IDs no more than hourly. */
863 
864  /* Initialize list entries. */
865  memset(&chan->next_with_same_id, 0, sizeof(chan->next_with_same_id));
866 
867  /* Timestamp it */
869 
870  /* It hasn't been open yet. */
871  chan->has_been_open = 0;
872 
873  /* Scheduler state is idle */
874  chan->scheduler_state = SCHED_CHAN_IDLE;
875 
876  /* Channel is not in the scheduler heap. */
877  chan->sched_heap_idx = -1;
878 
880 }
881 
882 /**
883  * Initialize a channel listener.
884  *
885  * This function should be called by subclasses to set up some per-channel
886  * variables. I.e., this is the superclass constructor. Before this, the
887  * channel listener should be allocated with tor_malloc_zero().
888  */
889 void
891 {
892  tor_assert(chan_l);
893 
894  /* Assign an ID and bump the counter */
895  chan_l->global_identifier = ++n_channels_allocated;
896 
897  /* Timestamp it */
899 }
900 
901 /**
902  * Free a channel; nothing outside of channel.c and subclasses should call
903  * this - it frees channels after they have closed and been unregistered.
904  */
905 void
907 {
908  if (!chan) return;
909 
910  /* It must be closed or errored */
911  tor_assert(CHANNEL_FINISHED(chan));
912 
913  /* It must be deregistered */
914  tor_assert(!(chan->registered));
915 
916  log_debug(LD_CHANNEL,
917  "Freeing channel %"PRIu64 " at %p",
918  (chan->global_identifier), chan);
919 
920  /* Get this one out of the scheduler */
921  scheduler_release_channel(chan);
922 
923  /*
924  * Get rid of cmux policy before we do anything, so cmux policies don't
925  * see channels in weird half-freed states.
926  */
927  if (chan->cmux) {
928  circuitmux_set_policy(chan->cmux, NULL);
929  }
930 
931  /* Remove all timers and associated handle entries now */
932  timer_free(chan->padding_timer);
933  channel_handle_free(chan->timer_handle);
934  channel_handles_clear(chan);
935 
936  /* Call a free method if there is one */
937  if (chan->free_fn) chan->free_fn(chan);
938 
940 
941  /* Get rid of cmux */
942  if (chan->cmux) {
945  circuitmux_free(chan->cmux);
946  chan->cmux = NULL;
947  }
948 
949  tor_free(chan);
950 }
951 
952 /**
953  * Free a channel listener; nothing outside of channel.c and subclasses
954  * should call this - it frees channel listeners after they have closed and
955  * been unregistered.
956  */
957 void
959 {
960  if (!chan_l) return;
961 
962  log_debug(LD_CHANNEL,
963  "Freeing channel_listener_t %"PRIu64 " at %p",
964  (chan_l->global_identifier),
965  chan_l);
966 
967  /* It must be closed or errored */
970  /* It must be deregistered */
971  tor_assert(!(chan_l->registered));
972 
973  /* Call a free method if there is one */
974  if (chan_l->free_fn) chan_l->free_fn(chan_l);
975 
976  tor_free(chan_l);
977 }
978 
979 /**
980  * Free a channel and skip the state/registration asserts; this internal-
981  * use-only function should be called only from channel_free_all() when
982  * shutting down the Tor process.
983  */
984 static void
986 {
987  tor_assert(chan);
988 
989  log_debug(LD_CHANNEL,
990  "Force-freeing channel %"PRIu64 " at %p",
991  (chan->global_identifier), chan);
992 
993  /* Get this one out of the scheduler */
994  scheduler_release_channel(chan);
995 
996  /*
997  * Get rid of cmux policy before we do anything, so cmux policies don't
998  * see channels in weird half-freed states.
999  */
1000  if (chan->cmux) {
1001  circuitmux_set_policy(chan->cmux, NULL);
1002  }
1003 
1004  /* Remove all timers and associated handle entries now */
1005  timer_free(chan->padding_timer);
1006  channel_handle_free(chan->timer_handle);
1007  channel_handles_clear(chan);
1008 
1009  /* Call a free method if there is one */
1010  if (chan->free_fn) chan->free_fn(chan);
1011 
1013 
1014  /* Get rid of cmux */
1015  if (chan->cmux) {
1016  circuitmux_free(chan->cmux);
1017  chan->cmux = NULL;
1018  }
1019 
1020  tor_free(chan);
1021 }
1022 
1023 /**
1024  * Free a channel listener and skip the state/registration asserts; this
1025  * internal-use-only function should be called only from channel_free_all()
1026  * when shutting down the Tor process.
1027  */
1028 static void
1030 {
1031  tor_assert(chan_l);
1032 
1033  log_debug(LD_CHANNEL,
1034  "Force-freeing channel_listener_t %"PRIu64 " at %p",
1035  (chan_l->global_identifier),
1036  chan_l);
1037 
1038  /* Call a free method if there is one */
1039  if (chan_l->free_fn) chan_l->free_fn(chan_l);
1040 
1041  /*
1042  * The incoming list just gets emptied and freed; we request close on
1043  * any channels we find there, but since we got called while shutting
1044  * down they will get deregistered and freed elsewhere anyway.
1045  */
1046  if (chan_l->incoming_list) {
1048  channel_t *, qchan) {
1049  channel_mark_for_close(qchan);
1050  } SMARTLIST_FOREACH_END(qchan);
1051 
1052  smartlist_free(chan_l->incoming_list);
1053  chan_l->incoming_list = NULL;
1054  }
1055 
1056  tor_free(chan_l);
1057 }
1058 
1059 /**
1060  * Set the listener for a channel listener.
1061  *
1062  * This function sets the handler for new incoming channels on a channel
1063  * listener.
1064  */
1065 void
1067  channel_listener_fn_ptr listener)
1068 {
1069  tor_assert(chan_l);
1071 
1072  log_debug(LD_CHANNEL,
1073  "Setting listener callback for channel listener %p "
1074  "(global ID %"PRIu64 ") to %p",
1075  chan_l, (chan_l->global_identifier),
1076  listener);
1077 
1078  chan_l->listener = listener;
1079  if (chan_l->listener) channel_listener_process_incoming(chan_l);
1080 }
1081 
1082 /**
1083  * Return the fixed-length cell handler for a channel.
1084  *
1085  * This function gets the handler for incoming fixed-length cells installed
1086  * on a channel.
1087  */
1088 channel_cell_handler_fn_ptr
1090 {
1091  tor_assert(chan);
1092 
1093  if (CHANNEL_CAN_HANDLE_CELLS(chan))
1094  return chan->cell_handler;
1095 
1096  return NULL;
1097 }
1098 
1099 /**
1100  * Set both cell handlers for a channel.
1101  *
1102  * This function sets both the fixed-length and variable length cell handlers
1103  * for a channel.
1104  */
1105 void
1107  channel_cell_handler_fn_ptr cell_handler)
1108 {
1109  tor_assert(chan);
1110  tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
1111 
1112  log_debug(LD_CHANNEL,
1113  "Setting cell_handler callback for channel %p to %p",
1114  chan, cell_handler);
1115 
1116  /* Change them */
1117  chan->cell_handler = cell_handler;
1118 }
1119 
1120 /*
1121  * On closing channels
1122  *
1123  * There are three functions that close channels, for use in
1124  * different circumstances:
1125  *
1126  * - Use channel_mark_for_close() for most cases
1127  * - Use channel_close_from_lower_layer() if you are connection_or.c
1128  * and the other end closes the underlying connection.
1129  * - Use channel_close_for_error() if you are connection_or.c and
1130  * some sort of error has occurred.
1131  */
1132 
1133 /**
1134  * Mark a channel for closure.
1135  *
1136  * This function tries to close a channel_t; it will go into the CLOSING
1137  * state, and eventually the lower layer should put it into the CLOSED or
1138  * ERROR state. Then, channel_run_cleanup() will eventually free it.
1139  */
1140 void
1142 {
1143  tor_assert(chan != NULL);
1144  tor_assert(chan->close != NULL);
1145 
1146  /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1147  if (CHANNEL_CONDEMNED(chan))
1148  return;
1149 
1150  log_debug(LD_CHANNEL,
1151  "Closing channel %p (global ID %"PRIu64 ") "
1152  "by request",
1153  chan, (chan->global_identifier));
1154 
1155  /* Note closing by request from above */
1156  chan->reason_for_closing = CHANNEL_CLOSE_REQUESTED;
1157 
1158  /* Change state to CLOSING */
1160 
1161  /* Tell the lower layer */
1162  chan->close(chan);
1163 
1164  /*
1165  * It's up to the lower layer to change state to CLOSED or ERROR when we're
1166  * ready; we'll try to free channels that are in the finished list from
1167  * channel_run_cleanup(). The lower layer should do this by calling
1168  * channel_closed().
1169  */
1170 }
1171 
1172 /**
1173  * Mark a channel listener for closure.
1174  *
1175  * This function tries to close a channel_listener_t; it will go into the
1176  * CLOSING state, and eventually the lower layer should put it into the CLOSED
1177  * or ERROR state. Then, channel_run_cleanup() will eventually free it.
1178  */
1179 void
1181 {
1182  tor_assert(chan_l != NULL);
1183  tor_assert(chan_l->close != NULL);
1184 
1185  /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1186  if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
1187  chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1188  chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
1189 
1190  log_debug(LD_CHANNEL,
1191  "Closing channel listener %p (global ID %"PRIu64 ") "
1192  "by request",
1193  chan_l, (chan_l->global_identifier));
1194 
1195  /* Note closing by request from above */
1196  chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_REQUESTED;
1197 
1198  /* Change state to CLOSING */
1200 
1201  /* Tell the lower layer */
1202  chan_l->close(chan_l);
1203 
1204  /*
1205  * It's up to the lower layer to change state to CLOSED or ERROR when we're
1206  * ready; we'll try to free channels that are in the finished list from
1207  * channel_run_cleanup(). The lower layer should do this by calling
1208  * channel_listener_closed().
1209  */
1210 }
1211 
1212 /**
1213  * Close a channel from the lower layer.
1214  *
1215  * Notify the channel code that the channel is being closed due to a non-error
1216  * condition in the lower layer. This does not call the close() method, since
1217  * the lower layer already knows.
1218  */
1219 void
1221 {
1222  tor_assert(chan != NULL);
1223 
1224  /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1225  if (CHANNEL_CONDEMNED(chan))
1226  return;
1227 
1228  log_debug(LD_CHANNEL,
1229  "Closing channel %p (global ID %"PRIu64 ") "
1230  "due to lower-layer event",
1231  chan, (chan->global_identifier));
1232 
1233  /* Note closing by event from below */
1234  chan->reason_for_closing = CHANNEL_CLOSE_FROM_BELOW;
1235 
1236  /* Change state to CLOSING */
1238 }
1239 
1240 /**
1241  * Notify that the channel is being closed due to an error condition.
1242  *
1243  * This function is called by the lower layer implementing the transport
1244  * when a channel must be closed due to an error condition. This does not
1245  * call the channel's close method, since the lower layer already knows.
1246  */
1247 void
1249 {
1250  tor_assert(chan != NULL);
1251 
1252  /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1253  if (CHANNEL_CONDEMNED(chan))
1254  return;
1255 
1256  log_debug(LD_CHANNEL,
1257  "Closing channel %p due to lower-layer error",
1258  chan);
1259 
1260  /* Note closing by event from below */
1261  chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
1262 
1263  /* Change state to CLOSING */
1265 }
1266 
1267 /**
1268  * Notify that the lower layer is finished closing the channel.
1269  *
1270  * This function should be called by the lower layer when a channel
1271  * is finished closing and it should be regarded as inactive and
1272  * freed by the channel code.
1273  */
1274 void
1276 {
1277  tor_assert(chan);
1278  tor_assert(CHANNEL_CONDEMNED(chan));
1279 
1280  /* No-op if already inactive */
1281  if (CHANNEL_FINISHED(chan))
1282  return;
1283 
1284  /* Inform any pending (not attached) circs that they should
1285  * give up. */
1286  if (! chan->has_been_open)
1287  circuit_n_chan_done(chan, 0, 0);
1288 
1289  /* Now close all the attached circuits on it. */
1290  circuit_unlink_all_from_channel(chan, END_CIRC_REASON_CHANNEL_CLOSED);
1291 
1292  if (chan->reason_for_closing != CHANNEL_CLOSE_FOR_ERROR) {
1294  } else {
1296  }
1297 }
1298 
1299 /**
1300  * Clear the identity_digest of a channel.
1301  *
1302  * This function clears the identity digest of the remote endpoint for a
1303  * channel; this is intended for use by the lower layer.
1304  */
1305 void
1307 {
1308  int state_not_in_map;
1309 
1310  tor_assert(chan);
1311 
1312  log_debug(LD_CHANNEL,
1313  "Clearing remote endpoint digest on channel %p with "
1314  "global ID %"PRIu64,
1315  chan, (chan->global_identifier));
1316 
1317  state_not_in_map = CHANNEL_CONDEMNED(chan);
1318 
1319  if (!state_not_in_map && chan->registered &&
1321  /* if it's registered get it out of the digest map */
1323 
1324  memset(chan->identity_digest, 0,
1325  sizeof(chan->identity_digest));
1326 }
1327 
1328 /**
1329  * Set the identity_digest of a channel.
1330  *
1331  * This function sets the identity digest of the remote endpoint for a
1332  * channel; this is intended for use by the lower layer.
1333  */
1334 void
1336  const char *identity_digest,
1337  const ed25519_public_key_t *ed_identity)
1338 {
1339  int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
1340 
1341  tor_assert(chan);
1342 
1343  log_debug(LD_CHANNEL,
1344  "Setting remote endpoint digest on channel %p with "
1345  "global ID %"PRIu64 " to digest %s",
1346  chan, (chan->global_identifier),
1347  identity_digest ?
1348  hex_str(identity_digest, DIGEST_LEN) : "(null)");
1349 
1350  state_not_in_map = CHANNEL_CONDEMNED(chan);
1351 
1352  was_in_digest_map =
1353  !state_not_in_map &&
1354  chan->registered &&
1356  should_be_in_digest_map =
1357  !state_not_in_map &&
1358  chan->registered &&
1359  (identity_digest &&
1360  !tor_digest_is_zero(identity_digest));
1361 
1362  if (was_in_digest_map)
1363  /* We should always remove it; we'll add it back if we're writing
1364  * in a new digest.
1365  */
1367 
1368  if (identity_digest) {
1369  memcpy(chan->identity_digest,
1370  identity_digest,
1371  sizeof(chan->identity_digest));
1372  } else {
1373  memset(chan->identity_digest, 0,
1374  sizeof(chan->identity_digest));
1375  }
1376  if (ed_identity) {
1377  memcpy(&chan->ed25519_identity, ed_identity, sizeof(*ed_identity));
1378  } else {
1379  memset(&chan->ed25519_identity, 0, sizeof(*ed_identity));
1380  }
1381 
1382  /* Put it in the digest map if we should */
1383  if (should_be_in_digest_map)
1385 }
1386 
1387 /**
1388  * Clear the remote end metadata (identity_digest) of a channel.
1389  *
1390  * This function clears all the remote end info from a channel; this is
1391  * intended for use by the lower layer.
1392  */
1393 void
1395 {
1396  int state_not_in_map;
1397 
1398  tor_assert(chan);
1399 
1400  log_debug(LD_CHANNEL,
1401  "Clearing remote endpoint identity on channel %p with "
1402  "global ID %"PRIu64,
1403  chan, (chan->global_identifier));
1404 
1405  state_not_in_map = CHANNEL_CONDEMNED(chan);
1406 
1407  if (!state_not_in_map && chan->registered &&
1409  /* if it's registered get it out of the digest map */
1411 
1412  memset(chan->identity_digest, 0,
1413  sizeof(chan->identity_digest));
1414 }
1415 
1416 /**
1417  * Write to a channel the given packed cell.
1418  *
1419  * Two possible errors can happen. Either the channel is not opened or the
1420  * lower layer (specialized channel) failed to write it. In both cases, it is
1421  * the caller responsibility to free the cell.
1422  */
1423 static int
1425 {
1426  int ret = -1;
1427  size_t cell_bytes;
1428  uint8_t command = packed_cell_get_command(cell, chan->wide_circ_ids);
1429 
1430  tor_assert(chan);
1431  tor_assert(cell);
1432 
1433  /* Assert that the state makes sense for a cell write */
1434  tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
1435 
1436  {
1437  circid_t circ_id;
1438  if (packed_cell_is_destroy(chan, cell, &circ_id)) {
1439  channel_note_destroy_not_pending(chan, circ_id);
1440  }
1441  }
1442 
1443  /* For statistical purposes, figure out how big this cell is */
1444  cell_bytes = get_cell_network_size(chan->wide_circ_ids);
1445 
1446  /* Can we send it right out? If so, try */
1447  if (!CHANNEL_IS_OPEN(chan)) {
1448  goto done;
1449  }
1450 
1451  /* Write the cell on the connection's outbuf. */
1452  if (chan->write_packed_cell(chan, cell) < 0) {
1453  goto done;
1454  }
1455  /* Timestamp for transmission */
1456  channel_timestamp_xmit(chan);
1457  /* Update the counter */
1458  ++(chan->n_cells_xmitted);
1459  chan->n_bytes_xmitted += cell_bytes;
1460  /* Successfully sent the cell. */
1461  ret = 0;
1462 
1463  /* Update padding statistics for the packed codepath.. */
1465  if (command == CELL_PADDING)
1467  if (chan->padding_enabled) {
1469  if (command == CELL_PADDING)
1471  }
1472 
1473  done:
1474  return ret;
1475 }
1476 
1477 /**
1478  * Write a packed cell to a channel.
1479  *
1480  * Write a packed cell to a channel using the write_cell() method. This is
1481  * called by the transport-independent code to deliver a packed cell to a
1482  * channel for transmission.
1483  *
1484  * Return 0 on success else a negative value. In both cases, the caller should
1485  * not access the cell anymore, it is freed both on success and error.
1486  */
1487 int
1489 {
1490  int ret = -1;
1491 
1492  tor_assert(chan);
1493  tor_assert(cell);
1494 
1495  if (CHANNEL_IS_CLOSING(chan)) {
1496  log_debug(LD_CHANNEL, "Discarding %p on closing channel %p with "
1497  "global ID %"PRIu64, cell, chan,
1498  (chan->global_identifier));
1499  goto end;
1500  }
1501  log_debug(LD_CHANNEL,
1502  "Writing %p to channel %p with global ID "
1503  "%"PRIu64, cell, chan, (chan->global_identifier));
1504 
1505  ret = write_packed_cell(chan, cell);
1506 
1507  end:
1508  /* Whatever happens, we free the cell. Either an error occurred or the cell
1509  * was put on the connection outbuf, both cases we have ownership of the
1510  * cell and we free it. */
1511  packed_cell_free(cell);
1512  return ret;
1513 }
1514 
1515 /**
1516  * Change channel state.
1517  *
1518  * This internal and subclass use only function is used to change channel
1519  * state, performing all transition validity checks and whatever actions
1520  * are appropriate to the state transition in question.
1521  */
1522 static void
1524 {
1525  channel_state_t from_state;
1526  unsigned char was_active, is_active;
1527  unsigned char was_in_id_map, is_in_id_map;
1528 
1529  tor_assert(chan);
1530  from_state = chan->state;
1531 
1532  tor_assert(channel_state_is_valid(from_state));
1534  tor_assert(channel_state_can_transition(chan->state, to_state));
1535 
1536  /* Check for no-op transitions */
1537  if (from_state == to_state) {
1538  log_debug(LD_CHANNEL,
1539  "Got no-op transition from \"%s\" to itself on channel %p"
1540  "(global ID %"PRIu64 ")",
1541  channel_state_to_string(to_state),
1542  chan, (chan->global_identifier));
1543  return;
1544  }
1545 
1546  /* If we're going to a closing or closed state, we must have a reason set */
1547  if (to_state == CHANNEL_STATE_CLOSING ||
1548  to_state == CHANNEL_STATE_CLOSED ||
1549  to_state == CHANNEL_STATE_ERROR) {
1550  tor_assert(chan->reason_for_closing != CHANNEL_NOT_CLOSING);
1551  }
1552 
1553  log_debug(LD_CHANNEL,
1554  "Changing state of channel %p (global ID %"PRIu64
1555  ") from \"%s\" to \"%s\"",
1556  chan,
1557  (chan->global_identifier),
1559  channel_state_to_string(to_state));
1560 
1561  chan->state = to_state;
1562 
1563  /* Need to add to the right lists if the channel is registered */
1564  if (chan->registered) {
1565  was_active = !(from_state == CHANNEL_STATE_CLOSED ||
1566  from_state == CHANNEL_STATE_ERROR);
1567  is_active = !(to_state == CHANNEL_STATE_CLOSED ||
1568  to_state == CHANNEL_STATE_ERROR);
1569 
1570  /* Need to take off active list and put on finished list? */
1571  if (was_active && !is_active) {
1572  if (active_channels) smartlist_remove(active_channels, chan);
1573  if (!finished_channels) finished_channels = smartlist_new();
1574  smartlist_add(finished_channels, chan);
1576  }
1577  /* Need to put on active list? */
1578  else if (!was_active && is_active) {
1579  if (finished_channels) smartlist_remove(finished_channels, chan);
1580  if (!active_channels) active_channels = smartlist_new();
1581  smartlist_add(active_channels, chan);
1582  }
1583 
1584  if (!tor_digest_is_zero(chan->identity_digest)) {
1585  /* Now we need to handle the identity map */
1586  was_in_id_map = !(from_state == CHANNEL_STATE_CLOSING ||
1587  from_state == CHANNEL_STATE_CLOSED ||
1588  from_state == CHANNEL_STATE_ERROR);
1589  is_in_id_map = !(to_state == CHANNEL_STATE_CLOSING ||
1590  to_state == CHANNEL_STATE_CLOSED ||
1591  to_state == CHANNEL_STATE_ERROR);
1592 
1593  if (!was_in_id_map && is_in_id_map) channel_add_to_digest_map(chan);
1594  else if (was_in_id_map && !is_in_id_map)
1596  }
1597  }
1598 
1599  /*
1600  * If we're going to a closed/closing state, we don't need scheduling any
1601  * more; in CHANNEL_STATE_MAINT we can't accept writes.
1602  */
1603  if (to_state == CHANNEL_STATE_CLOSING ||
1604  to_state == CHANNEL_STATE_CLOSED ||
1605  to_state == CHANNEL_STATE_ERROR) {
1606  scheduler_release_channel(chan);
1607  } else if (to_state == CHANNEL_STATE_MAINT) {
1609  }
1610 }
1611 
1612 /**
1613  * As channel_change_state_, but change the state to any state but open.
1614  */
1615 void
1617 {
1618  tor_assert(to_state != CHANNEL_STATE_OPEN);
1619  channel_change_state_(chan, to_state);
1620 }
1621 
1622 /**
1623  * As channel_change_state, but change the state to open.
1624  */
1625 void
1627 {
1629 
1630  /* Tell circuits if we opened and stuff */
1632  chan->has_been_open = 1;
1633 }
1634 
1635 /**
1636  * Change channel listener state.
1637  *
1638  * This internal and subclass use only function is used to change channel
1639  * listener state, performing all transition validity checks and whatever
1640  * actions are appropriate to the state transition in question.
1641  */
1642 void
1644  channel_listener_state_t to_state)
1645 {
1646  channel_listener_state_t from_state;
1647  unsigned char was_active, is_active;
1648 
1649  tor_assert(chan_l);
1650  from_state = chan_l->state;
1651 
1655 
1656  /* Check for no-op transitions */
1657  if (from_state == to_state) {
1658  log_debug(LD_CHANNEL,
1659  "Got no-op transition from \"%s\" to itself on channel "
1660  "listener %p (global ID %"PRIu64 ")",
1662  chan_l, (chan_l->global_identifier));
1663  return;
1664  }
1665 
1666  /* If we're going to a closing or closed state, we must have a reason set */
1667  if (to_state == CHANNEL_LISTENER_STATE_CLOSING ||
1668  to_state == CHANNEL_LISTENER_STATE_CLOSED ||
1669  to_state == CHANNEL_LISTENER_STATE_ERROR) {
1670  tor_assert(chan_l->reason_for_closing != CHANNEL_LISTENER_NOT_CLOSING);
1671  }
1672 
1673  log_debug(LD_CHANNEL,
1674  "Changing state of channel listener %p (global ID %"PRIu64
1675  "from \"%s\" to \"%s\"",
1676  chan_l, (chan_l->global_identifier),
1679 
1680  chan_l->state = to_state;
1681 
1682  /* Need to add to the right lists if the channel listener is registered */
1683  if (chan_l->registered) {
1684  was_active = !(from_state == CHANNEL_LISTENER_STATE_CLOSED ||
1685  from_state == CHANNEL_LISTENER_STATE_ERROR);
1686  is_active = !(to_state == CHANNEL_LISTENER_STATE_CLOSED ||
1687  to_state == CHANNEL_LISTENER_STATE_ERROR);
1688 
1689  /* Need to take off active list and put on finished list? */
1690  if (was_active && !is_active) {
1691  if (active_listeners) smartlist_remove(active_listeners, chan_l);
1692  if (!finished_listeners) finished_listeners = smartlist_new();
1693  smartlist_add(finished_listeners, chan_l);
1695  }
1696  /* Need to put on active list? */
1697  else if (!was_active && is_active) {
1698  if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
1699  if (!active_listeners) active_listeners = smartlist_new();
1700  smartlist_add(active_listeners, chan_l);
1701  }
1702  }
1703 
1704  if (to_state == CHANNEL_LISTENER_STATE_CLOSED ||
1705  to_state == CHANNEL_LISTENER_STATE_ERROR) {
1706  tor_assert(!(chan_l->incoming_list) ||
1707  smartlist_len(chan_l->incoming_list) == 0);
1708  }
1709 }
1710 
1711 /* Maximum number of cells that is allowed to flush at once within
1712  * channel_flush_some_cells(). */
1713 #define MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED 256
1714 
1715 /**
1716  * Try to flush cells of the given channel chan up to a maximum of num_cells.
1717  *
1718  * This is called by the scheduler when it wants to flush cells from the
1719  * channel's circuit queue(s) to the connection outbuf (not yet on the wire).
1720  *
1721  * If the channel is not in state CHANNEL_STATE_OPEN, this does nothing and
1722  * will return 0 meaning no cells were flushed.
1723  *
1724  * If num_cells is -1, we'll try to flush up to the maximum cells allowed
1725  * defined in MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED.
1726  *
1727  * On success, the number of flushed cells are returned and it can never be
1728  * above num_cells. If 0 is returned, no cells were flushed either because the
1729  * channel was not opened or we had no cells on the channel. A negative number
1730  * can NOT be sent back.
1731  *
1732  * This function is part of the fast path. */
1733 MOCK_IMPL(ssize_t,
1734 channel_flush_some_cells, (channel_t *chan, ssize_t num_cells))
1735 {
1736  unsigned int unlimited = 0;
1737  ssize_t flushed = 0;
1738  int clamped_num_cells;
1739 
1740  tor_assert(chan);
1741 
1742  if (num_cells < 0) unlimited = 1;
1743  if (!unlimited && num_cells <= flushed) goto done;
1744 
1745  /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
1746  if (CHANNEL_IS_OPEN(chan)) {
1747  if (circuitmux_num_cells(chan->cmux) > 0) {
1748  /* Calculate number of cells, including clamp */
1749  if (unlimited) {
1750  clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
1751  } else {
1752  if (num_cells - flushed >
1753  MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED) {
1754  clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
1755  } else {
1756  clamped_num_cells = (int)(num_cells - flushed);
1757  }
1758  }
1759 
1760  /* Try to get more cells from any active circuits */
1762  chan, clamped_num_cells);
1763  }
1764  }
1765 
1766  done:
1767  return flushed;
1768 }
1769 
1770 /**
1771  * Check if any cells are available.
1772  *
1773  * This is used by the scheduler to know if the channel has more to flush
1774  * after a scheduling round.
1775  */
1776 MOCK_IMPL(int,
1778 {
1779  tor_assert(chan);
1780 
1781  if (circuitmux_num_cells(chan->cmux) > 0) return 1;
1782 
1783  /* Else no */
1784  return 0;
1785 }
1786 
1787 /**
1788  * Notify the channel we're done flushing the output in the lower layer.
1789  *
1790  * Connection.c will call this when we've flushed the output; there's some
1791  * dirreq-related maintenance to do.
1792  */
1793 void
1795 {
1796  tor_assert(chan);
1797 
1798  if (chan->dirreq_id != 0)
1800  DIRREQ_TUNNELED,
1802 }
1803 
1804 /**
1805  * Process the queue of incoming channels on a listener.
1806  *
1807  * Use a listener's registered callback to process as many entries in the
1808  * queue of incoming channels as possible.
1809  */
1810 void
1812 {
1813  tor_assert(listener);
1814 
1815  /*
1816  * CHANNEL_LISTENER_STATE_CLOSING permitted because we drain the queue
1817  * while closing a listener.
1818  */
1820  listener->state == CHANNEL_LISTENER_STATE_CLOSING);
1821  tor_assert(listener->listener);
1822 
1823  log_debug(LD_CHANNEL,
1824  "Processing queue of incoming connections for channel "
1825  "listener %p (global ID %"PRIu64 ")",
1826  listener, (listener->global_identifier));
1827 
1828  if (!(listener->incoming_list)) return;
1829 
1831  channel_t *, chan) {
1832  tor_assert(chan);
1833 
1834  log_debug(LD_CHANNEL,
1835  "Handling incoming channel %p (%"PRIu64 ") "
1836  "for listener %p (%"PRIu64 ")",
1837  chan,
1838  (chan->global_identifier),
1839  listener,
1840  (listener->global_identifier));
1841  /* Make sure this is set correctly */
1842  channel_mark_incoming(chan);
1843  listener->listener(listener, chan);
1844  } SMARTLIST_FOREACH_END(chan);
1845 
1846  smartlist_free(listener->incoming_list);
1847  listener->incoming_list = NULL;
1848 }
1849 
1850 /**
1851  * Take actions required when a channel becomes open.
1852  *
1853  * Handle actions we should do when we know a channel is open; a lot of
1854  * this comes from the old connection_or_set_state_open() of connection_or.c.
1855  *
1856  * Because of this mechanism, future channel_t subclasses should take care
1857  * not to change a channel from CHANNEL_STATE_OPENING to CHANNEL_STATE_OPEN
1858  * until there is positive confirmation that the network is operational.
1859  * In particular, anything UDP-based should not make this transition until a
1860  * packet is received from the other side.
1861  */
1862 void
1864 {
1865  tor_addr_t remote_addr;
1866  int started_here;
1867  time_t now = time(NULL);
1868  int close_origin_circuits = 0;
1869 
1870  tor_assert(chan);
1871 
1872  started_here = channel_is_outgoing(chan);
1873 
1874  if (started_here) {
1877  } else {
1878  /* only report it to the geoip module if it's a client */
1879  if (channel_is_client(chan)) {
1880  if (channel_get_addr_if_possible(chan, &remote_addr)) {
1881  char *transport_name = NULL;
1882  channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
1883  if (chan->get_transport_name(chan, &transport_name) < 0)
1884  transport_name = NULL;
1885 
1887  &remote_addr, transport_name,
1888  now);
1889  /* Notify the DoS subsystem of a new client. */
1890  if (tlschan && tlschan->conn) {
1891  dos_new_client_conn(tlschan->conn, transport_name);
1892  }
1893  tor_free(transport_name);
1894  }
1895  /* Otherwise the underlying transport can't tell us this, so skip it */
1896  }
1897  }
1898 
1899  /* Disable or reduce padding according to user prefs. */
1900  if (chan->padding_enabled || get_options()->ConnectionPadding == 1) {
1901  if (!get_options()->ConnectionPadding) {
1902  /* Disable if torrc disabled */
1904  } else if (hs_service_allow_non_anonymous_connection(get_options()) &&
1906  CHANNELPADDING_SOS_PARAM,
1907  CHANNELPADDING_SOS_DEFAULT, 0, 1)) {
1908  /* Disable if we're using RSOS and the consensus disabled padding
1909  * for RSOS */
1911  } else if (get_options()->ReducedConnectionPadding) {
1912  /* Padding can be forced and/or reduced by clients, regardless of if
1913  * the channel supports it */
1915  }
1916  }
1917 
1918  circuit_n_chan_done(chan, 1, close_origin_circuits);
1919 }
1920 
1921 /**
1922  * Queue an incoming channel on a listener.
1923  *
1924  * Internal and subclass use only function to queue an incoming channel from
1925  * a listener. A subclass of channel_listener_t should call this when a new
1926  * incoming channel is created.
1927  */
1928 void
1930  channel_t *incoming)
1931 {
1932  int need_to_queue = 0;
1933 
1934  tor_assert(listener);
1936  tor_assert(incoming);
1937 
1938  log_debug(LD_CHANNEL,
1939  "Queueing incoming channel %p (global ID %"PRIu64 ") on "
1940  "channel listener %p (global ID %"PRIu64 ")",
1941  incoming, (incoming->global_identifier),
1942  listener, (listener->global_identifier));
1943 
1944  /* Do we need to queue it, or can we just call the listener right away? */
1945  if (!(listener->listener)) need_to_queue = 1;
1946  if (listener->incoming_list &&
1947  (smartlist_len(listener->incoming_list) > 0))
1948  need_to_queue = 1;
1949 
1950  /* If we need to queue and have no queue, create one */
1951  if (need_to_queue && !(listener->incoming_list)) {
1952  listener->incoming_list = smartlist_new();
1953  }
1954 
1955  /* Bump the counter and timestamp it */
1958  ++(listener->n_accepted);
1959 
1960  /* If we don't need to queue, process it right away */
1961  if (!need_to_queue) {
1962  tor_assert(listener->listener);
1963  listener->listener(listener, incoming);
1964  }
1965  /*
1966  * Otherwise, we need to queue; queue and then process the queue if
1967  * we can.
1968  */
1969  else {
1970  tor_assert(listener->incoming_list);
1971  smartlist_add(listener->incoming_list, incoming);
1972  if (listener->listener) channel_listener_process_incoming(listener);
1973  }
1974 }
1975 
1976 /**
1977  * Process a cell from the given channel.
1978  */
1979 void
1981 {
1982  tor_assert(chan);
1983  tor_assert(CHANNEL_IS_CLOSING(chan) || CHANNEL_IS_MAINT(chan) ||
1984  CHANNEL_IS_OPEN(chan));
1985  tor_assert(cell);
1986 
1987  /* Nothing we can do if we have no registered cell handlers */
1988  if (!chan->cell_handler)
1989  return;
1990 
1991  /* Timestamp for receiving */
1992  channel_timestamp_recv(chan);
1993  /* Update received counter. */
1994  ++(chan->n_cells_recved);
1995  chan->n_bytes_recved += get_cell_network_size(chan->wide_circ_ids);
1996 
1997  log_debug(LD_CHANNEL,
1998  "Processing incoming cell_t %p for channel %p (global ID "
1999  "%"PRIu64 ")", cell, chan,
2000  (chan->global_identifier));
2001  chan->cell_handler(chan, cell);
2002 }
2003 
2004 /** If <b>packed_cell</b> on <b>chan</b> is a destroy cell, then set
2005  * *<b>circid_out</b> to its circuit ID, and return true. Otherwise, return
2006  * false. */
2007 /* XXXX Move this function. */
2008 int
2010  const packed_cell_t *packed_cell,
2011  circid_t *circid_out)
2012 {
2013  if (chan->wide_circ_ids) {
2014  if (packed_cell->body[4] == CELL_DESTROY) {
2015  *circid_out = ntohl(get_uint32(packed_cell->body));
2016  return 1;
2017  }
2018  } else {
2019  if (packed_cell->body[2] == CELL_DESTROY) {
2020  *circid_out = ntohs(get_uint16(packed_cell->body));
2021  return 1;
2022  }
2023  }
2024  return 0;
2025 }
2026 
2027 /**
2028  * Send destroy cell on a channel.
2029  *
2030  * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
2031  * onto channel <b>chan</b>. Don't perform range-checking on reason:
2032  * we may want to propagate reasons from other cells.
2033  */
2034 int
2035 channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
2036 {
2037  tor_assert(chan);
2038  if (circ_id == 0) {
2039  log_warn(LD_BUG, "Attempted to send a destroy cell for circID 0 "
2040  "on a channel %"PRIu64 " at %p in state %s (%d)",
2041  (chan->global_identifier),
2042  chan, channel_state_to_string(chan->state),
2043  chan->state);
2044  return 0;
2045  }
2046 
2047  /* Check to make sure we can send on this channel first */
2048  if (!CHANNEL_CONDEMNED(chan) && chan->cmux) {
2049  channel_note_destroy_pending(chan, circ_id);
2050  circuitmux_append_destroy_cell(chan, chan->cmux, circ_id, reason);
2051  log_debug(LD_OR,
2052  "Sending destroy (circID %u) on channel %p "
2053  "(global ID %"PRIu64 ")",
2054  (unsigned)circ_id, chan,
2055  (chan->global_identifier));
2056  } else {
2057  log_warn(LD_BUG,
2058  "Someone called channel_send_destroy() for circID %u "
2059  "on a channel %"PRIu64 " at %p in state %s (%d)",
2060  (unsigned)circ_id, (chan->global_identifier),
2061  chan, channel_state_to_string(chan->state),
2062  chan->state);
2063  }
2064 
2065  return 0;
2066 }
2067 
2068 /**
2069  * Dump channel statistics to the log.
2070  *
2071  * This is called from dumpstats() in main.c and spams the log with
2072  * statistics on channels.
2073  */
2074 void
2075 channel_dumpstats(int severity)
2076 {
2077  if (all_channels && smartlist_len(all_channels) > 0) {
2078  tor_log(severity, LD_GENERAL,
2079  "Dumping statistics about %d channels:",
2080  smartlist_len(all_channels));
2081  tor_log(severity, LD_GENERAL,
2082  "%d are active, and %d are done and waiting for cleanup",
2083  (active_channels != NULL) ?
2084  smartlist_len(active_channels) : 0,
2085  (finished_channels != NULL) ?
2086  smartlist_len(finished_channels) : 0);
2087 
2088  SMARTLIST_FOREACH(all_channels, channel_t *, chan,
2089  channel_dump_statistics(chan, severity));
2090 
2091  tor_log(severity, LD_GENERAL,
2092  "Done spamming about channels now");
2093  } else {
2094  tor_log(severity, LD_GENERAL,
2095  "No channels to dump");
2096  }
2097 }
2098 
2099 /**
2100  * Dump channel listener statistics to the log.
2101  *
2102  * This is called from dumpstats() in main.c and spams the log with
2103  * statistics on channel listeners.
2104  */
2105 void
2107 {
2108  if (all_listeners && smartlist_len(all_listeners) > 0) {
2109  tor_log(severity, LD_GENERAL,
2110  "Dumping statistics about %d channel listeners:",
2111  smartlist_len(all_listeners));
2112  tor_log(severity, LD_GENERAL,
2113  "%d are active and %d are done and waiting for cleanup",
2114  (active_listeners != NULL) ?
2115  smartlist_len(active_listeners) : 0,
2116  (finished_listeners != NULL) ?
2117  smartlist_len(finished_listeners) : 0);
2118 
2119  SMARTLIST_FOREACH(all_listeners, channel_listener_t *, chan_l,
2120  channel_listener_dump_statistics(chan_l, severity));
2121 
2122  tor_log(severity, LD_GENERAL,
2123  "Done spamming about channel listeners now");
2124  } else {
2125  tor_log(severity, LD_GENERAL,
2126  "No channel listeners to dump");
2127  }
2128 }
2129 
2130 /**
2131  * Clean up channels.
2132  *
2133  * This gets called periodically from run_scheduled_events() in main.c;
2134  * it cleans up after closed channels.
2135  */
2136 void
2138 {
2139  channel_t *tmp = NULL;
2140 
2141  /* Check if we need to do anything */
2142  if (!finished_channels || smartlist_len(finished_channels) == 0) return;
2143 
2144  /* Iterate through finished_channels and get rid of them */
2145  SMARTLIST_FOREACH_BEGIN(finished_channels, channel_t *, curr) {
2146  tmp = curr;
2147  /* Remove it from the list */
2148  SMARTLIST_DEL_CURRENT(finished_channels, curr);
2149  /* Also unregister it */
2150  channel_unregister(tmp);
2151  /* ... and free it */
2152  channel_free(tmp);
2153  } SMARTLIST_FOREACH_END(curr);
2154 }
2155 
2156 /**
2157  * Clean up channel listeners.
2158  *
2159  * This gets called periodically from run_scheduled_events() in main.c;
2160  * it cleans up after closed channel listeners.
2161  */
2162 void
2164 {
2165  channel_listener_t *tmp = NULL;
2166 
2167  /* Check if we need to do anything */
2168  if (!finished_listeners || smartlist_len(finished_listeners) == 0) return;
2169 
2170  /* Iterate through finished_channels and get rid of them */
2171  SMARTLIST_FOREACH_BEGIN(finished_listeners, channel_listener_t *, curr) {
2172  tmp = curr;
2173  /* Remove it from the list */
2174  SMARTLIST_DEL_CURRENT(finished_listeners, curr);
2175  /* Also unregister it */
2177  /* ... and free it */
2178  channel_listener_free(tmp);
2179  } SMARTLIST_FOREACH_END(curr);
2180 }
2181 
2182 /**
2183  * Free a list of channels for channel_free_all().
2184  */
2185 static void
2186 channel_free_list(smartlist_t *channels, int mark_for_close)
2187 {
2188  if (!channels) return;
2189 
2190  SMARTLIST_FOREACH_BEGIN(channels, channel_t *, curr) {
2191  /* Deregister and free it */
2192  tor_assert(curr);
2193  log_debug(LD_CHANNEL,
2194  "Cleaning up channel %p (global ID %"PRIu64 ") "
2195  "in state %s (%d)",
2196  curr, (curr->global_identifier),
2197  channel_state_to_string(curr->state), curr->state);
2198  /* Detach circuits early so they can find the channel */
2199  if (curr->cmux) {
2200  circuitmux_detach_all_circuits(curr->cmux, NULL);
2201  }
2202  SMARTLIST_DEL_CURRENT(channels, curr);
2203  channel_unregister(curr);
2204  if (mark_for_close) {
2205  if (!CHANNEL_CONDEMNED(curr)) {
2206  channel_mark_for_close(curr);
2207  }
2208  channel_force_xfree(curr);
2209  } else channel_free(curr);
2210  } SMARTLIST_FOREACH_END(curr);
2211 }
2212 
2213 /**
2214  * Free a list of channel listeners for channel_free_all().
2215  */
2216 static void
2217 channel_listener_free_list(smartlist_t *listeners, int mark_for_close)
2218 {
2219  if (!listeners) return;
2220 
2221  SMARTLIST_FOREACH_BEGIN(listeners, channel_listener_t *, curr) {
2222  /* Deregister and free it */
2223  tor_assert(curr);
2224  log_debug(LD_CHANNEL,
2225  "Cleaning up channel listener %p (global ID %"PRIu64 ") "
2226  "in state %s (%d)",
2227  curr, (curr->global_identifier),
2228  channel_listener_state_to_string(curr->state), curr->state);
2230  if (mark_for_close) {
2231  if (!(curr->state == CHANNEL_LISTENER_STATE_CLOSING ||
2232  curr->state == CHANNEL_LISTENER_STATE_CLOSED ||
2233  curr->state == CHANNEL_LISTENER_STATE_ERROR)) {
2235  }
2237  } else channel_listener_free(curr);
2238  } SMARTLIST_FOREACH_END(curr);
2239 }
2240 
2241 /**
2242  * Close all channels and free everything.
2243  *
2244  * This gets called from tor_free_all() in main.c to clean up on exit.
2245  * It will close all registered channels and free associated storage,
2246  * then free the all_channels, active_channels, listening_channels and
2247  * finished_channels lists and also channel_identity_map.
2248  */
2249 void
2251 {
2252  log_debug(LD_CHANNEL,
2253  "Shutting down channels...");
2254 
2255  /* First, let's go for finished channels */
2256  if (finished_channels) {
2257  channel_free_list(finished_channels, 0);
2258  smartlist_free(finished_channels);
2259  finished_channels = NULL;
2260  }
2261 
2262  /* Now the finished listeners */
2263  if (finished_listeners) {
2264  channel_listener_free_list(finished_listeners, 0);
2265  smartlist_free(finished_listeners);
2266  finished_listeners = NULL;
2267  }
2268 
2269  /* Now all active channels */
2270  if (active_channels) {
2271  channel_free_list(active_channels, 1);
2272  smartlist_free(active_channels);
2273  active_channels = NULL;
2274  }
2275 
2276  /* Now all active listeners */
2277  if (active_listeners) {
2278  channel_listener_free_list(active_listeners, 1);
2279  smartlist_free(active_listeners);
2280  active_listeners = NULL;
2281  }
2282 
2283  /* Now all channels, in case any are left over */
2284  if (all_channels) {
2285  channel_free_list(all_channels, 1);
2286  smartlist_free(all_channels);
2287  all_channels = NULL;
2288  }
2289 
2290  /* Now all listeners, in case any are left over */
2291  if (all_listeners) {
2292  channel_listener_free_list(all_listeners, 1);
2293  smartlist_free(all_listeners);
2294  all_listeners = NULL;
2295  }
2296 
2297  /* Now free channel_identity_map */
2298  log_debug(LD_CHANNEL,
2299  "Freeing channel_identity_map");
2300  /* Geez, anything still left over just won't die ... let it leak then */
2301  HT_CLEAR(channel_idmap, &channel_identity_map);
2302 
2303  /* Same with channel_gid_map */
2304  log_debug(LD_CHANNEL,
2305  "Freeing channel_gid_map");
2306  HT_CLEAR(channel_gid_map, &channel_gid_map);
2307 
2308  log_debug(LD_CHANNEL,
2309  "Done cleaning up after channels");
2310 }
2311 
2312 /**
2313  * Connect to a given addr/port/digest.
2314  *
2315  * This sets up a new outgoing channel; in the future if multiple
2316  * channel_t subclasses are available, this is where the selection policy
2317  * should go. It may also be desirable to fold port into tor_addr_t
2318  * or make a new type including a tor_addr_t and port, so we have a
2319  * single abstract object encapsulating all the protocol details of
2320  * how to contact an OR.
2321  */
2322 channel_t *
2323 channel_connect(const tor_addr_t *addr, uint16_t port,
2324  const char *id_digest,
2325  const ed25519_public_key_t *ed_id)
2326 {
2327  return channel_tls_connect(addr, port, id_digest, ed_id);
2328 }
2329 
2330 /**
2331  * Decide which of two channels to prefer for extending a circuit.
2332  *
2333  * This function is called while extending a circuit and returns true iff
2334  * a is 'better' than b. The most important criterion here is that a
2335  * canonical channel is always better than a non-canonical one, but the
2336  * number of circuits and the age are used as tie-breakers.
2337  *
2338  * This is based on the former connection_or_is_better() of connection_or.c
2339  */
2340 int
2342 {
2343  int a_is_canonical, b_is_canonical;
2344 
2345  tor_assert(a);
2346  tor_assert(b);
2347 
2348  /* If one channel is bad for new circuits, and the other isn't,
2349  * use the one that is still good. */
2351  return 1;
2353  return 0;
2354 
2355  /* Check if one is canonical and the other isn't first */
2356  a_is_canonical = channel_is_canonical(a);
2357  b_is_canonical = channel_is_canonical(b);
2358 
2359  if (a_is_canonical && !b_is_canonical) return 1;
2360  if (!a_is_canonical && b_is_canonical) return 0;
2361 
2362  /* Check if we suspect that one of the channels will be preferred
2363  * by the peer */
2364  if (a->is_canonical_to_peer && !b->is_canonical_to_peer) return 1;
2365  if (!a->is_canonical_to_peer && b->is_canonical_to_peer) return 0;
2366 
2367  /*
2368  * Okay, if we're here they tied on canonicity. Prefer the older
2369  * connection, so that the adversary can't create a new connection
2370  * and try to switch us over to it (which will leak information
2371  * about long-lived circuits). Additionally, switching connections
2372  * too often makes us more vulnerable to attacks like Torscan and
2373  * passive netflow-based equivalents.
2374  *
2375  * Connections will still only live for at most a week, due to
2376  * the check in connection_or_group_set_badness() against
2377  * TIME_BEFORE_OR_CONN_IS_TOO_OLD, which marks old connections as
2378  * unusable for new circuits after 1 week. That check sets
2379  * is_bad_for_new_circs, which is checked in channel_get_for_extend().
2380  *
2381  * We check channel_is_bad_for_new_circs() above here anyway, for safety.
2382  */
2383  if (channel_when_created(a) < channel_when_created(b)) return 1;
2384  else if (channel_when_created(a) > channel_when_created(b)) return 0;
2385 
2386  if (channel_num_circuits(a) > channel_num_circuits(b)) return 1;
2387  else return 0;
2388 }
2389 
2390 /**
2391  * Get a channel to extend a circuit.
2392  *
2393  * Given the desired relay identity, pick a suitable channel to extend a
2394  * circuit to the target IPv4 or IPv6 address requested by the client. Search
2395  * for an existing channel for the requested endpoint. Make sure the channel
2396  * is usable for new circuits, and matches one of the target addresses.
2397  *
2398  * Try to return the best channel. But if there is no good channel, set
2399  * *msg_out to a message describing the channel's state and our next action,
2400  * and set *launch_out to a boolean indicated whether the caller should try to
2401  * launch a new channel with channel_connect().
2402  *
2403  * If `for_origin_circ` is set, mark the channel as interesting for origin
2404  * circuits, and therefore interesting for our bootstrapping reports.
2405  */
2407 channel_get_for_extend,(const char *rsa_id_digest,
2408  const ed25519_public_key_t *ed_id,
2409  const tor_addr_t *target_ipv4_addr,
2410  const tor_addr_t *target_ipv6_addr,
2411  bool for_origin_circ,
2412  const char **msg_out,
2413  int *launch_out))
2414 {
2415  channel_t *chan, *best = NULL;
2416  int n_inprogress_goodaddr = 0, n_old = 0;
2417  int n_noncanonical = 0;
2418 
2419  tor_assert(msg_out);
2420  tor_assert(launch_out);
2421 
2422  chan = channel_find_by_remote_identity(rsa_id_digest, ed_id);
2423 
2424  /* Walk the list of channels */
2425  for (; chan; chan = channel_next_with_rsa_identity(chan)) {
2427  rsa_id_digest, DIGEST_LEN));
2428 
2429  if (CHANNEL_CONDEMNED(chan))
2430  continue;
2431 
2432  /* Never return a channel on which the other end appears to be
2433  * a client. */
2434  if (channel_is_client(chan)) {
2435  continue;
2436  }
2437 
2438  /* The Ed25519 key has to match too */
2439  if (!channel_remote_identity_matches(chan, rsa_id_digest, ed_id)) {
2440  continue;
2441  }
2442 
2443  const bool matches_target =
2445  target_ipv4_addr,
2446  target_ipv6_addr);
2447  /* Never return a non-open connection. */
2448  if (!CHANNEL_IS_OPEN(chan)) {
2449  /* If the address matches, don't launch a new connection for this
2450  * circuit. */
2451  if (matches_target) {
2452  ++n_inprogress_goodaddr;
2453  if (for_origin_circ) {
2454  /* We were looking for a connection for an origin circuit; this one
2455  * matches, so we'll note that we decided to use it for an origin
2456  * circuit. */
2458  }
2459  }
2460  continue;
2461  }
2462 
2463  /* Never return a connection that shouldn't be used for circs. */
2464  if (channel_is_bad_for_new_circs(chan)) {
2465  ++n_old;
2466  continue;
2467  }
2468 
2469  /* Only return canonical connections or connections where the address
2470  * is the address we wanted. */
2471  if (!channel_is_canonical(chan) && !matches_target) {
2472  ++n_noncanonical;
2473  continue;
2474  }
2475 
2476  if (!best) {
2477  best = chan; /* If we have no 'best' so far, this one is good enough. */
2478  continue;
2479  }
2480 
2481  if (channel_is_better(chan, best))
2482  best = chan;
2483  }
2484 
2485  if (best) {
2486  *msg_out = "Connection is fine; using it.";
2487  *launch_out = 0;
2488  return best;
2489  } else if (n_inprogress_goodaddr) {
2490  *msg_out = "Connection in progress; waiting.";
2491  *launch_out = 0;
2492  return NULL;
2493  } else if (n_old || n_noncanonical) {
2494  *msg_out = "Connections all too old, or too non-canonical. "
2495  " Launching a new one.";
2496  *launch_out = 1;
2497  return NULL;
2498  } else {
2499  *msg_out = "Not connected. Connecting.";
2500  *launch_out = 1;
2501  return NULL;
2502  }
2503 }
2504 
2505 /**
2506  * Describe the transport subclass for a channel.
2507  *
2508  * Invoke a method to get a string description of the lower-layer
2509  * transport for this channel.
2510  */
2511 const char *
2513 {
2514  tor_assert(chan);
2516 
2517  return chan->describe_transport(chan);
2518 }
2519 
2520 /**
2521  * Describe the transport subclass for a channel listener.
2522  *
2523  * Invoke a method to get a string description of the lower-layer
2524  * transport for this channel listener.
2525  */
2526 const char *
2528 {
2529  tor_assert(chan_l);
2530  tor_assert(chan_l->describe_transport);
2531 
2532  return chan_l->describe_transport(chan_l);
2533 }
2534 
2535 /**
2536  * Dump channel statistics.
2537  *
2538  * Dump statistics for one channel to the log.
2539  */
2540 MOCK_IMPL(void,
2541 channel_dump_statistics, (channel_t *chan, int severity))
2542 {
2543  double avg, interval, age;
2544  time_t now = time(NULL);
2545  tor_addr_t remote_addr;
2546  int have_remote_addr;
2547  char *remote_addr_str;
2548 
2549  tor_assert(chan);
2550 
2551  age = (double)(now - chan->timestamp_created);
2552 
2553  tor_log(severity, LD_GENERAL,
2554  "Channel %"PRIu64 " (at %p) with transport %s is in state "
2555  "%s (%d)",
2556  (chan->global_identifier), chan,
2558  channel_state_to_string(chan->state), chan->state);
2559  tor_log(severity, LD_GENERAL,
2560  " * Channel %"PRIu64 " was created at %"PRIu64
2561  " (%"PRIu64 " seconds ago) "
2562  "and last active at %"PRIu64 " (%"PRIu64 " seconds ago)",
2563  (chan->global_identifier),
2564  (uint64_t)(chan->timestamp_created),
2565  (uint64_t)(now - chan->timestamp_created),
2566  (uint64_t)(chan->timestamp_active),
2567  (uint64_t)(now - chan->timestamp_active));
2568 
2569  /* Handle digest. */
2570  if (!tor_digest_is_zero(chan->identity_digest)) {
2571  tor_log(severity, LD_GENERAL,
2572  " * Channel %"PRIu64 " says it is connected "
2573  "to an OR with digest %s",
2574  (chan->global_identifier),
2576  } else {
2577  tor_log(severity, LD_GENERAL,
2578  " * Channel %"PRIu64 " does not know the digest"
2579  " of the OR it is connected to",
2580  (chan->global_identifier));
2581  }
2582 
2583  /* Handle remote address and descriptions */
2584  have_remote_addr = channel_get_addr_if_possible(chan, &remote_addr);
2585  if (have_remote_addr) {
2586  char *actual = tor_strdup(channel_describe_peer(chan));
2587  remote_addr_str = tor_addr_to_str_dup(&remote_addr);
2588  tor_log(severity, LD_GENERAL,
2589  " * Channel %"PRIu64 " says its remote address"
2590  " is %s, and gives a canonical description of \"%s\" and an "
2591  "actual description of \"%s\"",
2592  (chan->global_identifier),
2593  safe_str(remote_addr_str),
2594  safe_str(channel_describe_peer(chan)),
2595  safe_str(actual));
2596  tor_free(remote_addr_str);
2597  tor_free(actual);
2598  } else {
2599  char *actual = tor_strdup(channel_describe_peer(chan));
2600  tor_log(severity, LD_GENERAL,
2601  " * Channel %"PRIu64 " does not know its remote "
2602  "address, but gives a canonical description of \"%s\" and an "
2603  "actual description of \"%s\"",
2604  (chan->global_identifier),
2605  channel_describe_peer(chan),
2606  actual);
2607  tor_free(actual);
2608  }
2609 
2610  /* Handle marks */
2611  tor_log(severity, LD_GENERAL,
2612  " * Channel %"PRIu64 " has these marks: %s %s %s %s %s",
2613  (chan->global_identifier),
2615  "bad_for_new_circs" : "!bad_for_new_circs",
2616  channel_is_canonical(chan) ?
2617  "canonical" : "!canonical",
2618  channel_is_client(chan) ?
2619  "client" : "!client",
2620  channel_is_local(chan) ?
2621  "local" : "!local",
2622  channel_is_incoming(chan) ?
2623  "incoming" : "outgoing");
2624 
2625  /* Describe circuits */
2626  tor_log(severity, LD_GENERAL,
2627  " * Channel %"PRIu64 " has %d active circuits out of"
2628  " %d in total",
2629  (chan->global_identifier),
2630  (chan->cmux != NULL) ?
2632  (chan->cmux != NULL) ?
2633  circuitmux_num_circuits(chan->cmux) : 0);
2634 
2635  /* Describe timestamps */
2636  if (chan->timestamp_client == 0) {
2637  tor_log(severity, LD_GENERAL,
2638  " * Channel %"PRIu64 " was never used by a "
2639  "client", (chan->global_identifier));
2640  } else {
2641  tor_log(severity, LD_GENERAL,
2642  " * Channel %"PRIu64 " was last used by a "
2643  "client at %"PRIu64 " (%"PRIu64 " seconds ago)",
2644  (chan->global_identifier),
2645  (uint64_t)(chan->timestamp_client),
2646  (uint64_t)(now - chan->timestamp_client));
2647  }
2648  if (chan->timestamp_recv == 0) {
2649  tor_log(severity, LD_GENERAL,
2650  " * Channel %"PRIu64 " never received a cell",
2651  (chan->global_identifier));
2652  } else {
2653  tor_log(severity, LD_GENERAL,
2654  " * Channel %"PRIu64 " last received a cell "
2655  "at %"PRIu64 " (%"PRIu64 " seconds ago)",
2656  (chan->global_identifier),
2657  (uint64_t)(chan->timestamp_recv),
2658  (uint64_t)(now - chan->timestamp_recv));
2659  }
2660  if (chan->timestamp_xmit == 0) {
2661  tor_log(severity, LD_GENERAL,
2662  " * Channel %"PRIu64 " never transmitted a cell",
2663  (chan->global_identifier));
2664  } else {
2665  tor_log(severity, LD_GENERAL,
2666  " * Channel %"PRIu64 " last transmitted a cell "
2667  "at %"PRIu64 " (%"PRIu64 " seconds ago)",
2668  (chan->global_identifier),
2669  (uint64_t)(chan->timestamp_xmit),
2670  (uint64_t)(now - chan->timestamp_xmit));
2671  }
2672 
2673  /* Describe counters and rates */
2674  tor_log(severity, LD_GENERAL,
2675  " * Channel %"PRIu64 " has received "
2676  "%"PRIu64 " bytes in %"PRIu64 " cells and transmitted "
2677  "%"PRIu64 " bytes in %"PRIu64 " cells",
2678  (chan->global_identifier),
2679  (chan->n_bytes_recved),
2680  (chan->n_cells_recved),
2681  (chan->n_bytes_xmitted),
2682  (chan->n_cells_xmitted));
2683  if (now > chan->timestamp_created &&
2684  chan->timestamp_created > 0) {
2685  if (chan->n_bytes_recved > 0) {
2686  avg = (double)(chan->n_bytes_recved) / age;
2687  tor_log(severity, LD_GENERAL,
2688  " * Channel %"PRIu64 " has averaged %f "
2689  "bytes received per second",
2690  (chan->global_identifier), avg);
2691  }
2692  if (chan->n_cells_recved > 0) {
2693  avg = (double)(chan->n_cells_recved) / age;
2694  if (avg >= 1.0) {
2695  tor_log(severity, LD_GENERAL,
2696  " * Channel %"PRIu64 " has averaged %f "
2697  "cells received per second",
2698  (chan->global_identifier), avg);
2699  } else if (avg >= 0.0) {
2700  interval = 1.0 / avg;
2701  tor_log(severity, LD_GENERAL,
2702  " * Channel %"PRIu64 " has averaged %f "
2703  "seconds between received cells",
2704  (chan->global_identifier), interval);
2705  }
2706  }
2707  if (chan->n_bytes_xmitted > 0) {
2708  avg = (double)(chan->n_bytes_xmitted) / age;
2709  tor_log(severity, LD_GENERAL,
2710  " * Channel %"PRIu64 " has averaged %f "
2711  "bytes transmitted per second",
2712  (chan->global_identifier), avg);
2713  }
2714  if (chan->n_cells_xmitted > 0) {
2715  avg = (double)(chan->n_cells_xmitted) / age;
2716  if (avg >= 1.0) {
2717  tor_log(severity, LD_GENERAL,
2718  " * Channel %"PRIu64 " has averaged %f "
2719  "cells transmitted per second",
2720  (chan->global_identifier), avg);
2721  } else if (avg >= 0.0) {
2722  interval = 1.0 / avg;
2723  tor_log(severity, LD_GENERAL,
2724  " * Channel %"PRIu64 " has averaged %f "
2725  "seconds between transmitted cells",
2726  (chan->global_identifier), interval);
2727  }
2728  }
2729  }
2730 
2731  /* Dump anything the lower layer has to say */
2732  channel_dump_transport_statistics(chan, severity);
2733 }
2734 
2735 /**
2736  * Dump channel listener statistics.
2737  *
2738  * Dump statistics for one channel listener to the log.
2739  */
2740 void
2742 {
2743  double avg, interval, age;
2744  time_t now = time(NULL);
2745 
2746  tor_assert(chan_l);
2747 
2748  age = (double)(now - chan_l->timestamp_created);
2749 
2750  tor_log(severity, LD_GENERAL,
2751  "Channel listener %"PRIu64 " (at %p) with transport %s is in "
2752  "state %s (%d)",
2753  (chan_l->global_identifier), chan_l,
2755  channel_listener_state_to_string(chan_l->state), chan_l->state);
2756  tor_log(severity, LD_GENERAL,
2757  " * Channel listener %"PRIu64 " was created at %"PRIu64
2758  " (%"PRIu64 " seconds ago) "
2759  "and last active at %"PRIu64 " (%"PRIu64 " seconds ago)",
2760  (chan_l->global_identifier),
2761  (uint64_t)(chan_l->timestamp_created),
2762  (uint64_t)(now - chan_l->timestamp_created),
2763  (uint64_t)(chan_l->timestamp_active),
2764  (uint64_t)(now - chan_l->timestamp_active));
2765 
2766  tor_log(severity, LD_GENERAL,
2767  " * Channel listener %"PRIu64 " last accepted an incoming "
2768  "channel at %"PRIu64 " (%"PRIu64 " seconds ago) "
2769  "and has accepted %"PRIu64 " channels in total",
2770  (chan_l->global_identifier),
2771  (uint64_t)(chan_l->timestamp_accepted),
2772  (uint64_t)(now - chan_l->timestamp_accepted),
2773  (uint64_t)(chan_l->n_accepted));
2774 
2775  /*
2776  * If it's sensible to do so, get the rate of incoming channels on this
2777  * listener
2778  */
2779  if (now > chan_l->timestamp_created &&
2780  chan_l->timestamp_created > 0 &&
2781  chan_l->n_accepted > 0) {
2782  avg = (double)(chan_l->n_accepted) / age;
2783  if (avg >= 1.0) {
2784  tor_log(severity, LD_GENERAL,
2785  " * Channel listener %"PRIu64 " has averaged %f incoming "
2786  "channels per second",
2787  (chan_l->global_identifier), avg);
2788  } else if (avg >= 0.0) {
2789  interval = 1.0 / avg;
2790  tor_log(severity, LD_GENERAL,
2791  " * Channel listener %"PRIu64 " has averaged %f seconds "
2792  "between incoming channels",
2793  (chan_l->global_identifier), interval);
2794  }
2795  }
2796 
2797  /* Dump anything the lower layer has to say */
2799 }
2800 
2801 /**
2802  * Invoke transport-specific stats dump for channel.
2803  *
2804  * If there is a lower-layer statistics dump method, invoke it.
2805  */
2806 void
2808 {
2809  tor_assert(chan);
2810 
2811  if (chan->dumpstats) chan->dumpstats(chan, severity);
2812 }
2813 
2814 /**
2815  * Invoke transport-specific stats dump for channel listener.
2816  *
2817  * If there is a lower-layer statistics dump method, invoke it.
2818  */
2819 void
2821  int severity)
2822 {
2823  tor_assert(chan_l);
2824 
2825  if (chan_l->dumpstats) chan_l->dumpstats(chan_l, severity);
2826 }
2827 
2828 /**
2829  * Return text description of the remote endpoint canonical address.
2830  *
2831  * This function returns a human-readable string for logging; nothing
2832  * should parse it or rely on a particular format.
2833  *
2834  * Subsequent calls to this function may invalidate its return value.
2835  */
2836 MOCK_IMPL(const char *,
2838 {
2839  tor_assert(chan);
2840  tor_assert(chan->describe_peer);
2841 
2842  return chan->describe_peer(chan);
2843 }
2844 
2845 /**
2846  * Get the remote address for this channel, if possible.
2847  *
2848  * Write the remote address out to a tor_addr_t if the underlying transport
2849  * supports this operation, and return 1. Return 0 if the underlying transport
2850  * doesn't let us do this.
2851  *
2852  * Always returns the "real" address of the peer -- the one we're connected to
2853  * on the internet.
2854  */
2855 MOCK_IMPL(int,
2857  tor_addr_t *addr_out))
2858 {
2859  tor_assert(chan);
2860  tor_assert(addr_out);
2861  tor_assert(chan->get_remote_addr);
2862 
2863  return chan->get_remote_addr(chan, addr_out);
2864 }
2865 
2866 /**
2867  * Return true iff the channel has any cells on the connection outbuf waiting
2868  * to be sent onto the network.
2869  */
2870 int
2872 {
2873  tor_assert(chan);
2875 
2876  /* Check with the lower layer */
2877  return chan->has_queued_writes(chan);
2878 }
2879 
2880 /**
2881  * Check the is_bad_for_new_circs flag.
2882  *
2883  * This function returns the is_bad_for_new_circs flag of the specified
2884  * channel.
2885  */
2886 int
2888 {
2889  tor_assert(chan);
2890 
2891  return chan->is_bad_for_new_circs;
2892 }
2893 
2894 /**
2895  * Mark a channel as bad for new circuits.
2896  *
2897  * Set the is_bad_for_new_circs_flag on chan.
2898  */
2899 void
2901 {
2902  tor_assert(chan);
2903 
2904  chan->is_bad_for_new_circs = 1;
2905 }
2906 
2907 /**
2908  * Get the client flag.
2909  *
2910  * This returns the client flag of a channel, which will be set if
2911  * command_process_create_cell() in command.c thinks this is a connection
2912  * from a client.
2913  */
2914 int
2916 {
2917  tor_assert(chan);
2918 
2919  return chan->is_client;
2920 }
2921 
2922 /**
2923  * Set the client flag.
2924  *
2925  * Mark a channel as being from a client.
2926  */
2927 void
2929 {
2930  tor_assert(chan);
2931 
2932  chan->is_client = 1;
2933 }
2934 
2935 /**
2936  * Clear the client flag.
2937  *
2938  * Mark a channel as being _not_ from a client.
2939  */
2940 void
2942 {
2943  tor_assert(chan);
2944 
2945  chan->is_client = 0;
2946 }
2947 
2948 /**
2949  * Get the canonical flag for a channel.
2950  *
2951  * This returns the is_canonical for a channel; this flag is determined by
2952  * the lower layer and can't be set in a transport-independent way.
2953  */
2954 int
2956 {
2957  tor_assert(chan);
2958  tor_assert(chan->is_canonical);
2959 
2960  return chan->is_canonical(chan);
2961 }
2962 
2963 /**
2964  * Test incoming flag.
2965  *
2966  * This function gets the incoming flag; this is set when a listener spawns
2967  * a channel. If this returns true the channel was remotely initiated.
2968  */
2969 int
2971 {
2972  tor_assert(chan);
2973 
2974  return chan->is_incoming;
2975 }
2976 
2977 /**
2978  * Set the incoming flag.
2979  *
2980  * This function is called when a channel arrives on a listening channel
2981  * to mark it as incoming.
2982  */
2983 void
2985 {
2986  tor_assert(chan);
2987 
2988  chan->is_incoming = 1;
2989 }
2990 
2991 /**
2992  * Test local flag.
2993  *
2994  * This function gets the local flag; the lower layer should set this when
2995  * setting up the channel if is_local_addr() is true for all of the
2996  * destinations it will communicate with on behalf of this channel. It's
2997  * used to decide whether to declare the network reachable when seeing incoming
2998  * traffic on the channel.
2999  */
3000 int
3002 {
3003  tor_assert(chan);
3004 
3005  return chan->is_local;
3006 }
3007 
3008 /**
3009  * Set the local flag.
3010  *
3011  * This internal-only function should be called by the lower layer if the
3012  * channel is to a local address. See channel_is_local() above or the
3013  * description of the is_local bit in channel.h.
3014  */
3015 void
3017 {
3018  tor_assert(chan);
3019 
3020  chan->is_local = 1;
3021 }
3022 
3023 /**
3024  * Mark a channel as remote.
3025  *
3026  * This internal-only function should be called by the lower layer if the
3027  * channel is not to a local address but has previously been marked local.
3028  * See channel_is_local() above or the description of the is_local bit in
3029  * channel.h
3030  */
3031 void
3033 {
3034  tor_assert(chan);
3035 
3036  chan->is_local = 0;
3037 }
3038 
3039 /**
3040  * Test outgoing flag.
3041  *
3042  * This function gets the outgoing flag; this is the inverse of the incoming
3043  * bit set when a listener spawns a channel. If this returns true the channel
3044  * was locally initiated.
3045  */
3046 int
3048 {
3049  tor_assert(chan);
3050 
3051  return !(chan->is_incoming);
3052 }
3053 
3054 /**
3055  * Mark a channel as outgoing.
3056  *
3057  * This function clears the incoming flag and thus marks a channel as
3058  * outgoing.
3059  */
3060 void
3062 {
3063  tor_assert(chan);
3064 
3065  chan->is_incoming = 0;
3066 }
3067 
3068 /************************
3069  * Flow control queries *
3070  ***********************/
3071 
3072 /**
3073  * Estimate the number of writeable cells.
3074  *
3075  * Ask the lower layer for an estimate of how many cells it can accept.
3076  */
3077 int
3079 {
3080  int result;
3081 
3082  tor_assert(chan);
3083  tor_assert(chan->num_cells_writeable);
3084 
3085  if (chan->state == CHANNEL_STATE_OPEN) {
3086  /* Query lower layer */
3087  result = chan->num_cells_writeable(chan);
3088  if (result < 0) result = 0;
3089  } else {
3090  /* No cells are writeable in any other state */
3091  result = 0;
3092  }
3093 
3094  return result;
3095 }
3096 
3097 /*********************
3098  * Timestamp updates *
3099  ********************/
3100 
3101 /**
3102  * Update the created timestamp for a channel.
3103  *
3104  * This updates the channel's created timestamp and should only be called
3105  * from channel_init().
3106  */
3107 void
3109 {
3110  time_t now = time(NULL);
3111 
3112  tor_assert(chan);
3113 
3114  chan->timestamp_created = now;
3115 }
3116 
3117 /**
3118  * Update the created timestamp for a channel listener.
3119  *
3120  * This updates the channel listener's created timestamp and should only be
3121  * called from channel_init_listener().
3122  */
3123 void
3125 {
3126  time_t now = time(NULL);
3127 
3128  tor_assert(chan_l);
3129 
3130  chan_l->timestamp_created = now;
3131 }
3132 
3133 /**
3134  * Update the last active timestamp for a channel.
3135  *
3136  * This function updates the channel's last active timestamp; it should be
3137  * called by the lower layer whenever there is activity on the channel which
3138  * does not lead to a cell being transmitted or received; the active timestamp
3139  * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
3140  * but it should be updated for things like the v3 handshake and stuff that
3141  * produce activity only visible to the lower layer.
3142  */
3143 void
3145 {
3146  time_t now = time(NULL);
3147 
3148  tor_assert(chan);
3149  monotime_coarse_get(&chan->timestamp_xfer);
3150 
3151  chan->timestamp_active = now;
3152 
3153  /* Clear any potential netflow padding timer. We're active */
3154  monotime_coarse_zero(&chan->next_padding_time);
3155 }
3156 
3157 /**
3158  * Update the last active timestamp for a channel listener.
3159  */
3160 void
3162 {
3163  time_t now = time(NULL);
3164 
3165  tor_assert(chan_l);
3166 
3167  chan_l->timestamp_active = now;
3168 }
3169 
3170 /**
3171  * Update the last accepted timestamp.
3172  *
3173  * This function updates the channel listener's last accepted timestamp; it
3174  * should be called whenever a new incoming channel is accepted on a
3175  * listener.
3176  */
3177 void
3179 {
3180  time_t now = time(NULL);
3181 
3182  tor_assert(chan_l);
3183 
3184  chan_l->timestamp_active = now;
3185  chan_l->timestamp_accepted = now;
3186 }
3187 
3188 /**
3189  * Update client timestamp.
3190  *
3191  * This function is called by relay.c to timestamp a channel that appears to
3192  * be used as a client.
3193  */
3194 void
3196 {
3197  time_t now = time(NULL);
3198 
3199  tor_assert(chan);
3200 
3201  chan->timestamp_client = now;
3202 }
3203 
3204 /**
3205  * Update the recv timestamp.
3206  *
3207  * This is called whenever we get an incoming cell from the lower layer.
3208  * This also updates the active timestamp.
3209  */
3210 void
3212 {
3213  time_t now = time(NULL);
3214  tor_assert(chan);
3215  monotime_coarse_get(&chan->timestamp_xfer);
3216 
3217  chan->timestamp_active = now;
3218  chan->timestamp_recv = now;
3219 
3220  /* Clear any potential netflow padding timer. We're active */
3221  monotime_coarse_zero(&chan->next_padding_time);
3222 }
3223 
3224 /**
3225  * Update the xmit timestamp.
3226  *
3227  * This is called whenever we pass an outgoing cell to the lower layer. This
3228  * also updates the active timestamp.
3229  */
3230 void
3232 {
3233  time_t now = time(NULL);
3234  tor_assert(chan);
3235 
3236  monotime_coarse_get(&chan->timestamp_xfer);
3237 
3238  chan->timestamp_active = now;
3239  chan->timestamp_xmit = now;
3240 
3241  /* Clear any potential netflow padding timer. We're active */
3242  monotime_coarse_zero(&chan->next_padding_time);
3243 }
3244 
3245 /***************************************************************
3246  * Timestamp queries - see above for definitions of timestamps *
3247  **************************************************************/
3248 
3249 /**
3250  * Query created timestamp for a channel.
3251  */
3252 time_t
3254 {
3255  tor_assert(chan);
3256 
3257  return chan->timestamp_created;
3258 }
3259 
3260 /**
3261  * Query client timestamp.
3262  */
3263 time_t
3265 {
3266  tor_assert(chan);
3267 
3268  return chan->timestamp_client;
3269 }
3270 
3271 /**
3272  * Query xmit timestamp.
3273  */
3274 time_t
3276 {
3277  tor_assert(chan);
3278 
3279  return chan->timestamp_xmit;
3280 }
3281 
3282 /**
3283  * Check if a channel matches an extend_info_t.
3284  *
3285  * This function calls the lower layer and asks if this channel matches a
3286  * given extend_info_t.
3287  *
3288  * NOTE that this function only checks for an address/port match, and should
3289  * be used only when no identity is available.
3290  */
3291 int
3293 {
3294  tor_assert(chan);
3296  tor_assert(extend_info);
3297 
3298  return chan->matches_extend_info(chan, extend_info);
3299 }
3300 
3301 /**
3302  * Check if a channel matches the given target IPv4 or IPv6 addresses.
3303  * If either address matches, return true. If neither address matches,
3304  * return false.
3305  *
3306  * Both addresses can't be NULL.
3307  *
3308  * This function calls into the lower layer and asks if this channel thinks
3309  * it matches the target addresses for circuit extension purposes.
3310  */
3311 STATIC bool
3313  const tor_addr_t *target_ipv4_addr,
3314  const tor_addr_t *target_ipv6_addr)
3315 {
3316  tor_assert(chan);
3317  tor_assert(chan->matches_target);
3318 
3319  IF_BUG_ONCE(!target_ipv4_addr && !target_ipv6_addr)
3320  return false;
3321 
3322  if (target_ipv4_addr && chan->matches_target(chan, target_ipv4_addr))
3323  return true;
3324 
3325  if (target_ipv6_addr && chan->matches_target(chan, target_ipv6_addr))
3326  return true;
3327 
3328  return false;
3329 }
3330 
3331 /**
3332  * Return the total number of circuits used by a channel.
3333  *
3334  * @param chan Channel to query
3335  * @return Number of circuits using this as n_chan or p_chan
3336  */
3337 unsigned int
3339 {
3340  tor_assert(chan);
3341 
3342  return chan->num_n_circuits +
3343  chan->num_p_circuits;
3344 }
3345 
3346 /**
3347  * Set up circuit ID generation.
3348  *
3349  * This is called when setting up a channel and replaces the old
3350  * connection_or_set_circid_type().
3351  */
3352 MOCK_IMPL(void,
3354  crypto_pk_t *identity_rcvd,
3355  int consider_identity))
3356 {
3357  int started_here;
3358  crypto_pk_t *our_identity;
3359 
3360  tor_assert(chan);
3361 
3362  started_here = channel_is_outgoing(chan);
3363 
3364  if (! consider_identity) {
3365  if (started_here)
3367  else
3369  return;
3370  }
3371 
3372  our_identity = started_here ?
3373  get_tlsclient_identity_key() : get_server_identity_key();
3374 
3375  if (identity_rcvd) {
3376  if (crypto_pk_cmp_keys(our_identity, identity_rcvd) < 0) {
3378  } else {
3380  }
3381  } else {
3383  }
3384 }
3385 
3386 static int
3387 channel_sort_by_ed25519_identity(const void **a_, const void **b_)
3388 {
3389  const channel_t *a = *a_,
3390  *b = *b_;
3391  return fast_memcmp(&a->ed25519_identity.pubkey,
3392  &b->ed25519_identity.pubkey,
3393  sizeof(a->ed25519_identity.pubkey));
3394 }
3395 
3396 /** Helper for channel_update_bad_for_new_circs(): Perform the
3397  * channel_update_bad_for_new_circs operation on all channels in <b>lst</b>,
3398  * all of which MUST have the same RSA ID. (They MAY have different
3399  * Ed25519 IDs.) */
3400 static void
3401 channel_rsa_id_group_set_badness(struct channel_list_t *lst, int force)
3402 {
3403  /*XXXX This function should really be about channels. 15056 */
3404  channel_t *chan = TOR_LIST_FIRST(lst);
3405 
3406  if (!chan)
3407  return;
3408 
3409  /* if there is only one channel, don't bother looping */
3410  if (PREDICT_LIKELY(!TOR_LIST_NEXT(chan, next_with_same_id))) {
3412  time(NULL), BASE_CHAN_TO_TLS(chan)->conn, force);
3413  return;
3414  }
3415 
3416  smartlist_t *channels = smartlist_new();
3417 
3418  TOR_LIST_FOREACH(chan, lst, next_with_same_id) {
3419  if (BASE_CHAN_TO_TLS(chan)->conn) {
3420  smartlist_add(channels, chan);
3421  }
3422  }
3423 
3424  smartlist_sort(channels, channel_sort_by_ed25519_identity);
3425 
3426  const ed25519_public_key_t *common_ed25519_identity = NULL;
3427  /* it would be more efficient to do a slice, but this case is rare */
3428  smartlist_t *or_conns = smartlist_new();
3429  SMARTLIST_FOREACH_BEGIN(channels, channel_t *, channel) {
3430  tor_assert(channel); // Suppresses some compiler warnings.
3431 
3432  if (!common_ed25519_identity)
3433  common_ed25519_identity = &channel->ed25519_identity;
3434 
3435  if (! ed25519_pubkey_eq(&channel->ed25519_identity,
3436  common_ed25519_identity)) {
3437  connection_or_group_set_badness_(or_conns, force);
3438  smartlist_clear(or_conns);
3439  common_ed25519_identity = &channel->ed25519_identity;
3440  }
3441 
3442  smartlist_add(or_conns, BASE_CHAN_TO_TLS(channel)->conn);
3443  } SMARTLIST_FOREACH_END(channel);
3444 
3445  connection_or_group_set_badness_(or_conns, force);
3446 
3447  /* XXXX 15056 we may want to do something special with connections that have
3448  * no set Ed25519 identity! */
3449 
3450  smartlist_free(or_conns);
3451  smartlist_free(channels);
3452 }
3453 
3454 /** Go through all the channels (or if <b>digest</b> is non-NULL, just
3455  * the OR connections with that digest), and set the is_bad_for_new_circs
3456  * flag based on the rules in connection_or_group_set_badness() (or just
3457  * always set it if <b>force</b> is true).
3458  */
3459 void
3460 channel_update_bad_for_new_circs(const char *digest, int force)
3461 {
3462  if (digest) {
3463  channel_idmap_entry_t *ent;
3464  channel_idmap_entry_t search;
3465  memset(&search, 0, sizeof(search));
3466  memcpy(search.digest, digest, DIGEST_LEN);
3467  ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
3468  if (ent) {
3469  channel_rsa_id_group_set_badness(&ent->channel_list, force);
3470  }
3471  return;
3472  }
3473 
3474  /* no digest; just look at everything. */
3475  channel_idmap_entry_t **iter;
3476  HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
3477  channel_rsa_id_group_set_badness(&(*iter)->channel_list, force);
3478  }
3479 }
void tor_addr_make_unspec(tor_addr_t *a)
Definition: address.c:225
char * tor_addr_to_str_dup(const tor_addr_t *addr)
Definition: address.c:1164
const char * hex_str(const char *from, size_t fromlen)
Definition: binascii.c:34
static uint16_t get_uint16(const void *cp)
Definition: bytes.h:42
static uint32_t get_uint32(const void *cp)
Definition: bytes.h:54
Cell queue structures.
const char * channel_listener_describe_transport(channel_listener_t *chan_l)
Definition: channel.c:2527
int channel_has_queued_writes(channel_t *chan)
Definition: channel.c:2871
channel_t * channel_find_by_global_id(uint64_t global_identifier)
Definition: channel.c:650
channel_t * channel_find_by_remote_identity(const char *rsa_id_digest, const ed25519_public_key_t *ed_id)
Definition: channel.c:697
void channel_timestamp_active(channel_t *chan)
Definition: channel.c:3144
void channel_set_circid_type(channel_t *chan, crypto_pk_t *identity_rcvd, int consider_identity)
Definition: channel.c:3355
int channel_is_better(channel_t *a, channel_t *b)
Definition: channel.c:2341
int channel_is_bad_for_new_circs(channel_t *chan)
Definition: channel.c:2887
static void channel_remove_from_digest_map(channel_t *chan)
Definition: channel.c:597
int channel_is_outgoing(channel_t *chan)
Definition: channel.c:3047
const char * channel_describe_transport(channel_t *chan)
Definition: channel.c:2512
void channel_listener_process_incoming(channel_listener_t *listener)
Definition: channel.c:1811
channel_t * channel_next_with_rsa_identity(channel_t *chan)
Definition: channel.c:731
void channel_timestamp_recv(channel_t *chan)
Definition: channel.c:3211
void channel_run_cleanup(void)
Definition: channel.c:2137
void channel_update_bad_for_new_circs(const char *digest, int force)
Definition: channel.c:3460
void channel_dumpstats(int severity)
Definition: channel.c:2075
void channel_timestamp_client(channel_t *chan)
Definition: channel.c:3195
void channel_set_identity_digest(channel_t *chan, const char *identity_digest, const ed25519_public_key_t *ed_identity)
Definition: channel.c:1335
void channel_listener_unregister(channel_listener_t *chan_l)
Definition: channel.c:524
channel_t * channel_connect(const tor_addr_t *addr, uint16_t port, const char *id_digest, const ed25519_public_key_t *ed_id)
Definition: channel.c:2323
void channel_listener_dump_statistics(channel_listener_t *chan_l, int severity)
Definition: channel.c:2741
void channel_mark_local(channel_t *chan)
Definition: channel.c:3016
void channel_set_cell_handlers(channel_t *chan, channel_cell_handler_fn_ptr cell_handler)
Definition: channel.c:1106
void channel_mark_client(channel_t *chan)
Definition: channel.c:2928
time_t channel_when_last_xmit(channel_t *chan)
Definition: channel.c:3275
void channel_listener_run_cleanup(void)
Definition: channel.c:2163
static void channel_force_xfree(channel_t *chan)
Definition: channel.c:985
void channel_mark_incoming(channel_t *chan)
Definition: channel.c:2984
void channel_closed(channel_t *chan)
Definition: channel.c:1275
void channel_init_listener(channel_listener_t *chan_l)
Definition: channel.c:890
int channel_listener_state_can_transition(channel_listener_state_t from, channel_listener_state_t to)
Definition: channel.c:283
STATIC void channel_add_to_digest_map(channel_t *chan)
Definition: channel.c:560
int channel_state_is_valid(channel_state_t state)
Definition: channel.c:185
void channel_do_open_actions(channel_t *chan)
Definition: channel.c:1863
void channel_listener_mark_for_close(channel_listener_t *chan_l)
Definition: channel.c:1180
void channel_close_from_lower_layer(channel_t *chan)
Definition: channel.c:1220
void channel_check_for_duplicates(void)
Definition: channel.c:748
void channel_process_cell(channel_t *chan, cell_t *cell)
Definition: channel.c:1980
void channel_change_state_open(channel_t *chan)
Definition: channel.c:1626
void channel_listener_queue_incoming(channel_listener_t *listener, channel_t *incoming)
Definition: channel.c:1929
int channel_is_canonical(channel_t *chan)
Definition: channel.c:2955
int channel_listener_state_is_valid(channel_listener_state_t state)
Definition: channel.c:210
void channel_timestamp_created(channel_t *chan)
Definition: channel.c:3108
static void channel_free_list(smartlist_t *channels, int mark_for_close)
Definition: channel.c:2186
int channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
Definition: channel.c:3292
int channel_state_can_transition(channel_state_t from, channel_state_t to)
Definition: channel.c:237
int channel_remote_identity_matches(const channel_t *chan, const char *rsa_id_digest, const ed25519_public_key_t *ed_id)
Definition: channel.c:667
void channel_listener_set_listener_fn(channel_listener_t *chan_l, channel_listener_fn_ptr listener)
Definition: channel.c:1066
void channel_register(channel_t *chan)
Definition: channel.c:386
time_t channel_when_last_client(channel_t *chan)
Definition: channel.c:3264
void channel_listener_timestamp_created(channel_listener_t *chan_l)
Definition: channel.c:3124
void channel_listener_timestamp_active(channel_listener_t *chan_l)
Definition: channel.c:3161
void channel_listener_register(channel_listener_t *chan_l)
Definition: channel.c:483
void channel_listener_dump_transport_statistics(channel_listener_t *chan_l, int severity)
Definition: channel.c:2820
static void channel_change_state_(channel_t *chan, channel_state_t to_state)
Definition: channel.c:1523
static HT_HEAD(channel_gid_map, channel_t)
Definition: channel.c:109
int channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
Definition: channel.c:2035
void channel_mark_bad_for_new_circs(channel_t *chan)
Definition: channel.c:2900
int channel_is_incoming(channel_t *chan)
Definition: channel.c:2970
int channel_is_client(const channel_t *chan)
Definition: channel.c:2915
void channel_mark_remote(channel_t *chan)
Definition: channel.c:3032
void channel_unregister(channel_t *chan)
Definition: channel.c:444
static void channel_rsa_id_group_set_badness(struct channel_list_t *lst, int force)
Definition: channel.c:3401
channel_cell_handler_fn_ptr channel_get_cell_handler(channel_t *chan)
Definition: channel.c:1089
ssize_t channel_flush_some_cells(channel_t *chan, ssize_t num_cells)
Definition: channel.c:1734
static void channel_listener_free_list(smartlist_t *channels, int mark_for_close)
Definition: channel.c:2217
int packed_cell_is_destroy(channel_t *chan, const packed_cell_t *packed_cell, circid_t *circid_out)
Definition: channel.c:2009
STATIC bool channel_matches_target_addr_for_extend(channel_t *chan, const tor_addr_t *target_ipv4_addr, const tor_addr_t *target_ipv6_addr)
Definition: channel.c:3312
void channel_close_for_error(channel_t *chan)
Definition: channel.c:1248
void channel_listener_free_(channel_listener_t *chan_l)
Definition: channel.c:958
void channel_listener_dumpstats(int severity)
Definition: channel.c:2106
static int write_packed_cell(channel_t *chan, packed_cell_t *cell)
Definition: channel.c:1424
int channel_is_local(channel_t *chan)
Definition: channel.c:3001
void channel_listener_timestamp_accepted(channel_listener_t *chan_l)
Definition: channel.c:3178
void channel_notify_flushed(channel_t *chan)
Definition: channel.c:1794
int channel_num_cells_writeable(channel_t *chan)
Definition: channel.c:3078
void channel_timestamp_xmit(channel_t *chan)
Definition: channel.c:3231
int channel_get_addr_if_possible(const channel_t *chan, tor_addr_t *addr_out)
Definition: channel.c:2857
const char * channel_state_to_string(channel_state_t state)
Definition: channel.c:315
void channel_mark_for_close(channel_t *chan)
Definition: channel.c:1141
void channel_clear_identity_digest(channel_t *chan)
Definition: channel.c:1306
void channel_clear_remote_end(channel_t *chan)
Definition: channel.c:1394
void channel_listener_change_state(channel_listener_t *chan_l, channel_listener_state_t to_state)
Definition: channel.c:1643
void channel_mark_outgoing(channel_t *chan)
Definition: channel.c:3061
const char * channel_describe_peer(channel_t *chan)
Definition: channel.c:2837
static void channel_listener_force_xfree(channel_listener_t *chan_l)
Definition: channel.c:1029
void channel_dump_statistics(channel_t *chan, int severity)
Definition: channel.c:2541
void channel_free_all(void)
Definition: channel.c:2250
channel_t * channel_get_for_extend(const char *rsa_id_digest, const ed25519_public_key_t *ed_id, const tor_addr_t *target_ipv4_addr, const tor_addr_t *target_ipv6_addr, bool for_origin_circ, const char **msg_out, int *launch_out)
Definition: channel.c:2413
int channel_more_to_flush(channel_t *chan)
Definition: channel.c:1777
void channel_dump_transport_statistics(channel_t *chan, int severity)
Definition: channel.c:2807
unsigned int channel_num_circuits(channel_t *chan)
Definition: channel.c:3338
void channel_clear_client(channel_t *chan)
Definition: channel.c:2941
int channel_write_packed_cell(channel_t *chan, packed_cell_t *cell)
Definition: channel.c:1488
const char * channel_listener_state_to_string(channel_listener_state_t state)
Definition: channel.c:350
time_t channel_when_created(channel_t *chan)
Definition: channel.c:3253
void channel_init(channel_t *chan)
Definition: channel.c:851
void channel_free_(channel_t *chan)
Definition: channel.c:906
void channel_change_state(channel_t *chan, channel_state_t to_state)
Definition: channel.c:1616
Header file for channel.c.
void channel_mark_as_used_for_origin_circuit(channel_t *chan)
Definition: channeltls.c:375
channel_state_t
Definition: channel.h:50
@ CHANNEL_STATE_OPEN
Definition: channel.h:82
@ CHANNEL_STATE_CLOSED
Definition: channel.h:59
@ CHANNEL_STATE_MAINT
Definition: channel.h:94
@ CHANNEL_STATE_OPENING
Definition: channel.h:70
@ CHANNEL_STATE_CLOSING
Definition: channel.h:105
@ CHANNEL_STATE_ERROR
Definition: channel.h:117
@ CHANNEL_STATE_LAST
Definition: channel.h:121
@ CIRC_ID_TYPE_NEITHER
Definition: channel.h:44
@ CIRC_ID_TYPE_LOWER
Definition: channel.h:40
@ CIRC_ID_TYPE_HIGHER
Definition: channel.h:41
channel_listener_state_t
Definition: channel.h:126
@ CHANNEL_LISTENER_STATE_ERROR
Definition: channel.h:166
@ CHANNEL_LISTENER_STATE_LAST
Definition: channel.h:170
@ CHANNEL_LISTENER_STATE_LISTENING
Definition: channel.h:146
@ CHANNEL_LISTENER_STATE_CLOSING
Definition: channel.h:156
@ CHANNEL_LISTENER_STATE_CLOSED
Definition: channel.h:135
void channelpadding_disable_padding_on_channel(channel_t *chan)
void channelpadding_reduce_padding_on_channel(channel_t *chan)
channel_t * channel_tls_connect(const tor_addr_t *addr, uint16_t port, const char *id_digest, const ed25519_public_key_t *ed_id)
Definition: channeltls.c:192
Header file for channeltls.c.
void circuit_n_chan_done(channel_t *chan, int status, int close_origin_circuits)
Definition: circuitbuild.c:638
Header file for circuitbuild.c.
void channel_note_destroy_pending(channel_t *chan, circid_t id)
Definition: circuitlist.c:420
void channel_note_destroy_not_pending(channel_t *chan, circid_t id)
Definition: circuitlist.c:440
void circuit_unlink_all_from_channel(channel_t *chan, int reason)
Definition: circuitlist.c:1601
Header file for circuitlist.c.
void circuitmux_mark_destroyed_circids_usable(circuitmux_t *cmux, channel_t *chan)
Definition: circuitmux.c:324
void circuitmux_detach_all_circuits(circuitmux_t *cmux, smartlist_t *detached_out)
Definition: circuitmux.c:214
void circuitmux_set_policy(circuitmux_t *cmux, const circuitmux_policy_t *pol)
Definition: circuitmux.c:428
unsigned int circuitmux_num_active_circuits(circuitmux_t *cmux)
Definition: circuitmux.c:702
unsigned int circuitmux_num_circuits(circuitmux_t *cmux)
Definition: circuitmux.c:714
unsigned int circuitmux_num_cells(circuitmux_t *cmux)
Definition: circuitmux.c:690
Header file for circuitmux.c.
void circuit_build_times_network_is_live(circuit_build_times_t *cbt)
circuit_build_times_t * get_circuit_build_times_mutable(void)
Definition: circuitstats.c:85
Header file for circuitstats.c.
Functions and types for monotonic times.
const or_options_t * get_options(void)
Definition: config.c:926
tor_cmdline_mode_t command
Definition: config.c:2449
Header file for config.c.
int connection_or_single_set_badness_(time_t now, or_connection_t *or_conn, int force)
int connection_or_digest_is_known_relay(const char *id_digest)
void connection_or_group_set_badness_(smartlist_t *group, int force)
Header file for connection_or.c.
int ed25519_public_key_is_zero(const ed25519_public_key_t *pubkey)
int ed25519_pubkey_eq(const ed25519_public_key_t *key1, const ed25519_public_key_t *key2)
int crypto_pk_cmp_keys(const crypto_pk_t *a, const crypto_pk_t *b)
int tor_memeq(const void *a, const void *b, size_t sz)
Definition: di_ops.c:107
#define fast_memcmp(a, b, c)
Definition: di_ops.h:28
#define tor_memneq(a, b, sz)
Definition: di_ops.h:21
#define DIGEST_LEN
Definition: digest_sizes.h:20
Header file for dirlist.c.
Header file for circuitbuild.c.
Header file for geoip_stats.c.
@ DIRREQ_CHANNEL_BUFFER_FLUSHED
Definition: geoip_stats.h:73
void geoip_change_dirreq_state(uint64_t dirreq_id, dirreq_type_t type, dirreq_state_t new_state)
Definition: geoip_stats.c:552
@ GEOIP_CLIENT_CONNECT
Definition: geoip_stats.h:24
void geoip_note_client_seen(geoip_client_action_t action, const tor_addr_t *addr, const char *transport_name, time_t now)
Definition: geoip_stats.c:229
HT_PROTOTYPE(hs_circuitmap_ht, circuit_t, hs_circuitmap_node, hs_circuit_hash_token, hs_circuits_have_same_token)
Header file containing service data for the HS subsystem.
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:590
#define LD_CHANNEL
Definition: log.h:105
#define LD_OR
Definition: log.h:92
#define LD_BUG
Definition: log.h:86
#define LD_GENERAL
Definition: log.h:62
void mainloop_schedule_postloop_cleanup(void)
Definition: mainloop.c:1635
Header file for mainloop.c.
void tor_free_(void *mem)
Definition: malloc.c:227
void * tor_reallocarray_(void *ptr, size_t sz1, size_t sz2)
Definition: malloc.c:146
#define tor_free(p)
Definition: malloc.h:56
int32_t networkstatus_get_param(const networkstatus_t *ns, const char *param_name, int32_t default_val, int32_t min_val, int32_t max_val)
Header file for networkstatus.c.
void router_set_status(const char *digest, int up)
Definition: nodelist.c:2371
Header file for nodelist.c.
Master header file for Tor-specific functionality.
uint32_t circid_t
Definition: or.h:488
int channel_flush_from_first_active_circuit(channel_t *chan, int max)
Definition: relay.c:2986
uint8_t packed_cell_get_command(const packed_cell_t *cell, int wide_circ_ids)
Definition: relay.c:2961
Header file for relay.c.
void rep_hist_padding_count_write(padding_type_t type)
Definition: rephist.c:2814
Header file for rephist.c.
@ PADDING_TYPE_ENABLED_CELL
Definition: rephist.h:158
@ PADDING_TYPE_TOTAL
Definition: rephist.h:154
@ PADDING_TYPE_ENABLED_TOTAL
Definition: rephist.h:156
@ PADDING_TYPE_CELL
Definition: rephist.h:152
crypto_pk_t * get_tlsclient_identity_key(void)
Definition: router.c:432
Header file for router.c.
Header file for routerlist.c.
void scheduler_channel_doesnt_want_writes(channel_t *chan)
Definition: scheduler.c:512
Header file for scheduler*.c.
void smartlist_sort(smartlist_t *sl, int(*compare)(const void **a, const void **b))
Definition: smartlist.c:334
smartlist_t * smartlist_new(void)
void smartlist_add(smartlist_t *sl, void *element)
void smartlist_clear(smartlist_t *sl)
void smartlist_remove(smartlist_t *sl, const void *element)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define SMARTLIST_FOREACH(sl, type, var, cmd)
#define SMARTLIST_DEL_CURRENT(sl, var)
Definition: cell_st.h:17
channel_listener_state_t state
Definition: channel.h:463
enum channel_listener_t::@10 reason_for_closing
void(* dumpstats)(channel_listener_t *, int)
Definition: channel.h:495
uint64_t global_identifier
Definition: channel.h:468
void(* free_fn)(channel_listener_t *)
Definition: channel.h:489
unsigned char registered
Definition: channel.h:471
smartlist_t * incoming_list
Definition: channel.h:501
const char *(* describe_transport)(channel_listener_t *)
Definition: channel.h:493
uint64_t n_accepted
Definition: channel.h:507
time_t timestamp_created
Definition: channel.h:483
channel_listener_fn_ptr listener
Definition: channel.h:498
time_t timestamp_accepted
Definition: channel.h:504
void(* close)(channel_listener_t *)
Definition: channel.h:491
unsigned int is_local
Definition: channel.h:434
void(* free_fn)(channel_t *)
Definition: channel.h:316
channel_state_t state
Definition: channel.h:192
int sched_heap_idx
Definition: channel.h:295
int(* is_canonical)(channel_t *)
Definition: channel.h:353
void(* close)(channel_t *)
Definition: channel.h:318
monotime_coarse_t next_padding_time
Definition: channel.h:232
void(* dumpstats)(channel_t *, int)
Definition: channel.h:322
time_t timestamp_last_had_circuits
Definition: channel.h:448
unsigned int num_n_circuits
Definition: channel.h:410
int(* matches_extend_info)(channel_t *, extend_info_t *)
Definition: channel.h:355
enum channel_t::@9 scheduler_state
circ_id_type_bitfield_t circ_id_type
Definition: channel.h:405
uint64_t dirreq_id
Definition: channel.h:453
unsigned int padding_enabled
Definition: channel.h:214
char identity_digest[DIGEST_LEN]
Definition: channel.h:378
uint64_t n_cells_xmitted
Definition: channel.h:458
uint64_t n_cells_recved
Definition: channel.h:456
uint64_t global_identifier
Definition: channel.h:197
int(* write_packed_cell)(channel_t *, packed_cell_t *)
Definition: channel.h:365
struct channel_handle_t * timer_handle
Definition: channel.h:237
unsigned char registered
Definition: channel.h:200
time_t timestamp_client
Definition: channel.h:441
const char *(* describe_peer)(const channel_t *)
Definition: channel.h:346
unsigned int is_incoming
Definition: channel.h:427
time_t timestamp_xmit
Definition: channel.h:443
tor_addr_t addr_according_to_peer
Definition: channel.h:240
channel_cell_handler_fn_ptr cell_handler
Definition: channel.h:325
int(* matches_target)(channel_t *, const tor_addr_t *)
Definition: channel.h:357
time_t timestamp_recv
Definition: channel.h:442
struct ed25519_public_key_t ed25519_identity
Definition: channel.h:388
time_t timestamp_created
Definition: channel.h:298
unsigned int has_been_open
Definition: channel.h:203
monotime_coarse_t timestamp_xfer
Definition: channel.h:311
unsigned int is_client
Definition: channel.h:424
unsigned int is_bad_for_new_circs
Definition: channel.h:419
unsigned int is_canonical_to_peer
Definition: channel.h:224
const char *(* describe_transport)(channel_t *)
Definition: channel.h:320
circuitmux_t * cmux
Definition: channel.h:397
struct tor_timer_t * padding_timer
Definition: channel.h:235
ratelim_t last_warned_circ_ids_exhausted
Definition: channel.h:438
int(* has_queued_writes)(channel_t *)
Definition: channel.h:348
enum channel_t::@8 reason_for_closing
char body[CELL_MAX_NETWORK_SIZE]
Definition: cell_queue_st.h:21
int rate
Definition: ratelim.h:44
#define STATIC
Definition: testsupport.h:32
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
Header for timers.c.
#define tor_assert(expr)
Definition: util_bug.h:102
#define IF_BUG_ONCE(cond)
Definition: util_bug.h:246
int tor_digest_is_zero(const char *digest)
Definition: util_string.c:96
#define ED25519_PUBKEY_LEN
Definition: x25519_sizes.h:27