Merge remote-tracking branch 'tor-gitlab/mr/189' into maint-0.3.5
[tor.git] / src / core / or / channel.c
blob9649bdf278673ca17e25e59f438d7d7a97cca2c1
2 /* * Copyright (c) 2012-2019, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file channel.c
8 * \brief OR/OP-to-OR channel abstraction layer. A channel's job is to
9 * transfer cells from Tor instance to Tor instance. Currently, there is only
10 * one implementation of the channel abstraction: in channeltls.c.
12 * Channels are a higher-level abstraction than or_connection_t: In general,
13 * any means that two Tor relays use to exchange cells, or any means that a
14 * relay and a client use to exchange cells, is a channel.
16 * Channels differ from pluggable transports in that they do not wrap an
17 * underlying protocol over which cells are transmitted: they <em>are</em> the
18 * underlying protocol.
20 * This module defines the generic parts of the channel_t interface, and
21 * provides the machinery necessary for specialized implementations to be
22 * created. At present, there is one specialized implementation in
23 * channeltls.c, which uses connection_or.c to send cells over a TLS
24 * connection.
26 * Every channel implementation is responsible for being able to transmit
27 * cells that are passed to it
29 * For *inbound* cells, the entry point is: channel_process_cell(). It takes a
30 * cell and will pass it to the cell handler set by
31 * channel_set_cell_handlers(). Currently, this is passed back to the command
32 * subsystem which is command_process_cell().
34 * NOTE: For now, the separation between channels and specialized channels
35 * (like channeltls) is not that well defined. So the channeltls layer calls
36 * channel_process_cell() which originally comes from the connection subsytem.
37 * This should be hopefully be fixed with #23993.
39 * For *outbound* cells, the entry point is: channel_write_packed_cell().
40 * Only packed cells are dequeued from the circuit queue by the scheduler
41 * which uses channel_flush_from_first_active_circuit() to decide which cells
42 * to flush from which circuit on the channel. They are then passed down to
43 * the channel subsystem. This calls the low layer with the function pointer
44 * .write_packed_cell().
46 * Each specialized channel (currently only channeltls_t) MUST implement a
47 * series of function found in channel_t. See channel.h for more
48 * documentation.
49 **/
52 * Define this so channel.h gives us things only channel_t subclasses
53 * should touch.
55 #define TOR_CHANNEL_INTERNAL_
57 /* This one's for stuff only channel.c and the test suite should see */
58 #define CHANNEL_PRIVATE_
60 #include "core/or/or.h"
61 #include "app/config/config.h"
62 #include "core/mainloop/mainloop.h"
63 #include "core/or/channel.h"
64 #include "core/or/channelpadding.h"
65 #include "core/or/channeltls.h"
66 #include "core/or/circuitbuild.h"
67 #include "core/or/circuitlist.h"
68 #include "core/or/circuitmux.h"
69 #include "core/or/circuitstats.h"
70 #include "core/or/connection_or.h" /* For var_cell_free() */
71 #include "core/or/dos.h"
72 #include "core/or/relay.h"
73 #include "core/or/scheduler.h"
74 #include "feature/client/entrynodes.h"
75 #include "feature/nodelist/dirlist.h"
76 #include "feature/nodelist/networkstatus.h"
77 #include "feature/nodelist/nodelist.h"
78 #include "feature/nodelist/routerlist.h"
79 #include "feature/relay/router.h"
80 #include "feature/rend/rendservice.h"
81 #include "feature/stats/geoip_stats.h"
82 #include "feature/stats/rephist.h"
83 #include "lib/evloop/timers.h"
84 #include "lib/time/compat_time.h"
86 #include "core/or/cell_queue_st.h"
88 /* Global lists of channels */
90 /* All channel_t instances */
91 static smartlist_t *all_channels = NULL;
93 /* All channel_t instances not in ERROR or CLOSED states */
94 static smartlist_t *active_channels = NULL;
96 /* All channel_t instances in ERROR or CLOSED states */
97 static smartlist_t *finished_channels = NULL;
99 /* All channel_listener_t instances */
100 static smartlist_t *all_listeners = NULL;
102 /* All channel_listener_t instances in LISTENING state */
103 static smartlist_t *active_listeners = NULL;
105 /* All channel_listener_t instances in LISTENING state */
106 static smartlist_t *finished_listeners = NULL;
108 /** Map from channel->global_identifier to channel. Contains the same
109 * elements as all_channels. */
110 static HT_HEAD(channel_gid_map, channel_s) channel_gid_map = HT_INITIALIZER();
112 static unsigned
113 channel_id_hash(const channel_t *chan)
115 return (unsigned) chan->global_identifier;
117 static int
118 channel_id_eq(const channel_t *a, const channel_t *b)
120 return a->global_identifier == b->global_identifier;
122 HT_PROTOTYPE(channel_gid_map, channel_s, gidmap_node,
123 channel_id_hash, channel_id_eq)
124 HT_GENERATE2(channel_gid_map, channel_s, gidmap_node,
125 channel_id_hash, channel_id_eq,
126 0.6, tor_reallocarray_, tor_free_)
128 HANDLE_IMPL(channel, channel_s,)
130 /* Counter for ID numbers */
131 static uint64_t n_channels_allocated = 0;
133 /* Digest->channel map
135 * Similar to the one used in connection_or.c, this maps from the identity
136 * digest of a remote endpoint to a channel_t to that endpoint. Channels
137 * should be placed here when registered and removed when they close or error.
138 * If more than one channel exists, follow the next_with_same_id pointer
139 * as a linked list.
141 static HT_HEAD(channel_idmap, channel_idmap_entry_s) channel_identity_map =
142 HT_INITIALIZER();
144 typedef struct channel_idmap_entry_s {
145 HT_ENTRY(channel_idmap_entry_s) node;
146 uint8_t digest[DIGEST_LEN];
147 TOR_LIST_HEAD(channel_list_s, channel_s) channel_list;
148 } channel_idmap_entry_t;
150 static inline unsigned
151 channel_idmap_hash(const channel_idmap_entry_t *ent)
153 return (unsigned) siphash24g(ent->digest, DIGEST_LEN);
156 static inline int
157 channel_idmap_eq(const channel_idmap_entry_t *a,
158 const channel_idmap_entry_t *b)
160 return tor_memeq(a->digest, b->digest, DIGEST_LEN);
163 HT_PROTOTYPE(channel_idmap, channel_idmap_entry_s, node, channel_idmap_hash,
164 channel_idmap_eq)
165 HT_GENERATE2(channel_idmap, channel_idmap_entry_s, node, channel_idmap_hash,
166 channel_idmap_eq, 0.5, tor_reallocarray_, tor_free_)
168 /* Functions to maintain the digest map */
169 static void channel_remove_from_digest_map(channel_t *chan);
171 static void channel_force_xfree(channel_t *chan);
172 static void channel_free_list(smartlist_t *channels,
173 int mark_for_close);
174 static void channel_listener_free_list(smartlist_t *channels,
175 int mark_for_close);
176 static void channel_listener_force_xfree(channel_listener_t *chan_l);
178 /***********************************
179 * Channel state utility functions *
180 **********************************/
183 * Indicate whether a given channel state is valid.
186 channel_state_is_valid(channel_state_t state)
188 int is_valid;
190 switch (state) {
191 case CHANNEL_STATE_CLOSED:
192 case CHANNEL_STATE_CLOSING:
193 case CHANNEL_STATE_ERROR:
194 case CHANNEL_STATE_MAINT:
195 case CHANNEL_STATE_OPENING:
196 case CHANNEL_STATE_OPEN:
197 is_valid = 1;
198 break;
199 case CHANNEL_STATE_LAST:
200 default:
201 is_valid = 0;
204 return is_valid;
208 * Indicate whether a given channel listener state is valid.
211 channel_listener_state_is_valid(channel_listener_state_t state)
213 int is_valid;
215 switch (state) {
216 case CHANNEL_LISTENER_STATE_CLOSED:
217 case CHANNEL_LISTENER_STATE_LISTENING:
218 case CHANNEL_LISTENER_STATE_CLOSING:
219 case CHANNEL_LISTENER_STATE_ERROR:
220 is_valid = 1;
221 break;
222 case CHANNEL_LISTENER_STATE_LAST:
223 default:
224 is_valid = 0;
227 return is_valid;
231 * Indicate whether a channel state transition is valid.
233 * This function takes two channel states and indicates whether a
234 * transition between them is permitted (see the state definitions and
235 * transition table in or.h at the channel_state_t typedef).
238 channel_state_can_transition(channel_state_t from, channel_state_t to)
240 int is_valid;
242 switch (from) {
243 case CHANNEL_STATE_CLOSED:
244 is_valid = (to == CHANNEL_STATE_OPENING);
245 break;
246 case CHANNEL_STATE_CLOSING:
247 is_valid = (to == CHANNEL_STATE_CLOSED ||
248 to == CHANNEL_STATE_ERROR);
249 break;
250 case CHANNEL_STATE_ERROR:
251 is_valid = 0;
252 break;
253 case CHANNEL_STATE_MAINT:
254 is_valid = (to == CHANNEL_STATE_CLOSING ||
255 to == CHANNEL_STATE_ERROR ||
256 to == CHANNEL_STATE_OPEN);
257 break;
258 case CHANNEL_STATE_OPENING:
259 is_valid = (to == CHANNEL_STATE_CLOSING ||
260 to == CHANNEL_STATE_ERROR ||
261 to == CHANNEL_STATE_OPEN);
262 break;
263 case CHANNEL_STATE_OPEN:
264 is_valid = (to == CHANNEL_STATE_CLOSING ||
265 to == CHANNEL_STATE_ERROR ||
266 to == CHANNEL_STATE_MAINT);
267 break;
268 case CHANNEL_STATE_LAST:
269 default:
270 is_valid = 0;
273 return is_valid;
277 * Indicate whether a channel listener state transition is valid.
279 * This function takes two channel listener states and indicates whether a
280 * transition between them is permitted (see the state definitions and
281 * transition table in or.h at the channel_listener_state_t typedef).
284 channel_listener_state_can_transition(channel_listener_state_t from,
285 channel_listener_state_t to)
287 int is_valid;
289 switch (from) {
290 case CHANNEL_LISTENER_STATE_CLOSED:
291 is_valid = (to == CHANNEL_LISTENER_STATE_LISTENING);
292 break;
293 case CHANNEL_LISTENER_STATE_CLOSING:
294 is_valid = (to == CHANNEL_LISTENER_STATE_CLOSED ||
295 to == CHANNEL_LISTENER_STATE_ERROR);
296 break;
297 case CHANNEL_LISTENER_STATE_ERROR:
298 is_valid = 0;
299 break;
300 case CHANNEL_LISTENER_STATE_LISTENING:
301 is_valid = (to == CHANNEL_LISTENER_STATE_CLOSING ||
302 to == CHANNEL_LISTENER_STATE_ERROR);
303 break;
304 case CHANNEL_LISTENER_STATE_LAST:
305 default:
306 is_valid = 0;
309 return is_valid;
313 * Return a human-readable description for a channel state.
315 const char *
316 channel_state_to_string(channel_state_t state)
318 const char *descr;
320 switch (state) {
321 case CHANNEL_STATE_CLOSED:
322 descr = "closed";
323 break;
324 case CHANNEL_STATE_CLOSING:
325 descr = "closing";
326 break;
327 case CHANNEL_STATE_ERROR:
328 descr = "channel error";
329 break;
330 case CHANNEL_STATE_MAINT:
331 descr = "temporarily suspended for maintenance";
332 break;
333 case CHANNEL_STATE_OPENING:
334 descr = "opening";
335 break;
336 case CHANNEL_STATE_OPEN:
337 descr = "open";
338 break;
339 case CHANNEL_STATE_LAST:
340 default:
341 descr = "unknown or invalid channel state";
344 return descr;
348 * Return a human-readable description for a channel listener state.
350 const char *
351 channel_listener_state_to_string(channel_listener_state_t state)
353 const char *descr;
355 switch (state) {
356 case CHANNEL_LISTENER_STATE_CLOSED:
357 descr = "closed";
358 break;
359 case CHANNEL_LISTENER_STATE_CLOSING:
360 descr = "closing";
361 break;
362 case CHANNEL_LISTENER_STATE_ERROR:
363 descr = "channel listener error";
364 break;
365 case CHANNEL_LISTENER_STATE_LISTENING:
366 descr = "listening";
367 break;
368 case CHANNEL_LISTENER_STATE_LAST:
369 default:
370 descr = "unknown or invalid channel listener state";
373 return descr;
376 /***************************************
377 * Channel registration/unregistration *
378 ***************************************/
381 * Register a channel.
383 * This function registers a newly created channel in the global lists/maps
384 * of active channels.
386 void
387 channel_register(channel_t *chan)
389 tor_assert(chan);
390 tor_assert(chan->global_identifier);
392 /* No-op if already registered */
393 if (chan->registered) return;
395 log_debug(LD_CHANNEL,
396 "Registering channel %p (ID %"PRIu64 ") "
397 "in state %s (%d) with digest %s",
398 chan, (chan->global_identifier),
399 channel_state_to_string(chan->state), chan->state,
400 hex_str(chan->identity_digest, DIGEST_LEN));
402 /* Make sure we have all_channels, then add it */
403 if (!all_channels) all_channels = smartlist_new();
404 smartlist_add(all_channels, chan);
405 channel_t *oldval = HT_REPLACE(channel_gid_map, &channel_gid_map, chan);
406 tor_assert(! oldval);
408 /* Is it finished? */
409 if (CHANNEL_FINISHED(chan)) {
410 /* Put it in the finished list, creating it if necessary */
411 if (!finished_channels) finished_channels = smartlist_new();
412 smartlist_add(finished_channels, chan);
413 mainloop_schedule_postloop_cleanup();
414 } else {
415 /* Put it in the active list, creating it if necessary */
416 if (!active_channels) active_channels = smartlist_new();
417 smartlist_add(active_channels, chan);
419 if (!CHANNEL_IS_CLOSING(chan)) {
420 /* It should have a digest set */
421 if (!tor_digest_is_zero(chan->identity_digest)) {
422 /* Yeah, we're good, add it to the map */
423 channel_add_to_digest_map(chan);
424 } else {
425 log_info(LD_CHANNEL,
426 "Channel %p (global ID %"PRIu64 ") "
427 "in state %s (%d) registered with no identity digest",
428 chan, (chan->global_identifier),
429 channel_state_to_string(chan->state), chan->state);
434 /* Mark it as registered */
435 chan->registered = 1;
439 * Unregister a channel.
441 * This function removes a channel from the global lists and maps and is used
442 * when freeing a closed/errored channel.
444 void
445 channel_unregister(channel_t *chan)
447 tor_assert(chan);
449 /* No-op if not registered */
450 if (!(chan->registered)) return;
452 /* Is it finished? */
453 if (CHANNEL_FINISHED(chan)) {
454 /* Get it out of the finished list */
455 if (finished_channels) smartlist_remove(finished_channels, chan);
456 } else {
457 /* Get it out of the active list */
458 if (active_channels) smartlist_remove(active_channels, chan);
461 /* Get it out of all_channels */
462 if (all_channels) smartlist_remove(all_channels, chan);
463 channel_t *oldval = HT_REMOVE(channel_gid_map, &channel_gid_map, chan);
464 tor_assert(oldval == NULL || oldval == chan);
466 /* Mark it as unregistered */
467 chan->registered = 0;
469 /* Should it be in the digest map? */
470 if (!tor_digest_is_zero(chan->identity_digest) &&
471 !(CHANNEL_CONDEMNED(chan))) {
472 /* Remove it */
473 channel_remove_from_digest_map(chan);
478 * Register a channel listener.
480 * This function registers a newly created channel listener in the global
481 * lists/maps of active channel listeners.
483 void
484 channel_listener_register(channel_listener_t *chan_l)
486 tor_assert(chan_l);
488 /* No-op if already registered */
489 if (chan_l->registered) return;
491 log_debug(LD_CHANNEL,
492 "Registering channel listener %p (ID %"PRIu64 ") "
493 "in state %s (%d)",
494 chan_l, (chan_l->global_identifier),
495 channel_listener_state_to_string(chan_l->state),
496 chan_l->state);
498 /* Make sure we have all_listeners, then add it */
499 if (!all_listeners) all_listeners = smartlist_new();
500 smartlist_add(all_listeners, chan_l);
502 /* Is it finished? */
503 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
504 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
505 /* Put it in the finished list, creating it if necessary */
506 if (!finished_listeners) finished_listeners = smartlist_new();
507 smartlist_add(finished_listeners, chan_l);
508 } else {
509 /* Put it in the active list, creating it if necessary */
510 if (!active_listeners) active_listeners = smartlist_new();
511 smartlist_add(active_listeners, chan_l);
514 /* Mark it as registered */
515 chan_l->registered = 1;
519 * Unregister a channel listener.
521 * This function removes a channel listener from the global lists and maps
522 * and is used when freeing a closed/errored channel listener.
524 void
525 channel_listener_unregister(channel_listener_t *chan_l)
527 tor_assert(chan_l);
529 /* No-op if not registered */
530 if (!(chan_l->registered)) return;
532 /* Is it finished? */
533 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
534 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
535 /* Get it out of the finished list */
536 if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
537 } else {
538 /* Get it out of the active list */
539 if (active_listeners) smartlist_remove(active_listeners, chan_l);
542 /* Get it out of all_listeners */
543 if (all_listeners) smartlist_remove(all_listeners, chan_l);
545 /* Mark it as unregistered */
546 chan_l->registered = 0;
549 /*********************************
550 * Channel digest map maintenance
551 *********************************/
554 * Add a channel to the digest map.
556 * This function adds a channel to the digest map and inserts it into the
557 * correct linked list if channels with that remote endpoint identity digest
558 * already exist.
560 STATIC void
561 channel_add_to_digest_map(channel_t *chan)
563 channel_idmap_entry_t *ent, search;
565 tor_assert(chan);
567 /* Assert that the state makes sense */
568 tor_assert(!CHANNEL_CONDEMNED(chan));
570 /* Assert that there is a digest */
571 tor_assert(!tor_digest_is_zero(chan->identity_digest));
573 memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
574 ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
575 if (! ent) {
576 ent = tor_malloc(sizeof(channel_idmap_entry_t));
577 memcpy(ent->digest, chan->identity_digest, DIGEST_LEN);
578 TOR_LIST_INIT(&ent->channel_list);
579 HT_INSERT(channel_idmap, &channel_identity_map, ent);
581 TOR_LIST_INSERT_HEAD(&ent->channel_list, chan, next_with_same_id);
583 log_debug(LD_CHANNEL,
584 "Added channel %p (global ID %"PRIu64 ") "
585 "to identity map in state %s (%d) with digest %s",
586 chan, (chan->global_identifier),
587 channel_state_to_string(chan->state), chan->state,
588 hex_str(chan->identity_digest, DIGEST_LEN));
592 * Remove a channel from the digest map.
594 * This function removes a channel from the digest map and the linked list of
595 * channels for that digest if more than one exists.
597 static void
598 channel_remove_from_digest_map(channel_t *chan)
600 channel_idmap_entry_t *ent, search;
602 tor_assert(chan);
604 /* Assert that there is a digest */
605 tor_assert(!tor_digest_is_zero(chan->identity_digest));
607 /* Pull it out of its list, wherever that list is */
608 TOR_LIST_REMOVE(chan, next_with_same_id);
610 memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
611 ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
613 /* Look for it in the map */
614 if (ent) {
615 /* Okay, it's here */
617 if (TOR_LIST_EMPTY(&ent->channel_list)) {
618 HT_REMOVE(channel_idmap, &channel_identity_map, ent);
619 tor_free(ent);
622 log_debug(LD_CHANNEL,
623 "Removed channel %p (global ID %"PRIu64 ") from "
624 "identity map in state %s (%d) with digest %s",
625 chan, (chan->global_identifier),
626 channel_state_to_string(chan->state), chan->state,
627 hex_str(chan->identity_digest, DIGEST_LEN));
628 } else {
629 /* Shouldn't happen */
630 log_warn(LD_BUG,
631 "Trying to remove channel %p (global ID %"PRIu64 ") with "
632 "digest %s from identity map, but couldn't find any with "
633 "that digest",
634 chan, (chan->global_identifier),
635 hex_str(chan->identity_digest, DIGEST_LEN));
639 /****************************
640 * Channel lookup functions *
641 ***************************/
644 * Find channel by global ID.
646 * This function searches for a channel by the global_identifier assigned
647 * at initialization time. This identifier is unique for the lifetime of the
648 * Tor process.
650 channel_t *
651 channel_find_by_global_id(uint64_t global_identifier)
653 channel_t lookup;
654 channel_t *rv = NULL;
656 lookup.global_identifier = global_identifier;
657 rv = HT_FIND(channel_gid_map, &channel_gid_map, &lookup);
658 if (rv) {
659 tor_assert(rv->global_identifier == global_identifier);
662 return rv;
665 /** Return true iff <b>chan</b> matches <b>rsa_id_digest</b> and <b>ed_id</b>.
666 * as its identity keys. If either is NULL, do not check for a match. */
668 channel_remote_identity_matches(const channel_t *chan,
669 const char *rsa_id_digest,
670 const ed25519_public_key_t *ed_id)
672 if (BUG(!chan))
673 return 0;
674 if (rsa_id_digest) {
675 if (tor_memneq(rsa_id_digest, chan->identity_digest, DIGEST_LEN))
676 return 0;
678 if (ed_id) {
679 if (tor_memneq(ed_id->pubkey, chan->ed25519_identity.pubkey,
680 ED25519_PUBKEY_LEN))
681 return 0;
683 return 1;
687 * Find channel by RSA/Ed25519 identity of of the remote endpoint.
689 * This function looks up a channel by the digest of its remote endpoint's RSA
690 * identity key. If <b>ed_id</b> is provided and nonzero, only a channel
691 * matching the <b>ed_id</b> will be returned.
693 * It's possible that more than one channel to a given endpoint exists. Use
694 * channel_next_with_rsa_identity() to walk the list of channels; make sure
695 * to test for Ed25519 identity match too (as appropriate)
697 channel_t *
698 channel_find_by_remote_identity(const char *rsa_id_digest,
699 const ed25519_public_key_t *ed_id)
701 channel_t *rv = NULL;
702 channel_idmap_entry_t *ent, search;
704 tor_assert(rsa_id_digest); /* For now, we require that every channel have
705 * an RSA identity, and that every lookup
706 * contain an RSA identity */
707 if (ed_id && ed25519_public_key_is_zero(ed_id)) {
708 /* Treat zero as meaning "We don't care about the presence or absence of
709 * an Ed key", not "There must be no Ed key". */
710 ed_id = NULL;
713 memcpy(search.digest, rsa_id_digest, DIGEST_LEN);
714 ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
715 if (ent) {
716 rv = TOR_LIST_FIRST(&ent->channel_list);
718 while (rv && ! channel_remote_identity_matches(rv, rsa_id_digest, ed_id)) {
719 rv = channel_next_with_rsa_identity(rv);
722 return rv;
726 * Get next channel with digest.
728 * This function takes a channel and finds the next channel in the list
729 * with the same digest.
731 channel_t *
732 channel_next_with_rsa_identity(channel_t *chan)
734 tor_assert(chan);
736 return TOR_LIST_NEXT(chan, next_with_same_id);
740 * Relays run this once an hour to look over our list of channels to other
741 * relays. It prints out some statistics if there are multiple connections
742 * to many relays.
744 * This function is similar to connection_or_set_bad_connections(),
745 * and probably could be adapted to replace it, if it was modified to actually
746 * take action on any of these connections.
748 void
749 channel_check_for_duplicates(void)
751 channel_idmap_entry_t **iter;
752 channel_t *chan;
753 int total_dirauth_connections = 0, total_dirauths = 0;
754 int total_relay_connections = 0, total_relays = 0, total_canonical = 0;
755 int total_half_canonical = 0;
756 int total_gt_one_connection = 0, total_gt_two_connections = 0;
757 int total_gt_four_connections = 0;
759 HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
760 int connections_to_relay = 0;
761 const char *id_digest = (char *) (*iter)->digest;
763 /* Only consider relay connections */
764 if (!connection_or_digest_is_known_relay(id_digest))
765 continue;
767 total_relays++;
769 const bool is_dirauth = router_digest_is_trusted_dir(id_digest);
770 if (is_dirauth)
771 total_dirauths++;
773 for (chan = TOR_LIST_FIRST(&(*iter)->channel_list); chan;
774 chan = channel_next_with_rsa_identity(chan)) {
776 if (CHANNEL_CONDEMNED(chan) || !CHANNEL_IS_OPEN(chan))
777 continue;
779 connections_to_relay++;
780 total_relay_connections++;
781 if (is_dirauth)
782 total_dirauth_connections++;
784 if (chan->is_canonical(chan)) total_canonical++;
786 if (!chan->is_canonical_to_peer && chan->is_canonical(chan)) {
787 total_half_canonical++;
791 if (connections_to_relay > 1) total_gt_one_connection++;
792 if (connections_to_relay > 2) total_gt_two_connections++;
793 if (connections_to_relay > 4) total_gt_four_connections++;
796 /* Don't bother warning about excessive connections unless we have
797 * at least this many connections, total.
799 #define MIN_RELAY_CONNECTIONS_TO_WARN 25
800 /* If the average number of connections for a regular relay is more than
801 * this, that's too high.
803 #define MAX_AVG_RELAY_CONNECTIONS 1.5
804 /* If the average number of connections for a dirauth is more than
805 * this, that's too high.
807 #define MAX_AVG_DIRAUTH_CONNECTIONS 4
809 /* How many connections total would be okay, given the number of
810 * relays and dirauths that we have connections to? */
811 const int max_tolerable_connections = (int)(
812 (total_relays-total_dirauths) * MAX_AVG_RELAY_CONNECTIONS +
813 total_dirauths * MAX_AVG_DIRAUTH_CONNECTIONS);
815 /* If we average 1.5 or more connections per relay, something is wrong */
816 if (total_relays > MIN_RELAY_CONNECTIONS_TO_WARN &&
817 total_relay_connections > max_tolerable_connections) {
818 log_notice(LD_OR,
819 "Your relay has a very large number of connections to other relays. "
820 "Is your outbound address the same as your relay address? "
821 "Found %d connections to %d relays. Found %d current canonical "
822 "connections, in %d of which we were a non-canonical peer. "
823 "%d relays had more than 1 connection, %d had more than 2, and "
824 "%d had more than 4 connections.",
825 total_relay_connections, total_relays, total_canonical,
826 total_half_canonical, total_gt_one_connection,
827 total_gt_two_connections, total_gt_four_connections);
828 } else {
829 log_info(LD_OR, "Performed connection pruning. "
830 "Found %d connections to %d relays. Found %d current canonical "
831 "connections, in %d of which we were a non-canonical peer. "
832 "%d relays had more than 1 connection, %d had more than 2, and "
833 "%d had more than 4 connections.",
834 total_relay_connections, total_relays, total_canonical,
835 total_half_canonical, total_gt_one_connection,
836 total_gt_two_connections, total_gt_four_connections);
841 * Initialize a channel.
843 * This function should be called by subclasses to set up some per-channel
844 * variables. I.e., this is the superclass constructor. Before this, the
845 * channel should be allocated with tor_malloc_zero().
847 void
848 channel_init(channel_t *chan)
850 tor_assert(chan);
852 /* Assign an ID and bump the counter */
853 chan->global_identifier = ++n_channels_allocated;
855 /* Init timestamp */
856 chan->timestamp_last_had_circuits = time(NULL);
858 /* Warn about exhausted circuit IDs no more than hourly. */
859 chan->last_warned_circ_ids_exhausted.rate = 3600;
861 /* Initialize list entries. */
862 memset(&chan->next_with_same_id, 0, sizeof(chan->next_with_same_id));
864 /* Timestamp it */
865 channel_timestamp_created(chan);
867 /* It hasn't been open yet. */
868 chan->has_been_open = 0;
870 /* Scheduler state is idle */
871 chan->scheduler_state = SCHED_CHAN_IDLE;
873 /* Channel is not in the scheduler heap. */
874 chan->sched_heap_idx = -1;
878 * Initialize a channel listener.
880 * This function should be called by subclasses to set up some per-channel
881 * variables. I.e., this is the superclass constructor. Before this, the
882 * channel listener should be allocated with tor_malloc_zero().
884 void
885 channel_init_listener(channel_listener_t *chan_l)
887 tor_assert(chan_l);
889 /* Assign an ID and bump the counter */
890 chan_l->global_identifier = ++n_channels_allocated;
892 /* Timestamp it */
893 channel_listener_timestamp_created(chan_l);
897 * Free a channel; nothing outside of channel.c and subclasses should call
898 * this - it frees channels after they have closed and been unregistered.
900 void
901 channel_free_(channel_t *chan)
903 if (!chan) return;
905 /* It must be closed or errored */
906 tor_assert(CHANNEL_FINISHED(chan));
908 /* It must be deregistered */
909 tor_assert(!(chan->registered));
911 log_debug(LD_CHANNEL,
912 "Freeing channel %"PRIu64 " at %p",
913 (chan->global_identifier), chan);
915 /* Get this one out of the scheduler */
916 scheduler_release_channel(chan);
919 * Get rid of cmux policy before we do anything, so cmux policies don't
920 * see channels in weird half-freed states.
922 if (chan->cmux) {
923 circuitmux_set_policy(chan->cmux, NULL);
926 /* Remove all timers and associated handle entries now */
927 timer_free(chan->padding_timer);
928 channel_handle_free(chan->timer_handle);
929 channel_handles_clear(chan);
931 /* Call a free method if there is one */
932 if (chan->free_fn) chan->free_fn(chan);
934 channel_clear_remote_end(chan);
936 /* Get rid of cmux */
937 if (chan->cmux) {
938 circuitmux_detach_all_circuits(chan->cmux, NULL);
939 circuitmux_mark_destroyed_circids_usable(chan->cmux, chan);
940 circuitmux_free(chan->cmux);
941 chan->cmux = NULL;
944 tor_free(chan);
948 * Free a channel listener; nothing outside of channel.c and subclasses
949 * should call this - it frees channel listeners after they have closed and
950 * been unregistered.
952 void
953 channel_listener_free_(channel_listener_t *chan_l)
955 if (!chan_l) return;
957 log_debug(LD_CHANNEL,
958 "Freeing channel_listener_t %"PRIu64 " at %p",
959 (chan_l->global_identifier),
960 chan_l);
962 /* It must be closed or errored */
963 tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
964 chan_l->state == CHANNEL_LISTENER_STATE_ERROR);
965 /* It must be deregistered */
966 tor_assert(!(chan_l->registered));
968 /* Call a free method if there is one */
969 if (chan_l->free_fn) chan_l->free_fn(chan_l);
971 tor_free(chan_l);
975 * Free a channel and skip the state/registration asserts; this internal-
976 * use-only function should be called only from channel_free_all() when
977 * shutting down the Tor process.
979 static void
980 channel_force_xfree(channel_t *chan)
982 tor_assert(chan);
984 log_debug(LD_CHANNEL,
985 "Force-freeing channel %"PRIu64 " at %p",
986 (chan->global_identifier), chan);
988 /* Get this one out of the scheduler */
989 scheduler_release_channel(chan);
992 * Get rid of cmux policy before we do anything, so cmux policies don't
993 * see channels in weird half-freed states.
995 if (chan->cmux) {
996 circuitmux_set_policy(chan->cmux, NULL);
999 /* Remove all timers and associated handle entries now */
1000 timer_free(chan->padding_timer);
1001 channel_handle_free(chan->timer_handle);
1002 channel_handles_clear(chan);
1004 /* Call a free method if there is one */
1005 if (chan->free_fn) chan->free_fn(chan);
1007 channel_clear_remote_end(chan);
1009 /* Get rid of cmux */
1010 if (chan->cmux) {
1011 circuitmux_free(chan->cmux);
1012 chan->cmux = NULL;
1015 tor_free(chan);
1019 * Free a channel listener and skip the state/registration asserts; this
1020 * internal-use-only function should be called only from channel_free_all()
1021 * when shutting down the Tor process.
1023 static void
1024 channel_listener_force_xfree(channel_listener_t *chan_l)
1026 tor_assert(chan_l);
1028 log_debug(LD_CHANNEL,
1029 "Force-freeing channel_listener_t %"PRIu64 " at %p",
1030 (chan_l->global_identifier),
1031 chan_l);
1033 /* Call a free method if there is one */
1034 if (chan_l->free_fn) chan_l->free_fn(chan_l);
1037 * The incoming list just gets emptied and freed; we request close on
1038 * any channels we find there, but since we got called while shutting
1039 * down they will get deregistered and freed elsewhere anyway.
1041 if (chan_l->incoming_list) {
1042 SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
1043 channel_t *, qchan) {
1044 channel_mark_for_close(qchan);
1045 } SMARTLIST_FOREACH_END(qchan);
1047 smartlist_free(chan_l->incoming_list);
1048 chan_l->incoming_list = NULL;
1051 tor_free(chan_l);
1055 * Set the listener for a channel listener.
1057 * This function sets the handler for new incoming channels on a channel
1058 * listener.
1060 void
1061 channel_listener_set_listener_fn(channel_listener_t *chan_l,
1062 channel_listener_fn_ptr listener)
1064 tor_assert(chan_l);
1065 tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_LISTENING);
1067 log_debug(LD_CHANNEL,
1068 "Setting listener callback for channel listener %p "
1069 "(global ID %"PRIu64 ") to %p",
1070 chan_l, (chan_l->global_identifier),
1071 listener);
1073 chan_l->listener = listener;
1074 if (chan_l->listener) channel_listener_process_incoming(chan_l);
1078 * Return the fixed-length cell handler for a channel.
1080 * This function gets the handler for incoming fixed-length cells installed
1081 * on a channel.
1083 channel_cell_handler_fn_ptr
1084 channel_get_cell_handler(channel_t *chan)
1086 tor_assert(chan);
1088 if (CHANNEL_CAN_HANDLE_CELLS(chan))
1089 return chan->cell_handler;
1091 return NULL;
1095 * Return the variable-length cell handler for a channel.
1097 * This function gets the handler for incoming variable-length cells
1098 * installed on a channel.
1100 channel_var_cell_handler_fn_ptr
1101 channel_get_var_cell_handler(channel_t *chan)
1103 tor_assert(chan);
1105 if (CHANNEL_CAN_HANDLE_CELLS(chan))
1106 return chan->var_cell_handler;
1108 return NULL;
1112 * Set both cell handlers for a channel.
1114 * This function sets both the fixed-length and variable length cell handlers
1115 * for a channel.
1117 void
1118 channel_set_cell_handlers(channel_t *chan,
1119 channel_cell_handler_fn_ptr cell_handler,
1120 channel_var_cell_handler_fn_ptr
1121 var_cell_handler)
1123 tor_assert(chan);
1124 tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
1126 log_debug(LD_CHANNEL,
1127 "Setting cell_handler callback for channel %p to %p",
1128 chan, cell_handler);
1129 log_debug(LD_CHANNEL,
1130 "Setting var_cell_handler callback for channel %p to %p",
1131 chan, var_cell_handler);
1133 /* Change them */
1134 chan->cell_handler = cell_handler;
1135 chan->var_cell_handler = var_cell_handler;
1139 * On closing channels
1141 * There are three functions that close channels, for use in
1142 * different circumstances:
1144 * - Use channel_mark_for_close() for most cases
1145 * - Use channel_close_from_lower_layer() if you are connection_or.c
1146 * and the other end closes the underlying connection.
1147 * - Use channel_close_for_error() if you are connection_or.c and
1148 * some sort of error has occurred.
1152 * Mark a channel for closure.
1154 * This function tries to close a channel_t; it will go into the CLOSING
1155 * state, and eventually the lower layer should put it into the CLOSED or
1156 * ERROR state. Then, channel_run_cleanup() will eventually free it.
1158 void
1159 channel_mark_for_close(channel_t *chan)
1161 tor_assert(chan != NULL);
1162 tor_assert(chan->close != NULL);
1164 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1165 if (CHANNEL_CONDEMNED(chan))
1166 return;
1168 log_debug(LD_CHANNEL,
1169 "Closing channel %p (global ID %"PRIu64 ") "
1170 "by request",
1171 chan, (chan->global_identifier));
1173 /* Note closing by request from above */
1174 chan->reason_for_closing = CHANNEL_CLOSE_REQUESTED;
1176 /* Change state to CLOSING */
1177 channel_change_state(chan, CHANNEL_STATE_CLOSING);
1179 /* Tell the lower layer */
1180 chan->close(chan);
1183 * It's up to the lower layer to change state to CLOSED or ERROR when we're
1184 * ready; we'll try to free channels that are in the finished list from
1185 * channel_run_cleanup(). The lower layer should do this by calling
1186 * channel_closed().
1191 * Mark a channel listener for closure.
1193 * This function tries to close a channel_listener_t; it will go into the
1194 * CLOSING state, and eventually the lower layer should put it into the CLOSED
1195 * or ERROR state. Then, channel_run_cleanup() will eventually free it.
1197 void
1198 channel_listener_mark_for_close(channel_listener_t *chan_l)
1200 tor_assert(chan_l != NULL);
1201 tor_assert(chan_l->close != NULL);
1203 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1204 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
1205 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1206 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
1208 log_debug(LD_CHANNEL,
1209 "Closing channel listener %p (global ID %"PRIu64 ") "
1210 "by request",
1211 chan_l, (chan_l->global_identifier));
1213 /* Note closing by request from above */
1214 chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_REQUESTED;
1216 /* Change state to CLOSING */
1217 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
1219 /* Tell the lower layer */
1220 chan_l->close(chan_l);
1223 * It's up to the lower layer to change state to CLOSED or ERROR when we're
1224 * ready; we'll try to free channels that are in the finished list from
1225 * channel_run_cleanup(). The lower layer should do this by calling
1226 * channel_listener_closed().
1231 * Close a channel from the lower layer.
1233 * Notify the channel code that the channel is being closed due to a non-error
1234 * condition in the lower layer. This does not call the close() method, since
1235 * the lower layer already knows.
1237 void
1238 channel_close_from_lower_layer(channel_t *chan)
1240 tor_assert(chan != NULL);
1242 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1243 if (CHANNEL_CONDEMNED(chan))
1244 return;
1246 log_debug(LD_CHANNEL,
1247 "Closing channel %p (global ID %"PRIu64 ") "
1248 "due to lower-layer event",
1249 chan, (chan->global_identifier));
1251 /* Note closing by event from below */
1252 chan->reason_for_closing = CHANNEL_CLOSE_FROM_BELOW;
1254 /* Change state to CLOSING */
1255 channel_change_state(chan, CHANNEL_STATE_CLOSING);
1259 * Notify that the channel is being closed due to an error condition.
1261 * This function is called by the lower layer implementing the transport
1262 * when a channel must be closed due to an error condition. This does not
1263 * call the channel's close method, since the lower layer already knows.
1265 void
1266 channel_close_for_error(channel_t *chan)
1268 tor_assert(chan != NULL);
1270 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1271 if (CHANNEL_CONDEMNED(chan))
1272 return;
1274 log_debug(LD_CHANNEL,
1275 "Closing channel %p due to lower-layer error",
1276 chan);
1278 /* Note closing by event from below */
1279 chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
1281 /* Change state to CLOSING */
1282 channel_change_state(chan, CHANNEL_STATE_CLOSING);
1286 * Notify that the lower layer is finished closing the channel.
1288 * This function should be called by the lower layer when a channel
1289 * is finished closing and it should be regarded as inactive and
1290 * freed by the channel code.
1292 void
1293 channel_closed(channel_t *chan)
1295 tor_assert(chan);
1296 tor_assert(CHANNEL_CONDEMNED(chan));
1298 /* No-op if already inactive */
1299 if (CHANNEL_FINISHED(chan))
1300 return;
1302 /* Inform any pending (not attached) circs that they should
1303 * give up. */
1304 if (! chan->has_been_open)
1305 circuit_n_chan_done(chan, 0, 0);
1307 /* Now close all the attached circuits on it. */
1308 circuit_unlink_all_from_channel(chan, END_CIRC_REASON_CHANNEL_CLOSED);
1310 if (chan->reason_for_closing != CHANNEL_CLOSE_FOR_ERROR) {
1311 channel_change_state(chan, CHANNEL_STATE_CLOSED);
1312 } else {
1313 channel_change_state(chan, CHANNEL_STATE_ERROR);
1318 * Clear the identity_digest of a channel.
1320 * This function clears the identity digest of the remote endpoint for a
1321 * channel; this is intended for use by the lower layer.
1323 void
1324 channel_clear_identity_digest(channel_t *chan)
1326 int state_not_in_map;
1328 tor_assert(chan);
1330 log_debug(LD_CHANNEL,
1331 "Clearing remote endpoint digest on channel %p with "
1332 "global ID %"PRIu64,
1333 chan, (chan->global_identifier));
1335 state_not_in_map = CHANNEL_CONDEMNED(chan);
1337 if (!state_not_in_map && chan->registered &&
1338 !tor_digest_is_zero(chan->identity_digest))
1339 /* if it's registered get it out of the digest map */
1340 channel_remove_from_digest_map(chan);
1342 memset(chan->identity_digest, 0,
1343 sizeof(chan->identity_digest));
1347 * Set the identity_digest of a channel.
1349 * This function sets the identity digest of the remote endpoint for a
1350 * channel; this is intended for use by the lower layer.
1352 void
1353 channel_set_identity_digest(channel_t *chan,
1354 const char *identity_digest,
1355 const ed25519_public_key_t *ed_identity)
1357 int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
1359 tor_assert(chan);
1361 log_debug(LD_CHANNEL,
1362 "Setting remote endpoint digest on channel %p with "
1363 "global ID %"PRIu64 " to digest %s",
1364 chan, (chan->global_identifier),
1365 identity_digest ?
1366 hex_str(identity_digest, DIGEST_LEN) : "(null)");
1368 state_not_in_map = CHANNEL_CONDEMNED(chan);
1370 was_in_digest_map =
1371 !state_not_in_map &&
1372 chan->registered &&
1373 !tor_digest_is_zero(chan->identity_digest);
1374 should_be_in_digest_map =
1375 !state_not_in_map &&
1376 chan->registered &&
1377 (identity_digest &&
1378 !tor_digest_is_zero(identity_digest));
1380 if (was_in_digest_map)
1381 /* We should always remove it; we'll add it back if we're writing
1382 * in a new digest.
1384 channel_remove_from_digest_map(chan);
1386 if (identity_digest) {
1387 memcpy(chan->identity_digest,
1388 identity_digest,
1389 sizeof(chan->identity_digest));
1390 } else {
1391 memset(chan->identity_digest, 0,
1392 sizeof(chan->identity_digest));
1394 if (ed_identity) {
1395 memcpy(&chan->ed25519_identity, ed_identity, sizeof(*ed_identity));
1396 } else {
1397 memset(&chan->ed25519_identity, 0, sizeof(*ed_identity));
1400 /* Put it in the digest map if we should */
1401 if (should_be_in_digest_map)
1402 channel_add_to_digest_map(chan);
1406 * Clear the remote end metadata (identity_digest) of a channel.
1408 * This function clears all the remote end info from a channel; this is
1409 * intended for use by the lower layer.
1411 void
1412 channel_clear_remote_end(channel_t *chan)
1414 int state_not_in_map;
1416 tor_assert(chan);
1418 log_debug(LD_CHANNEL,
1419 "Clearing remote endpoint identity on channel %p with "
1420 "global ID %"PRIu64,
1421 chan, (chan->global_identifier));
1423 state_not_in_map = CHANNEL_CONDEMNED(chan);
1425 if (!state_not_in_map && chan->registered &&
1426 !tor_digest_is_zero(chan->identity_digest))
1427 /* if it's registered get it out of the digest map */
1428 channel_remove_from_digest_map(chan);
1430 memset(chan->identity_digest, 0,
1431 sizeof(chan->identity_digest));
1435 * Write to a channel the given packed cell.
1437 * Two possible errors can happen. Either the channel is not opened or the
1438 * lower layer (specialized channel) failed to write it. In both cases, it is
1439 * the caller responsibility to free the cell.
1441 static int
1442 write_packed_cell(channel_t *chan, packed_cell_t *cell)
1444 int ret = -1;
1445 size_t cell_bytes;
1447 tor_assert(chan);
1448 tor_assert(cell);
1450 /* Assert that the state makes sense for a cell write */
1451 tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
1454 circid_t circ_id;
1455 if (packed_cell_is_destroy(chan, cell, &circ_id)) {
1456 channel_note_destroy_not_pending(chan, circ_id);
1460 /* For statistical purposes, figure out how big this cell is */
1461 cell_bytes = get_cell_network_size(chan->wide_circ_ids);
1463 /* Can we send it right out? If so, try */
1464 if (!CHANNEL_IS_OPEN(chan)) {
1465 goto done;
1468 /* Write the cell on the connection's outbuf. */
1469 if (chan->write_packed_cell(chan, cell) < 0) {
1470 goto done;
1472 /* Timestamp for transmission */
1473 channel_timestamp_xmit(chan);
1474 /* Update the counter */
1475 ++(chan->n_cells_xmitted);
1476 chan->n_bytes_xmitted += cell_bytes;
1477 /* Successfully sent the cell. */
1478 ret = 0;
1480 done:
1481 return ret;
1485 * Write a packed cell to a channel.
1487 * Write a packed cell to a channel using the write_cell() method. This is
1488 * called by the transport-independent code to deliver a packed cell to a
1489 * channel for transmission.
1491 * Return 0 on success else a negative value. In both cases, the caller should
1492 * not access the cell anymore, it is freed both on success and error.
1495 channel_write_packed_cell(channel_t *chan, packed_cell_t *cell)
1497 int ret = -1;
1499 tor_assert(chan);
1500 tor_assert(cell);
1502 if (CHANNEL_IS_CLOSING(chan)) {
1503 log_debug(LD_CHANNEL, "Discarding %p on closing channel %p with "
1504 "global ID %"PRIu64, cell, chan,
1505 (chan->global_identifier));
1506 goto end;
1508 log_debug(LD_CHANNEL,
1509 "Writing %p to channel %p with global ID "
1510 "%"PRIu64, cell, chan, (chan->global_identifier));
1512 ret = write_packed_cell(chan, cell);
1514 end:
1515 /* Whatever happens, we free the cell. Either an error occurred or the cell
1516 * was put on the connection outbuf, both cases we have ownership of the
1517 * cell and we free it. */
1518 packed_cell_free(cell);
1519 return ret;
1523 * Change channel state.
1525 * This internal and subclass use only function is used to change channel
1526 * state, performing all transition validity checks and whatever actions
1527 * are appropriate to the state transition in question.
1529 static void
1530 channel_change_state_(channel_t *chan, channel_state_t to_state)
1532 channel_state_t from_state;
1533 unsigned char was_active, is_active;
1534 unsigned char was_in_id_map, is_in_id_map;
1536 tor_assert(chan);
1537 from_state = chan->state;
1539 tor_assert(channel_state_is_valid(from_state));
1540 tor_assert(channel_state_is_valid(to_state));
1541 tor_assert(channel_state_can_transition(chan->state, to_state));
1543 /* Check for no-op transitions */
1544 if (from_state == to_state) {
1545 log_debug(LD_CHANNEL,
1546 "Got no-op transition from \"%s\" to itself on channel %p"
1547 "(global ID %"PRIu64 ")",
1548 channel_state_to_string(to_state),
1549 chan, (chan->global_identifier));
1550 return;
1553 /* If we're going to a closing or closed state, we must have a reason set */
1554 if (to_state == CHANNEL_STATE_CLOSING ||
1555 to_state == CHANNEL_STATE_CLOSED ||
1556 to_state == CHANNEL_STATE_ERROR) {
1557 tor_assert(chan->reason_for_closing != CHANNEL_NOT_CLOSING);
1560 log_debug(LD_CHANNEL,
1561 "Changing state of channel %p (global ID %"PRIu64
1562 ") from \"%s\" to \"%s\"",
1563 chan,
1564 (chan->global_identifier),
1565 channel_state_to_string(chan->state),
1566 channel_state_to_string(to_state));
1568 chan->state = to_state;
1570 /* Need to add to the right lists if the channel is registered */
1571 if (chan->registered) {
1572 was_active = !(from_state == CHANNEL_STATE_CLOSED ||
1573 from_state == CHANNEL_STATE_ERROR);
1574 is_active = !(to_state == CHANNEL_STATE_CLOSED ||
1575 to_state == CHANNEL_STATE_ERROR);
1577 /* Need to take off active list and put on finished list? */
1578 if (was_active && !is_active) {
1579 if (active_channels) smartlist_remove(active_channels, chan);
1580 if (!finished_channels) finished_channels = smartlist_new();
1581 smartlist_add(finished_channels, chan);
1582 mainloop_schedule_postloop_cleanup();
1584 /* Need to put on active list? */
1585 else if (!was_active && is_active) {
1586 if (finished_channels) smartlist_remove(finished_channels, chan);
1587 if (!active_channels) active_channels = smartlist_new();
1588 smartlist_add(active_channels, chan);
1591 if (!tor_digest_is_zero(chan->identity_digest)) {
1592 /* Now we need to handle the identity map */
1593 was_in_id_map = !(from_state == CHANNEL_STATE_CLOSING ||
1594 from_state == CHANNEL_STATE_CLOSED ||
1595 from_state == CHANNEL_STATE_ERROR);
1596 is_in_id_map = !(to_state == CHANNEL_STATE_CLOSING ||
1597 to_state == CHANNEL_STATE_CLOSED ||
1598 to_state == CHANNEL_STATE_ERROR);
1600 if (!was_in_id_map && is_in_id_map) channel_add_to_digest_map(chan);
1601 else if (was_in_id_map && !is_in_id_map)
1602 channel_remove_from_digest_map(chan);
1607 * If we're going to a closed/closing state, we don't need scheduling any
1608 * more; in CHANNEL_STATE_MAINT we can't accept writes.
1610 if (to_state == CHANNEL_STATE_CLOSING ||
1611 to_state == CHANNEL_STATE_CLOSED ||
1612 to_state == CHANNEL_STATE_ERROR) {
1613 scheduler_release_channel(chan);
1614 } else if (to_state == CHANNEL_STATE_MAINT) {
1615 scheduler_channel_doesnt_want_writes(chan);
1620 * As channel_change_state_, but change the state to any state but open.
1622 void
1623 channel_change_state(channel_t *chan, channel_state_t to_state)
1625 tor_assert(to_state != CHANNEL_STATE_OPEN);
1626 channel_change_state_(chan, to_state);
1630 * As channel_change_state, but change the state to open.
1632 void
1633 channel_change_state_open(channel_t *chan)
1635 channel_change_state_(chan, CHANNEL_STATE_OPEN);
1637 /* Tell circuits if we opened and stuff */
1638 channel_do_open_actions(chan);
1639 chan->has_been_open = 1;
1643 * Change channel listener state.
1645 * This internal and subclass use only function is used to change channel
1646 * listener state, performing all transition validity checks and whatever
1647 * actions are appropriate to the state transition in question.
1649 void
1650 channel_listener_change_state(channel_listener_t *chan_l,
1651 channel_listener_state_t to_state)
1653 channel_listener_state_t from_state;
1654 unsigned char was_active, is_active;
1656 tor_assert(chan_l);
1657 from_state = chan_l->state;
1659 tor_assert(channel_listener_state_is_valid(from_state));
1660 tor_assert(channel_listener_state_is_valid(to_state));
1661 tor_assert(channel_listener_state_can_transition(chan_l->state, to_state));
1663 /* Check for no-op transitions */
1664 if (from_state == to_state) {
1665 log_debug(LD_CHANNEL,
1666 "Got no-op transition from \"%s\" to itself on channel "
1667 "listener %p (global ID %"PRIu64 ")",
1668 channel_listener_state_to_string(to_state),
1669 chan_l, (chan_l->global_identifier));
1670 return;
1673 /* If we're going to a closing or closed state, we must have a reason set */
1674 if (to_state == CHANNEL_LISTENER_STATE_CLOSING ||
1675 to_state == CHANNEL_LISTENER_STATE_CLOSED ||
1676 to_state == CHANNEL_LISTENER_STATE_ERROR) {
1677 tor_assert(chan_l->reason_for_closing != CHANNEL_LISTENER_NOT_CLOSING);
1680 log_debug(LD_CHANNEL,
1681 "Changing state of channel listener %p (global ID %"PRIu64
1682 "from \"%s\" to \"%s\"",
1683 chan_l, (chan_l->global_identifier),
1684 channel_listener_state_to_string(chan_l->state),
1685 channel_listener_state_to_string(to_state));
1687 chan_l->state = to_state;
1689 /* Need to add to the right lists if the channel listener is registered */
1690 if (chan_l->registered) {
1691 was_active = !(from_state == CHANNEL_LISTENER_STATE_CLOSED ||
1692 from_state == CHANNEL_LISTENER_STATE_ERROR);
1693 is_active = !(to_state == CHANNEL_LISTENER_STATE_CLOSED ||
1694 to_state == CHANNEL_LISTENER_STATE_ERROR);
1696 /* Need to take off active list and put on finished list? */
1697 if (was_active && !is_active) {
1698 if (active_listeners) smartlist_remove(active_listeners, chan_l);
1699 if (!finished_listeners) finished_listeners = smartlist_new();
1700 smartlist_add(finished_listeners, chan_l);
1701 mainloop_schedule_postloop_cleanup();
1703 /* Need to put on active list? */
1704 else if (!was_active && is_active) {
1705 if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
1706 if (!active_listeners) active_listeners = smartlist_new();
1707 smartlist_add(active_listeners, chan_l);
1711 if (to_state == CHANNEL_LISTENER_STATE_CLOSED ||
1712 to_state == CHANNEL_LISTENER_STATE_ERROR) {
1713 tor_assert(!(chan_l->incoming_list) ||
1714 smartlist_len(chan_l->incoming_list) == 0);
1718 /* Maximum number of cells that is allowed to flush at once within
1719 * channel_flush_some_cells(). */
1720 #define MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED 256
1723 * Try to flush cells of the given channel chan up to a maximum of num_cells.
1725 * This is called by the scheduler when it wants to flush cells from the
1726 * channel's circuit queue(s) to the connection outbuf (not yet on the wire).
1728 * If the channel is not in state CHANNEL_STATE_OPEN, this does nothing and
1729 * will return 0 meaning no cells were flushed.
1731 * If num_cells is -1, we'll try to flush up to the maximum cells allowed
1732 * defined in MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED.
1734 * On success, the number of flushed cells are returned and it can never be
1735 * above num_cells. If 0 is returned, no cells were flushed either because the
1736 * channel was not opened or we had no cells on the channel. A negative number
1737 * can NOT be sent back.
1739 * This function is part of the fast path. */
1740 MOCK_IMPL(ssize_t,
1741 channel_flush_some_cells, (channel_t *chan, ssize_t num_cells))
1743 unsigned int unlimited = 0;
1744 ssize_t flushed = 0;
1745 int clamped_num_cells;
1747 tor_assert(chan);
1749 if (num_cells < 0) unlimited = 1;
1750 if (!unlimited && num_cells <= flushed) goto done;
1752 /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
1753 if (CHANNEL_IS_OPEN(chan)) {
1754 if (circuitmux_num_cells(chan->cmux) > 0) {
1755 /* Calculate number of cells, including clamp */
1756 if (unlimited) {
1757 clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
1758 } else {
1759 if (num_cells - flushed >
1760 MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED) {
1761 clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
1762 } else {
1763 clamped_num_cells = (int)(num_cells - flushed);
1767 /* Try to get more cells from any active circuits */
1768 flushed = channel_flush_from_first_active_circuit(
1769 chan, clamped_num_cells);
1773 done:
1774 return flushed;
1778 * Check if any cells are available.
1780 * This is used by the scheduler to know if the channel has more to flush
1781 * after a scheduling round.
1783 MOCK_IMPL(int,
1784 channel_more_to_flush, (channel_t *chan))
1786 tor_assert(chan);
1788 if (circuitmux_num_cells(chan->cmux) > 0) return 1;
1790 /* Else no */
1791 return 0;
1795 * Notify the channel we're done flushing the output in the lower layer.
1797 * Connection.c will call this when we've flushed the output; there's some
1798 * dirreq-related maintenance to do.
1800 void
1801 channel_notify_flushed(channel_t *chan)
1803 tor_assert(chan);
1805 if (chan->dirreq_id != 0)
1806 geoip_change_dirreq_state(chan->dirreq_id,
1807 DIRREQ_TUNNELED,
1808 DIRREQ_CHANNEL_BUFFER_FLUSHED);
1812 * Process the queue of incoming channels on a listener.
1814 * Use a listener's registered callback to process as many entries in the
1815 * queue of incoming channels as possible.
1817 void
1818 channel_listener_process_incoming(channel_listener_t *listener)
1820 tor_assert(listener);
1823 * CHANNEL_LISTENER_STATE_CLOSING permitted because we drain the queue
1824 * while closing a listener.
1826 tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING ||
1827 listener->state == CHANNEL_LISTENER_STATE_CLOSING);
1828 tor_assert(listener->listener);
1830 log_debug(LD_CHANNEL,
1831 "Processing queue of incoming connections for channel "
1832 "listener %p (global ID %"PRIu64 ")",
1833 listener, (listener->global_identifier));
1835 if (!(listener->incoming_list)) return;
1837 SMARTLIST_FOREACH_BEGIN(listener->incoming_list,
1838 channel_t *, chan) {
1839 tor_assert(chan);
1841 log_debug(LD_CHANNEL,
1842 "Handling incoming channel %p (%"PRIu64 ") "
1843 "for listener %p (%"PRIu64 ")",
1844 chan,
1845 (chan->global_identifier),
1846 listener,
1847 (listener->global_identifier));
1848 /* Make sure this is set correctly */
1849 channel_mark_incoming(chan);
1850 listener->listener(listener, chan);
1851 } SMARTLIST_FOREACH_END(chan);
1853 smartlist_free(listener->incoming_list);
1854 listener->incoming_list = NULL;
1858 * Take actions required when a channel becomes open.
1860 * Handle actions we should do when we know a channel is open; a lot of
1861 * this comes from the old connection_or_set_state_open() of connection_or.c.
1863 * Because of this mechanism, future channel_t subclasses should take care
1864 * not to change a channel from CHANNEL_STATE_OPENING to CHANNEL_STATE_OPEN
1865 * until there is positive confirmation that the network is operational.
1866 * In particular, anything UDP-based should not make this transition until a
1867 * packet is received from the other side.
1869 void
1870 channel_do_open_actions(channel_t *chan)
1872 tor_addr_t remote_addr;
1873 int started_here;
1874 time_t now = time(NULL);
1875 int close_origin_circuits = 0;
1877 tor_assert(chan);
1879 started_here = channel_is_outgoing(chan);
1881 if (started_here) {
1882 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
1883 router_set_status(chan->identity_digest, 1);
1884 } else {
1885 /* only report it to the geoip module if it's a client */
1886 if (channel_is_client(chan)) {
1887 if (channel_get_addr_if_possible(chan, &remote_addr)) {
1888 char *transport_name = NULL;
1889 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
1890 if (chan->get_transport_name(chan, &transport_name) < 0)
1891 transport_name = NULL;
1893 geoip_note_client_seen(GEOIP_CLIENT_CONNECT,
1894 &remote_addr, transport_name,
1895 now);
1896 tor_free(transport_name);
1897 /* Notify the DoS subsystem of a new client. */
1898 if (tlschan && tlschan->conn) {
1899 dos_new_client_conn(tlschan->conn, transport_name);
1902 /* Otherwise the underlying transport can't tell us this, so skip it */
1906 /* Disable or reduce padding according to user prefs. */
1907 if (chan->padding_enabled || get_options()->ConnectionPadding == 1) {
1908 if (!get_options()->ConnectionPadding) {
1909 /* Disable if torrc disabled */
1910 channelpadding_disable_padding_on_channel(chan);
1911 } else if (rend_service_allow_non_anonymous_connection(get_options()) &&
1912 !networkstatus_get_param(NULL,
1913 CHANNELPADDING_SOS_PARAM,
1914 CHANNELPADDING_SOS_DEFAULT, 0, 1)) {
1915 /* Disable if we're using RSOS and the consensus disabled padding
1916 * for RSOS */
1917 channelpadding_disable_padding_on_channel(chan);
1918 } else if (get_options()->ReducedConnectionPadding) {
1919 /* Padding can be forced and/or reduced by clients, regardless of if
1920 * the channel supports it */
1921 channelpadding_reduce_padding_on_channel(chan);
1925 circuit_n_chan_done(chan, 1, close_origin_circuits);
1929 * Queue an incoming channel on a listener.
1931 * Internal and subclass use only function to queue an incoming channel from
1932 * a listener. A subclass of channel_listener_t should call this when a new
1933 * incoming channel is created.
1935 void
1936 channel_listener_queue_incoming(channel_listener_t *listener,
1937 channel_t *incoming)
1939 int need_to_queue = 0;
1941 tor_assert(listener);
1942 tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING);
1943 tor_assert(incoming);
1945 log_debug(LD_CHANNEL,
1946 "Queueing incoming channel %p (global ID %"PRIu64 ") on "
1947 "channel listener %p (global ID %"PRIu64 ")",
1948 incoming, (incoming->global_identifier),
1949 listener, (listener->global_identifier));
1951 /* Do we need to queue it, or can we just call the listener right away? */
1952 if (!(listener->listener)) need_to_queue = 1;
1953 if (listener->incoming_list &&
1954 (smartlist_len(listener->incoming_list) > 0))
1955 need_to_queue = 1;
1957 /* If we need to queue and have no queue, create one */
1958 if (need_to_queue && !(listener->incoming_list)) {
1959 listener->incoming_list = smartlist_new();
1962 /* Bump the counter and timestamp it */
1963 channel_listener_timestamp_active(listener);
1964 channel_listener_timestamp_accepted(listener);
1965 ++(listener->n_accepted);
1967 /* If we don't need to queue, process it right away */
1968 if (!need_to_queue) {
1969 tor_assert(listener->listener);
1970 listener->listener(listener, incoming);
1973 * Otherwise, we need to queue; queue and then process the queue if
1974 * we can.
1976 else {
1977 tor_assert(listener->incoming_list);
1978 smartlist_add(listener->incoming_list, incoming);
1979 if (listener->listener) channel_listener_process_incoming(listener);
1984 * Process a cell from the given channel.
1986 void
1987 channel_process_cell(channel_t *chan, cell_t *cell)
1989 tor_assert(chan);
1990 tor_assert(CHANNEL_IS_CLOSING(chan) || CHANNEL_IS_MAINT(chan) ||
1991 CHANNEL_IS_OPEN(chan));
1992 tor_assert(cell);
1994 /* Nothing we can do if we have no registered cell handlers */
1995 if (!chan->cell_handler)
1996 return;
1998 /* Timestamp for receiving */
1999 channel_timestamp_recv(chan);
2000 /* Update received counter. */
2001 ++(chan->n_cells_recved);
2002 chan->n_bytes_recved += get_cell_network_size(chan->wide_circ_ids);
2004 log_debug(LD_CHANNEL,
2005 "Processing incoming cell_t %p for channel %p (global ID "
2006 "%"PRIu64 ")", cell, chan,
2007 (chan->global_identifier));
2008 chan->cell_handler(chan, cell);
2011 /** If <b>packed_cell</b> on <b>chan</b> is a destroy cell, then set
2012 * *<b>circid_out</b> to its circuit ID, and return true. Otherwise, return
2013 * false. */
2014 /* XXXX Move this function. */
2016 packed_cell_is_destroy(channel_t *chan,
2017 const packed_cell_t *packed_cell,
2018 circid_t *circid_out)
2020 if (chan->wide_circ_ids) {
2021 if (packed_cell->body[4] == CELL_DESTROY) {
2022 *circid_out = ntohl(get_uint32(packed_cell->body));
2023 return 1;
2025 } else {
2026 if (packed_cell->body[2] == CELL_DESTROY) {
2027 *circid_out = ntohs(get_uint16(packed_cell->body));
2028 return 1;
2031 return 0;
2035 * Send destroy cell on a channel.
2037 * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
2038 * onto channel <b>chan</b>. Don't perform range-checking on reason:
2039 * we may want to propagate reasons from other cells.
2042 channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
2044 tor_assert(chan);
2045 if (circ_id == 0) {
2046 log_warn(LD_BUG, "Attempted to send a destroy cell for circID 0 "
2047 "on a channel %"PRIu64 " at %p in state %s (%d)",
2048 (chan->global_identifier),
2049 chan, channel_state_to_string(chan->state),
2050 chan->state);
2051 return 0;
2054 /* Check to make sure we can send on this channel first */
2055 if (!CHANNEL_CONDEMNED(chan) && chan->cmux) {
2056 channel_note_destroy_pending(chan, circ_id);
2057 circuitmux_append_destroy_cell(chan, chan->cmux, circ_id, reason);
2058 log_debug(LD_OR,
2059 "Sending destroy (circID %u) on channel %p "
2060 "(global ID %"PRIu64 ")",
2061 (unsigned)circ_id, chan,
2062 (chan->global_identifier));
2063 } else {
2064 log_warn(LD_BUG,
2065 "Someone called channel_send_destroy() for circID %u "
2066 "on a channel %"PRIu64 " at %p in state %s (%d)",
2067 (unsigned)circ_id, (chan->global_identifier),
2068 chan, channel_state_to_string(chan->state),
2069 chan->state);
2072 return 0;
2076 * Dump channel statistics to the log.
2078 * This is called from dumpstats() in main.c and spams the log with
2079 * statistics on channels.
2081 void
2082 channel_dumpstats(int severity)
2084 if (all_channels && smartlist_len(all_channels) > 0) {
2085 tor_log(severity, LD_GENERAL,
2086 "Dumping statistics about %d channels:",
2087 smartlist_len(all_channels));
2088 tor_log(severity, LD_GENERAL,
2089 "%d are active, and %d are done and waiting for cleanup",
2090 (active_channels != NULL) ?
2091 smartlist_len(active_channels) : 0,
2092 (finished_channels != NULL) ?
2093 smartlist_len(finished_channels) : 0);
2095 SMARTLIST_FOREACH(all_channels, channel_t *, chan,
2096 channel_dump_statistics(chan, severity));
2098 tor_log(severity, LD_GENERAL,
2099 "Done spamming about channels now");
2100 } else {
2101 tor_log(severity, LD_GENERAL,
2102 "No channels to dump");
2107 * Dump channel listener statistics to the log.
2109 * This is called from dumpstats() in main.c and spams the log with
2110 * statistics on channel listeners.
2112 void
2113 channel_listener_dumpstats(int severity)
2115 if (all_listeners && smartlist_len(all_listeners) > 0) {
2116 tor_log(severity, LD_GENERAL,
2117 "Dumping statistics about %d channel listeners:",
2118 smartlist_len(all_listeners));
2119 tor_log(severity, LD_GENERAL,
2120 "%d are active and %d are done and waiting for cleanup",
2121 (active_listeners != NULL) ?
2122 smartlist_len(active_listeners) : 0,
2123 (finished_listeners != NULL) ?
2124 smartlist_len(finished_listeners) : 0);
2126 SMARTLIST_FOREACH(all_listeners, channel_listener_t *, chan_l,
2127 channel_listener_dump_statistics(chan_l, severity));
2129 tor_log(severity, LD_GENERAL,
2130 "Done spamming about channel listeners now");
2131 } else {
2132 tor_log(severity, LD_GENERAL,
2133 "No channel listeners to dump");
2138 * Clean up channels.
2140 * This gets called periodically from run_scheduled_events() in main.c;
2141 * it cleans up after closed channels.
2143 void
2144 channel_run_cleanup(void)
2146 channel_t *tmp = NULL;
2148 /* Check if we need to do anything */
2149 if (!finished_channels || smartlist_len(finished_channels) == 0) return;
2151 /* Iterate through finished_channels and get rid of them */
2152 SMARTLIST_FOREACH_BEGIN(finished_channels, channel_t *, curr) {
2153 tmp = curr;
2154 /* Remove it from the list */
2155 SMARTLIST_DEL_CURRENT(finished_channels, curr);
2156 /* Also unregister it */
2157 channel_unregister(tmp);
2158 /* ... and free it */
2159 channel_free(tmp);
2160 } SMARTLIST_FOREACH_END(curr);
2164 * Clean up channel listeners.
2166 * This gets called periodically from run_scheduled_events() in main.c;
2167 * it cleans up after closed channel listeners.
2169 void
2170 channel_listener_run_cleanup(void)
2172 channel_listener_t *tmp = NULL;
2174 /* Check if we need to do anything */
2175 if (!finished_listeners || smartlist_len(finished_listeners) == 0) return;
2177 /* Iterate through finished_channels and get rid of them */
2178 SMARTLIST_FOREACH_BEGIN(finished_listeners, channel_listener_t *, curr) {
2179 tmp = curr;
2180 /* Remove it from the list */
2181 SMARTLIST_DEL_CURRENT(finished_listeners, curr);
2182 /* Also unregister it */
2183 channel_listener_unregister(tmp);
2184 /* ... and free it */
2185 channel_listener_free(tmp);
2186 } SMARTLIST_FOREACH_END(curr);
2190 * Free a list of channels for channel_free_all().
2192 static void
2193 channel_free_list(smartlist_t *channels, int mark_for_close)
2195 if (!channels) return;
2197 SMARTLIST_FOREACH_BEGIN(channels, channel_t *, curr) {
2198 /* Deregister and free it */
2199 tor_assert(curr);
2200 log_debug(LD_CHANNEL,
2201 "Cleaning up channel %p (global ID %"PRIu64 ") "
2202 "in state %s (%d)",
2203 curr, (curr->global_identifier),
2204 channel_state_to_string(curr->state), curr->state);
2205 /* Detach circuits early so they can find the channel */
2206 if (curr->cmux) {
2207 circuitmux_detach_all_circuits(curr->cmux, NULL);
2209 SMARTLIST_DEL_CURRENT(channels, curr);
2210 channel_unregister(curr);
2211 if (mark_for_close) {
2212 if (!CHANNEL_CONDEMNED(curr)) {
2213 channel_mark_for_close(curr);
2215 channel_force_xfree(curr);
2216 } else channel_free(curr);
2217 } SMARTLIST_FOREACH_END(curr);
2221 * Free a list of channel listeners for channel_free_all().
2223 static void
2224 channel_listener_free_list(smartlist_t *listeners, int mark_for_close)
2226 if (!listeners) return;
2228 SMARTLIST_FOREACH_BEGIN(listeners, channel_listener_t *, curr) {
2229 /* Deregister and free it */
2230 tor_assert(curr);
2231 log_debug(LD_CHANNEL,
2232 "Cleaning up channel listener %p (global ID %"PRIu64 ") "
2233 "in state %s (%d)",
2234 curr, (curr->global_identifier),
2235 channel_listener_state_to_string(curr->state), curr->state);
2236 channel_listener_unregister(curr);
2237 if (mark_for_close) {
2238 if (!(curr->state == CHANNEL_LISTENER_STATE_CLOSING ||
2239 curr->state == CHANNEL_LISTENER_STATE_CLOSED ||
2240 curr->state == CHANNEL_LISTENER_STATE_ERROR)) {
2241 channel_listener_mark_for_close(curr);
2243 channel_listener_force_xfree(curr);
2244 } else channel_listener_free(curr);
2245 } SMARTLIST_FOREACH_END(curr);
2249 * Close all channels and free everything.
2251 * This gets called from tor_free_all() in main.c to clean up on exit.
2252 * It will close all registered channels and free associated storage,
2253 * then free the all_channels, active_channels, listening_channels and
2254 * finished_channels lists and also channel_identity_map.
2256 void
2257 channel_free_all(void)
2259 log_debug(LD_CHANNEL,
2260 "Shutting down channels...");
2262 /* First, let's go for finished channels */
2263 if (finished_channels) {
2264 channel_free_list(finished_channels, 0);
2265 smartlist_free(finished_channels);
2266 finished_channels = NULL;
2269 /* Now the finished listeners */
2270 if (finished_listeners) {
2271 channel_listener_free_list(finished_listeners, 0);
2272 smartlist_free(finished_listeners);
2273 finished_listeners = NULL;
2276 /* Now all active channels */
2277 if (active_channels) {
2278 channel_free_list(active_channels, 1);
2279 smartlist_free(active_channels);
2280 active_channels = NULL;
2283 /* Now all active listeners */
2284 if (active_listeners) {
2285 channel_listener_free_list(active_listeners, 1);
2286 smartlist_free(active_listeners);
2287 active_listeners = NULL;
2290 /* Now all channels, in case any are left over */
2291 if (all_channels) {
2292 channel_free_list(all_channels, 1);
2293 smartlist_free(all_channels);
2294 all_channels = NULL;
2297 /* Now all listeners, in case any are left over */
2298 if (all_listeners) {
2299 channel_listener_free_list(all_listeners, 1);
2300 smartlist_free(all_listeners);
2301 all_listeners = NULL;
2304 /* Now free channel_identity_map */
2305 log_debug(LD_CHANNEL,
2306 "Freeing channel_identity_map");
2307 /* Geez, anything still left over just won't die ... let it leak then */
2308 HT_CLEAR(channel_idmap, &channel_identity_map);
2310 /* Same with channel_gid_map */
2311 log_debug(LD_CHANNEL,
2312 "Freeing channel_gid_map");
2313 HT_CLEAR(channel_gid_map, &channel_gid_map);
2315 log_debug(LD_CHANNEL,
2316 "Done cleaning up after channels");
2320 * Connect to a given addr/port/digest.
2322 * This sets up a new outgoing channel; in the future if multiple
2323 * channel_t subclasses are available, this is where the selection policy
2324 * should go. It may also be desirable to fold port into tor_addr_t
2325 * or make a new type including a tor_addr_t and port, so we have a
2326 * single abstract object encapsulating all the protocol details of
2327 * how to contact an OR.
2329 channel_t *
2330 channel_connect(const tor_addr_t *addr, uint16_t port,
2331 const char *id_digest,
2332 const ed25519_public_key_t *ed_id)
2334 return channel_tls_connect(addr, port, id_digest, ed_id);
2338 * Decide which of two channels to prefer for extending a circuit.
2340 * This function is called while extending a circuit and returns true iff
2341 * a is 'better' than b. The most important criterion here is that a
2342 * canonical channel is always better than a non-canonical one, but the
2343 * number of circuits and the age are used as tie-breakers.
2345 * This is based on the former connection_or_is_better() of connection_or.c
2348 channel_is_better(channel_t *a, channel_t *b)
2350 int a_is_canonical, b_is_canonical;
2352 tor_assert(a);
2353 tor_assert(b);
2355 /* If one channel is bad for new circuits, and the other isn't,
2356 * use the one that is still good. */
2357 if (!channel_is_bad_for_new_circs(a) && channel_is_bad_for_new_circs(b))
2358 return 1;
2359 if (channel_is_bad_for_new_circs(a) && !channel_is_bad_for_new_circs(b))
2360 return 0;
2362 /* Check if one is canonical and the other isn't first */
2363 a_is_canonical = channel_is_canonical(a);
2364 b_is_canonical = channel_is_canonical(b);
2366 if (a_is_canonical && !b_is_canonical) return 1;
2367 if (!a_is_canonical && b_is_canonical) return 0;
2369 /* Check if we suspect that one of the channels will be preferred
2370 * by the peer */
2371 if (a->is_canonical_to_peer && !b->is_canonical_to_peer) return 1;
2372 if (!a->is_canonical_to_peer && b->is_canonical_to_peer) return 0;
2375 * Okay, if we're here they tied on canonicity, the prefer the older
2376 * connection, so that the adversary can't create a new connection
2377 * and try to switch us over to it (which will leak information
2378 * about long-lived circuits). Additionally, switching connections
2379 * too often makes us more vulnerable to attacks like Torscan and
2380 * passive netflow-based equivalents.
2382 * Connections will still only live for at most a week, due to
2383 * the check in connection_or_group_set_badness() against
2384 * TIME_BEFORE_OR_CONN_IS_TOO_OLD, which marks old connections as
2385 * unusable for new circuits after 1 week. That check sets
2386 * is_bad_for_new_circs, which is checked in channel_get_for_extend().
2388 * We check channel_is_bad_for_new_circs() above here anyway, for safety.
2390 if (channel_when_created(a) < channel_when_created(b)) return 1;
2391 else if (channel_when_created(a) > channel_when_created(b)) return 0;
2393 if (channel_num_circuits(a) > channel_num_circuits(b)) return 1;
2394 else return 0;
2398 * Get a channel to extend a circuit.
2400 * Pick a suitable channel to extend a circuit to given the desired digest
2401 * the address we believe is correct for that digest; this tries to see
2402 * if we already have one for the requested endpoint, but if there is no good
2403 * channel, set *msg_out to a message describing the channel's state
2404 * and our next action, and set *launch_out to a boolean indicated whether
2405 * the caller should try to launch a new channel with channel_connect().
2407 channel_t *
2408 channel_get_for_extend(const char *rsa_id_digest,
2409 const ed25519_public_key_t *ed_id,
2410 const tor_addr_t *target_addr,
2411 const char **msg_out,
2412 int *launch_out)
2414 channel_t *chan, *best = NULL;
2415 int n_inprogress_goodaddr = 0, n_old = 0;
2416 int n_noncanonical = 0;
2418 tor_assert(msg_out);
2419 tor_assert(launch_out);
2421 chan = channel_find_by_remote_identity(rsa_id_digest, ed_id);
2423 /* Walk the list, unrefing the old one and refing the new at each
2424 * iteration.
2426 for (; chan; chan = channel_next_with_rsa_identity(chan)) {
2427 tor_assert(tor_memeq(chan->identity_digest,
2428 rsa_id_digest, DIGEST_LEN));
2430 if (CHANNEL_CONDEMNED(chan))
2431 continue;
2433 /* Never return a channel on which the other end appears to be
2434 * a client. */
2435 if (channel_is_client(chan)) {
2436 continue;
2439 /* The Ed25519 key has to match too */
2440 if (!channel_remote_identity_matches(chan, rsa_id_digest, ed_id)) {
2441 continue;
2444 /* Never return a non-open connection. */
2445 if (!CHANNEL_IS_OPEN(chan)) {
2446 /* If the address matches, don't launch a new connection for this
2447 * circuit. */
2448 if (channel_matches_target_addr_for_extend(chan, target_addr))
2449 ++n_inprogress_goodaddr;
2450 continue;
2453 /* Never return a connection that shouldn't be used for circs. */
2454 if (channel_is_bad_for_new_circs(chan)) {
2455 ++n_old;
2456 continue;
2459 /* Only return canonical connections or connections where the address
2460 * is the address we wanted. */
2461 if (!channel_is_canonical(chan) &&
2462 !channel_matches_target_addr_for_extend(chan, target_addr)) {
2463 ++n_noncanonical;
2464 continue;
2467 if (!best) {
2468 best = chan; /* If we have no 'best' so far, this one is good enough. */
2469 continue;
2472 if (channel_is_better(chan, best))
2473 best = chan;
2476 if (best) {
2477 *msg_out = "Connection is fine; using it.";
2478 *launch_out = 0;
2479 return best;
2480 } else if (n_inprogress_goodaddr) {
2481 *msg_out = "Connection in progress; waiting.";
2482 *launch_out = 0;
2483 return NULL;
2484 } else if (n_old || n_noncanonical) {
2485 *msg_out = "Connections all too old, or too non-canonical. "
2486 " Launching a new one.";
2487 *launch_out = 1;
2488 return NULL;
2489 } else {
2490 *msg_out = "Not connected. Connecting.";
2491 *launch_out = 1;
2492 return NULL;
2497 * Describe the transport subclass for a channel.
2499 * Invoke a method to get a string description of the lower-layer
2500 * transport for this channel.
2502 const char *
2503 channel_describe_transport(channel_t *chan)
2505 tor_assert(chan);
2506 tor_assert(chan->describe_transport);
2508 return chan->describe_transport(chan);
2512 * Describe the transport subclass for a channel listener.
2514 * Invoke a method to get a string description of the lower-layer
2515 * transport for this channel listener.
2517 const char *
2518 channel_listener_describe_transport(channel_listener_t *chan_l)
2520 tor_assert(chan_l);
2521 tor_assert(chan_l->describe_transport);
2523 return chan_l->describe_transport(chan_l);
2527 * Dump channel statistics.
2529 * Dump statistics for one channel to the log.
2531 MOCK_IMPL(void,
2532 channel_dump_statistics, (channel_t *chan, int severity))
2534 double avg, interval, age;
2535 time_t now = time(NULL);
2536 tor_addr_t remote_addr;
2537 int have_remote_addr;
2538 char *remote_addr_str;
2540 tor_assert(chan);
2542 age = (double)(now - chan->timestamp_created);
2544 tor_log(severity, LD_GENERAL,
2545 "Channel %"PRIu64 " (at %p) with transport %s is in state "
2546 "%s (%d)",
2547 (chan->global_identifier), chan,
2548 channel_describe_transport(chan),
2549 channel_state_to_string(chan->state), chan->state);
2550 tor_log(severity, LD_GENERAL,
2551 " * Channel %"PRIu64 " was created at %"PRIu64
2552 " (%"PRIu64 " seconds ago) "
2553 "and last active at %"PRIu64 " (%"PRIu64 " seconds ago)",
2554 (chan->global_identifier),
2555 (uint64_t)(chan->timestamp_created),
2556 (uint64_t)(now - chan->timestamp_created),
2557 (uint64_t)(chan->timestamp_active),
2558 (uint64_t)(now - chan->timestamp_active));
2560 /* Handle digest. */
2561 if (!tor_digest_is_zero(chan->identity_digest)) {
2562 tor_log(severity, LD_GENERAL,
2563 " * Channel %"PRIu64 " says it is connected "
2564 "to an OR with digest %s",
2565 (chan->global_identifier),
2566 hex_str(chan->identity_digest, DIGEST_LEN));
2567 } else {
2568 tor_log(severity, LD_GENERAL,
2569 " * Channel %"PRIu64 " does not know the digest"
2570 " of the OR it is connected to",
2571 (chan->global_identifier));
2574 /* Handle remote address and descriptions */
2575 have_remote_addr = channel_get_addr_if_possible(chan, &remote_addr);
2576 if (have_remote_addr) {
2577 char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
2578 remote_addr_str = tor_addr_to_str_dup(&remote_addr);
2579 tor_log(severity, LD_GENERAL,
2580 " * Channel %"PRIu64 " says its remote address"
2581 " is %s, and gives a canonical description of \"%s\" and an "
2582 "actual description of \"%s\"",
2583 (chan->global_identifier),
2584 safe_str(remote_addr_str),
2585 safe_str(channel_get_canonical_remote_descr(chan)),
2586 safe_str(actual));
2587 tor_free(remote_addr_str);
2588 tor_free(actual);
2589 } else {
2590 char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
2591 tor_log(severity, LD_GENERAL,
2592 " * Channel %"PRIu64 " does not know its remote "
2593 "address, but gives a canonical description of \"%s\" and an "
2594 "actual description of \"%s\"",
2595 (chan->global_identifier),
2596 channel_get_canonical_remote_descr(chan),
2597 actual);
2598 tor_free(actual);
2601 /* Handle marks */
2602 tor_log(severity, LD_GENERAL,
2603 " * Channel %"PRIu64 " has these marks: %s %s %s %s %s",
2604 (chan->global_identifier),
2605 channel_is_bad_for_new_circs(chan) ?
2606 "bad_for_new_circs" : "!bad_for_new_circs",
2607 channel_is_canonical(chan) ?
2608 "canonical" : "!canonical",
2609 channel_is_client(chan) ?
2610 "client" : "!client",
2611 channel_is_local(chan) ?
2612 "local" : "!local",
2613 channel_is_incoming(chan) ?
2614 "incoming" : "outgoing");
2616 /* Describe circuits */
2617 tor_log(severity, LD_GENERAL,
2618 " * Channel %"PRIu64 " has %d active circuits out of"
2619 " %d in total",
2620 (chan->global_identifier),
2621 (chan->cmux != NULL) ?
2622 circuitmux_num_active_circuits(chan->cmux) : 0,
2623 (chan->cmux != NULL) ?
2624 circuitmux_num_circuits(chan->cmux) : 0);
2626 /* Describe timestamps */
2627 tor_log(severity, LD_GENERAL,
2628 " * Channel %"PRIu64 " was last used by a "
2629 "client at %"PRIu64 " (%"PRIu64 " seconds ago)",
2630 (chan->global_identifier),
2631 (uint64_t)(chan->timestamp_client),
2632 (uint64_t)(now - chan->timestamp_client));
2633 tor_log(severity, LD_GENERAL,
2634 " * Channel %"PRIu64 " last received a cell "
2635 "at %"PRIu64 " (%"PRIu64 " seconds ago)",
2636 (chan->global_identifier),
2637 (uint64_t)(chan->timestamp_recv),
2638 (uint64_t)(now - chan->timestamp_recv));
2639 tor_log(severity, LD_GENERAL,
2640 " * Channel %"PRIu64 " last transmitted a cell "
2641 "at %"PRIu64 " (%"PRIu64 " seconds ago)",
2642 (chan->global_identifier),
2643 (uint64_t)(chan->timestamp_xmit),
2644 (uint64_t)(now - chan->timestamp_xmit));
2646 /* Describe counters and rates */
2647 tor_log(severity, LD_GENERAL,
2648 " * Channel %"PRIu64 " has received "
2649 "%"PRIu64 " bytes in %"PRIu64 " cells and transmitted "
2650 "%"PRIu64 " bytes in %"PRIu64 " cells",
2651 (chan->global_identifier),
2652 (chan->n_bytes_recved),
2653 (chan->n_cells_recved),
2654 (chan->n_bytes_xmitted),
2655 (chan->n_cells_xmitted));
2656 if (now > chan->timestamp_created &&
2657 chan->timestamp_created > 0) {
2658 if (chan->n_bytes_recved > 0) {
2659 avg = (double)(chan->n_bytes_recved) / age;
2660 tor_log(severity, LD_GENERAL,
2661 " * Channel %"PRIu64 " has averaged %f "
2662 "bytes received per second",
2663 (chan->global_identifier), avg);
2665 if (chan->n_cells_recved > 0) {
2666 avg = (double)(chan->n_cells_recved) / age;
2667 if (avg >= 1.0) {
2668 tor_log(severity, LD_GENERAL,
2669 " * Channel %"PRIu64 " has averaged %f "
2670 "cells received per second",
2671 (chan->global_identifier), avg);
2672 } else if (avg >= 0.0) {
2673 interval = 1.0 / avg;
2674 tor_log(severity, LD_GENERAL,
2675 " * Channel %"PRIu64 " has averaged %f "
2676 "seconds between received cells",
2677 (chan->global_identifier), interval);
2680 if (chan->n_bytes_xmitted > 0) {
2681 avg = (double)(chan->n_bytes_xmitted) / age;
2682 tor_log(severity, LD_GENERAL,
2683 " * Channel %"PRIu64 " has averaged %f "
2684 "bytes transmitted per second",
2685 (chan->global_identifier), avg);
2687 if (chan->n_cells_xmitted > 0) {
2688 avg = (double)(chan->n_cells_xmitted) / age;
2689 if (avg >= 1.0) {
2690 tor_log(severity, LD_GENERAL,
2691 " * Channel %"PRIu64 " has averaged %f "
2692 "cells transmitted per second",
2693 (chan->global_identifier), avg);
2694 } else if (avg >= 0.0) {
2695 interval = 1.0 / avg;
2696 tor_log(severity, LD_GENERAL,
2697 " * Channel %"PRIu64 " has averaged %f "
2698 "seconds between transmitted cells",
2699 (chan->global_identifier), interval);
2704 /* Dump anything the lower layer has to say */
2705 channel_dump_transport_statistics(chan, severity);
2709 * Dump channel listener statistics.
2711 * Dump statistics for one channel listener to the log.
2713 void
2714 channel_listener_dump_statistics(channel_listener_t *chan_l, int severity)
2716 double avg, interval, age;
2717 time_t now = time(NULL);
2719 tor_assert(chan_l);
2721 age = (double)(now - chan_l->timestamp_created);
2723 tor_log(severity, LD_GENERAL,
2724 "Channel listener %"PRIu64 " (at %p) with transport %s is in "
2725 "state %s (%d)",
2726 (chan_l->global_identifier), chan_l,
2727 channel_listener_describe_transport(chan_l),
2728 channel_listener_state_to_string(chan_l->state), chan_l->state);
2729 tor_log(severity, LD_GENERAL,
2730 " * Channel listener %"PRIu64 " was created at %"PRIu64
2731 " (%"PRIu64 " seconds ago) "
2732 "and last active at %"PRIu64 " (%"PRIu64 " seconds ago)",
2733 (chan_l->global_identifier),
2734 (uint64_t)(chan_l->timestamp_created),
2735 (uint64_t)(now - chan_l->timestamp_created),
2736 (uint64_t)(chan_l->timestamp_active),
2737 (uint64_t)(now - chan_l->timestamp_active));
2739 tor_log(severity, LD_GENERAL,
2740 " * Channel listener %"PRIu64 " last accepted an incoming "
2741 "channel at %"PRIu64 " (%"PRIu64 " seconds ago) "
2742 "and has accepted %"PRIu64 " channels in total",
2743 (chan_l->global_identifier),
2744 (uint64_t)(chan_l->timestamp_accepted),
2745 (uint64_t)(now - chan_l->timestamp_accepted),
2746 (uint64_t)(chan_l->n_accepted));
2749 * If it's sensible to do so, get the rate of incoming channels on this
2750 * listener
2752 if (now > chan_l->timestamp_created &&
2753 chan_l->timestamp_created > 0 &&
2754 chan_l->n_accepted > 0) {
2755 avg = (double)(chan_l->n_accepted) / age;
2756 if (avg >= 1.0) {
2757 tor_log(severity, LD_GENERAL,
2758 " * Channel listener %"PRIu64 " has averaged %f incoming "
2759 "channels per second",
2760 (chan_l->global_identifier), avg);
2761 } else if (avg >= 0.0) {
2762 interval = 1.0 / avg;
2763 tor_log(severity, LD_GENERAL,
2764 " * Channel listener %"PRIu64 " has averaged %f seconds "
2765 "between incoming channels",
2766 (chan_l->global_identifier), interval);
2770 /* Dump anything the lower layer has to say */
2771 channel_listener_dump_transport_statistics(chan_l, severity);
2775 * Invoke transport-specific stats dump for channel.
2777 * If there is a lower-layer statistics dump method, invoke it.
2779 void
2780 channel_dump_transport_statistics(channel_t *chan, int severity)
2782 tor_assert(chan);
2784 if (chan->dumpstats) chan->dumpstats(chan, severity);
2788 * Invoke transport-specific stats dump for channel listener.
2790 * If there is a lower-layer statistics dump method, invoke it.
2792 void
2793 channel_listener_dump_transport_statistics(channel_listener_t *chan_l,
2794 int severity)
2796 tor_assert(chan_l);
2798 if (chan_l->dumpstats) chan_l->dumpstats(chan_l, severity);
2802 * Return text description of the remote endpoint.
2804 * This function return a test provided by the lower layer of the remote
2805 * endpoint for this channel; it should specify the actual address connected
2806 * to/from.
2808 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
2809 * may invalidate the return value from this function.
2811 const char *
2812 channel_get_actual_remote_descr(channel_t *chan)
2814 tor_assert(chan);
2815 tor_assert(chan->get_remote_descr);
2817 /* Param 1 indicates the actual description */
2818 return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL);
2822 * Return the text address of the remote endpoint.
2824 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
2825 * may invalidate the return value from this function.
2827 const char *
2828 channel_get_actual_remote_address(channel_t *chan)
2830 /* Param 1 indicates the actual description */
2831 return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY);
2835 * Return text description of the remote endpoint canonical address.
2837 * This function return a test provided by the lower layer of the remote
2838 * endpoint for this channel; it should use the known canonical address for
2839 * this OR's identity digest if possible.
2841 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
2842 * may invalidate the return value from this function.
2844 const char *
2845 channel_get_canonical_remote_descr(channel_t *chan)
2847 tor_assert(chan);
2848 tor_assert(chan->get_remote_descr);
2850 /* Param 0 indicates the canonicalized description */
2851 return chan->get_remote_descr(chan, 0);
2855 * Get remote address if possible.
2857 * Write the remote address out to a tor_addr_t if the underlying transport
2858 * supports this operation, and return 1. Return 0 if the underlying transport
2859 * doesn't let us do this.
2861 MOCK_IMPL(int,
2862 channel_get_addr_if_possible,(channel_t *chan, tor_addr_t *addr_out))
2864 tor_assert(chan);
2865 tor_assert(addr_out);
2867 if (chan->get_remote_addr)
2868 return chan->get_remote_addr(chan, addr_out);
2869 /* Else no support, method not implemented */
2870 else return 0;
2874 * Return true iff the channel has any cells on the connection outbuf waiting
2875 * to be sent onto the network.
2878 channel_has_queued_writes(channel_t *chan)
2880 tor_assert(chan);
2881 tor_assert(chan->has_queued_writes);
2883 /* Check with the lower layer */
2884 return chan->has_queued_writes(chan);
2888 * Check the is_bad_for_new_circs flag.
2890 * This function returns the is_bad_for_new_circs flag of the specified
2891 * channel.
2894 channel_is_bad_for_new_circs(channel_t *chan)
2896 tor_assert(chan);
2898 return chan->is_bad_for_new_circs;
2902 * Mark a channel as bad for new circuits.
2904 * Set the is_bad_for_new_circs_flag on chan.
2906 void
2907 channel_mark_bad_for_new_circs(channel_t *chan)
2909 tor_assert(chan);
2911 chan->is_bad_for_new_circs = 1;
2915 * Get the client flag.
2917 * This returns the client flag of a channel, which will be set if
2918 * command_process_create_cell() in command.c thinks this is a connection
2919 * from a client.
2922 channel_is_client(const channel_t *chan)
2924 tor_assert(chan);
2926 return chan->is_client;
2930 * Set the client flag.
2932 * Mark a channel as being from a client.
2934 void
2935 channel_mark_client(channel_t *chan)
2937 tor_assert(chan);
2939 chan->is_client = 1;
2943 * Clear the client flag.
2945 * Mark a channel as being _not_ from a client.
2947 void
2948 channel_clear_client(channel_t *chan)
2950 tor_assert(chan);
2952 chan->is_client = 0;
2956 * Get the canonical flag for a channel.
2958 * This returns the is_canonical for a channel; this flag is determined by
2959 * the lower layer and can't be set in a transport-independent way.
2962 channel_is_canonical(channel_t *chan)
2964 tor_assert(chan);
2965 tor_assert(chan->is_canonical);
2967 return chan->is_canonical(chan);
2971 * Test incoming flag.
2973 * This function gets the incoming flag; this is set when a listener spawns
2974 * a channel. If this returns true the channel was remotely initiated.
2977 channel_is_incoming(channel_t *chan)
2979 tor_assert(chan);
2981 return chan->is_incoming;
2985 * Set the incoming flag.
2987 * This function is called when a channel arrives on a listening channel
2988 * to mark it as incoming.
2990 void
2991 channel_mark_incoming(channel_t *chan)
2993 tor_assert(chan);
2995 chan->is_incoming = 1;
2999 * Test local flag.
3001 * This function gets the local flag; the lower layer should set this when
3002 * setting up the channel if is_local_addr() is true for all of the
3003 * destinations it will communicate with on behalf of this channel. It's
3004 * used to decide whether to declare the network reachable when seeing incoming
3005 * traffic on the channel.
3008 channel_is_local(channel_t *chan)
3010 tor_assert(chan);
3012 return chan->is_local;
3016 * Set the local flag.
3018 * This internal-only function should be called by the lower layer if the
3019 * channel is to a local address. See channel_is_local() above or the
3020 * description of the is_local bit in channel.h.
3022 void
3023 channel_mark_local(channel_t *chan)
3025 tor_assert(chan);
3027 chan->is_local = 1;
3031 * Mark a channel as remote.
3033 * This internal-only function should be called by the lower layer if the
3034 * channel is not to a local address but has previously been marked local.
3035 * See channel_is_local() above or the description of the is_local bit in
3036 * channel.h
3038 void
3039 channel_mark_remote(channel_t *chan)
3041 tor_assert(chan);
3043 chan->is_local = 0;
3047 * Test outgoing flag.
3049 * This function gets the outgoing flag; this is the inverse of the incoming
3050 * bit set when a listener spawns a channel. If this returns true the channel
3051 * was locally initiated.
3054 channel_is_outgoing(channel_t *chan)
3056 tor_assert(chan);
3058 return !(chan->is_incoming);
3062 * Mark a channel as outgoing.
3064 * This function clears the incoming flag and thus marks a channel as
3065 * outgoing.
3067 void
3068 channel_mark_outgoing(channel_t *chan)
3070 tor_assert(chan);
3072 chan->is_incoming = 0;
3075 /************************
3076 * Flow control queries *
3077 ***********************/
3080 * Estimate the number of writeable cells.
3082 * Ask the lower layer for an estimate of how many cells it can accept.
3085 channel_num_cells_writeable(channel_t *chan)
3087 int result;
3089 tor_assert(chan);
3090 tor_assert(chan->num_cells_writeable);
3092 if (chan->state == CHANNEL_STATE_OPEN) {
3093 /* Query lower layer */
3094 result = chan->num_cells_writeable(chan);
3095 if (result < 0) result = 0;
3096 } else {
3097 /* No cells are writeable in any other state */
3098 result = 0;
3101 return result;
3104 /*********************
3105 * Timestamp updates *
3106 ********************/
3109 * Update the created timestamp for a channel.
3111 * This updates the channel's created timestamp and should only be called
3112 * from channel_init().
3114 void
3115 channel_timestamp_created(channel_t *chan)
3117 time_t now = time(NULL);
3119 tor_assert(chan);
3121 chan->timestamp_created = now;
3125 * Update the created timestamp for a channel listener.
3127 * This updates the channel listener's created timestamp and should only be
3128 * called from channel_init_listener().
3130 void
3131 channel_listener_timestamp_created(channel_listener_t *chan_l)
3133 time_t now = time(NULL);
3135 tor_assert(chan_l);
3137 chan_l->timestamp_created = now;
3141 * Update the last active timestamp for a channel.
3143 * This function updates the channel's last active timestamp; it should be
3144 * called by the lower layer whenever there is activity on the channel which
3145 * does not lead to a cell being transmitted or received; the active timestamp
3146 * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
3147 * but it should be updated for things like the v3 handshake and stuff that
3148 * produce activity only visible to the lower layer.
3150 void
3151 channel_timestamp_active(channel_t *chan)
3153 time_t now = time(NULL);
3155 tor_assert(chan);
3156 monotime_coarse_get(&chan->timestamp_xfer);
3158 chan->timestamp_active = now;
3160 /* Clear any potential netflow padding timer. We're active */
3161 monotime_coarse_zero(&chan->next_padding_time);
3165 * Update the last active timestamp for a channel listener.
3167 void
3168 channel_listener_timestamp_active(channel_listener_t *chan_l)
3170 time_t now = time(NULL);
3172 tor_assert(chan_l);
3174 chan_l->timestamp_active = now;
3178 * Update the last accepted timestamp.
3180 * This function updates the channel listener's last accepted timestamp; it
3181 * should be called whenever a new incoming channel is accepted on a
3182 * listener.
3184 void
3185 channel_listener_timestamp_accepted(channel_listener_t *chan_l)
3187 time_t now = time(NULL);
3189 tor_assert(chan_l);
3191 chan_l->timestamp_active = now;
3192 chan_l->timestamp_accepted = now;
3196 * Update client timestamp.
3198 * This function is called by relay.c to timestamp a channel that appears to
3199 * be used as a client.
3201 void
3202 channel_timestamp_client(channel_t *chan)
3204 time_t now = time(NULL);
3206 tor_assert(chan);
3208 chan->timestamp_client = now;
3212 * Update the recv timestamp.
3214 * This is called whenever we get an incoming cell from the lower layer.
3215 * This also updates the active timestamp.
3217 void
3218 channel_timestamp_recv(channel_t *chan)
3220 time_t now = time(NULL);
3221 tor_assert(chan);
3222 monotime_coarse_get(&chan->timestamp_xfer);
3224 chan->timestamp_active = now;
3225 chan->timestamp_recv = now;
3227 /* Clear any potential netflow padding timer. We're active */
3228 monotime_coarse_zero(&chan->next_padding_time);
3232 * Update the xmit timestamp.
3234 * This is called whenever we pass an outgoing cell to the lower layer. This
3235 * also updates the active timestamp.
3237 void
3238 channel_timestamp_xmit(channel_t *chan)
3240 time_t now = time(NULL);
3241 tor_assert(chan);
3243 monotime_coarse_get(&chan->timestamp_xfer);
3245 chan->timestamp_active = now;
3246 chan->timestamp_xmit = now;
3248 /* Clear any potential netflow padding timer. We're active */
3249 monotime_coarse_zero(&chan->next_padding_time);
3252 /***************************************************************
3253 * Timestamp queries - see above for definitions of timestamps *
3254 **************************************************************/
3257 * Query created timestamp for a channel.
3259 time_t
3260 channel_when_created(channel_t *chan)
3262 tor_assert(chan);
3264 return chan->timestamp_created;
3268 * Query client timestamp.
3270 time_t
3271 channel_when_last_client(channel_t *chan)
3273 tor_assert(chan);
3275 return chan->timestamp_client;
3279 * Query xmit timestamp.
3281 time_t
3282 channel_when_last_xmit(channel_t *chan)
3284 tor_assert(chan);
3286 return chan->timestamp_xmit;
3290 * Check if a channel matches an extend_info_t.
3292 * This function calls the lower layer and asks if this channel matches a
3293 * given extend_info_t.
3296 channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
3298 tor_assert(chan);
3299 tor_assert(chan->matches_extend_info);
3300 tor_assert(extend_info);
3302 return chan->matches_extend_info(chan, extend_info);
3306 * Check if a channel matches a given target address; return true iff we do.
3308 * This function calls into the lower layer and asks if this channel thinks
3309 * it matches a given target address for circuit extension purposes.
3312 channel_matches_target_addr_for_extend(channel_t *chan,
3313 const tor_addr_t *target)
3315 tor_assert(chan);
3316 tor_assert(chan->matches_target);
3317 tor_assert(target);
3319 return chan->matches_target(chan, target);
3323 * Return the total number of circuits used by a channel.
3325 * @param chan Channel to query
3326 * @return Number of circuits using this as n_chan or p_chan
3328 unsigned int
3329 channel_num_circuits(channel_t *chan)
3331 tor_assert(chan);
3333 return chan->num_n_circuits +
3334 chan->num_p_circuits;
3338 * Set up circuit ID generation.
3340 * This is called when setting up a channel and replaces the old
3341 * connection_or_set_circid_type().
3343 MOCK_IMPL(void,
3344 channel_set_circid_type,(channel_t *chan,
3345 crypto_pk_t *identity_rcvd,
3346 int consider_identity))
3348 int started_here;
3349 crypto_pk_t *our_identity;
3351 tor_assert(chan);
3353 started_here = channel_is_outgoing(chan);
3355 if (! consider_identity) {
3356 if (started_here)
3357 chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
3358 else
3359 chan->circ_id_type = CIRC_ID_TYPE_LOWER;
3360 return;
3363 our_identity = started_here ?
3364 get_tlsclient_identity_key() : get_server_identity_key();
3366 if (identity_rcvd) {
3367 if (crypto_pk_cmp_keys(our_identity, identity_rcvd) < 0) {
3368 chan->circ_id_type = CIRC_ID_TYPE_LOWER;
3369 } else {
3370 chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
3372 } else {
3373 chan->circ_id_type = CIRC_ID_TYPE_NEITHER;
3377 static int
3378 channel_sort_by_ed25519_identity(const void **a_, const void **b_)
3380 const channel_t *a = *a_,
3381 *b = *b_;
3382 return fast_memcmp(&a->ed25519_identity.pubkey,
3383 &b->ed25519_identity.pubkey,
3384 sizeof(a->ed25519_identity.pubkey));
3387 /** Helper for channel_update_bad_for_new_circs(): Perform the
3388 * channel_update_bad_for_new_circs operation on all channels in <b>lst</b>,
3389 * all of which MUST have the same RSA ID. (They MAY have different
3390 * Ed25519 IDs.) */
3391 static void
3392 channel_rsa_id_group_set_badness(struct channel_list_s *lst, int force)
3394 /*XXXX This function should really be about channels. 15056 */
3395 channel_t *chan = TOR_LIST_FIRST(lst);
3397 if (!chan)
3398 return;
3400 /* if there is only one channel, don't bother looping */
3401 if (PREDICT_LIKELY(!TOR_LIST_NEXT(chan, next_with_same_id))) {
3402 connection_or_single_set_badness_(
3403 time(NULL), BASE_CHAN_TO_TLS(chan)->conn, force);
3404 return;
3407 smartlist_t *channels = smartlist_new();
3409 TOR_LIST_FOREACH(chan, lst, next_with_same_id) {
3410 if (BASE_CHAN_TO_TLS(chan)->conn) {
3411 smartlist_add(channels, chan);
3415 smartlist_sort(channels, channel_sort_by_ed25519_identity);
3417 const ed25519_public_key_t *common_ed25519_identity = NULL;
3418 /* it would be more efficient to do a slice, but this case is rare */
3419 smartlist_t *or_conns = smartlist_new();
3420 SMARTLIST_FOREACH_BEGIN(channels, channel_t *, channel) {
3421 tor_assert(channel); // Suppresses some compiler warnings.
3423 if (!common_ed25519_identity)
3424 common_ed25519_identity = &channel->ed25519_identity;
3426 if (! ed25519_pubkey_eq(&channel->ed25519_identity,
3427 common_ed25519_identity)) {
3428 connection_or_group_set_badness_(or_conns, force);
3429 smartlist_clear(or_conns);
3430 common_ed25519_identity = &channel->ed25519_identity;
3433 smartlist_add(or_conns, BASE_CHAN_TO_TLS(channel)->conn);
3434 } SMARTLIST_FOREACH_END(channel);
3436 connection_or_group_set_badness_(or_conns, force);
3438 /* XXXX 15056 we may want to do something special with connections that have
3439 * no set Ed25519 identity! */
3441 smartlist_free(or_conns);
3442 smartlist_free(channels);
3445 /** Go through all the channels (or if <b>digest</b> is non-NULL, just
3446 * the OR connections with that digest), and set the is_bad_for_new_circs
3447 * flag based on the rules in connection_or_group_set_badness() (or just
3448 * always set it if <b>force</b> is true).
3450 void
3451 channel_update_bad_for_new_circs(const char *digest, int force)
3453 if (digest) {
3454 channel_idmap_entry_t *ent;
3455 channel_idmap_entry_t search;
3456 memset(&search, 0, sizeof(search));
3457 memcpy(search.digest, digest, DIGEST_LEN);
3458 ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
3459 if (ent) {
3460 channel_rsa_id_group_set_badness(&ent->channel_list, force);
3462 return;
3465 /* no digest; just look at everything. */
3466 channel_idmap_entry_t **iter;
3467 HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
3468 channel_rsa_id_group_set_badness(&(*iter)->channel_list, force);