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