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