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