1 /* * Copyright (c) 2012-2020, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
7 * \brief OR/OP-to-OR channel abstraction layer. A channel's job is to
8 * transfer cells from Tor instance to Tor instance. Currently, there is only
9 * one implementation of the channel abstraction: in channeltls.c.
11 * Channels are a higher-level abstraction than or_connection_t: In general,
12 * any means that two Tor relays use to exchange cells, or any means that a
13 * relay and a client use to exchange cells, is a channel.
15 * Channels differ from pluggable transports in that they do not wrap an
16 * underlying protocol over which cells are transmitted: they <em>are</em> the
17 * underlying protocol.
19 * This module defines the generic parts of the channel_t interface, and
20 * provides the machinery necessary for specialized implementations to be
21 * created. At present, there is one specialized implementation in
22 * channeltls.c, which uses connection_or.c to send cells over a TLS
25 * Every channel implementation is responsible for being able to transmit
26 * cells that are passed to it
28 * For *inbound* cells, the entry point is: channel_process_cell(). It takes a
29 * cell and will pass it to the cell handler set by
30 * channel_set_cell_handlers(). Currently, this is passed back to the command
31 * subsystem which is command_process_cell().
33 * NOTE: For now, the separation between channels and specialized channels
34 * (like channeltls) is not that well defined. So the channeltls layer calls
35 * channel_process_cell() which originally comes from the connection subsytem.
36 * This should be hopefully be fixed with #23993.
38 * For *outbound* cells, the entry point is: channel_write_packed_cell().
39 * Only packed cells are dequeued from the circuit queue by the scheduler
40 * which uses channel_flush_from_first_active_circuit() to decide which cells
41 * to flush from which circuit on the channel. They are then passed down to
42 * the channel subsystem. This calls the low layer with the function pointer
43 * .write_packed_cell().
45 * Each specialized channel (currently only channeltls_t) MUST implement a
46 * series of function found in channel_t. See channel.h for more
51 * Define this so channel.h gives us things only channel_t subclasses
54 #define CHANNEL_OBJECT_PRIVATE
56 /* This one's for stuff only channel.c and the test suite should see */
57 #define CHANNEL_FILE_PRIVATE
59 #include "core/or/or.h"
60 #include "app/config/config.h"
61 #include "core/mainloop/mainloop.h"
62 #include "core/or/channel.h"
63 #include "core/or/channelpadding.h"
64 #include "core/or/channeltls.h"
65 #include "core/or/circuitbuild.h"
66 #include "core/or/circuitlist.h"
67 #include "core/or/circuitmux.h"
68 #include "core/or/circuitstats.h"
69 #include "core/or/connection_or.h" /* For var_cell_free() */
70 #include "core/or/dos.h"
71 #include "core/or/relay.h"
72 #include "core/or/scheduler.h"
73 #include "feature/client/entrynodes.h"
74 #include "feature/nodelist/dirlist.h"
75 #include "feature/nodelist/networkstatus.h"
76 #include "feature/nodelist/nodelist.h"
77 #include "feature/nodelist/routerlist.h"
78 #include "feature/relay/router.h"
79 #include "feature/rend/rendservice.h"
80 #include "feature/stats/geoip_stats.h"
81 #include "feature/stats/rephist.h"
82 #include "lib/evloop/timers.h"
83 #include "lib/time/compat_time.h"
85 #include "core/or/cell_queue_st.h"
87 /* Static function prototypes */
89 static bool channel_matches_target_addr_for_extend(
91 const tor_addr_t
*target_ipv4_addr
,
92 const tor_addr_t
*target_ipv6_addr
);
94 /* Global lists of channels */
96 /* All channel_t instances */
97 static smartlist_t
*all_channels
= NULL
;
99 /* All channel_t instances not in ERROR or CLOSED states */
100 static smartlist_t
*active_channels
= NULL
;
102 /* All channel_t instances in ERROR or CLOSED states */
103 static smartlist_t
*finished_channels
= NULL
;
105 /* All channel_listener_t instances */
106 static smartlist_t
*all_listeners
= NULL
;
108 /* All channel_listener_t instances in LISTENING state */
109 static smartlist_t
*active_listeners
= NULL
;
111 /* All channel_listener_t instances in LISTENING state */
112 static smartlist_t
*finished_listeners
= NULL
;
114 /** Map from channel->global_identifier to channel. Contains the same
115 * elements as all_channels. */
116 static HT_HEAD(channel_gid_map
, channel_t
) channel_gid_map
= HT_INITIALIZER();
119 channel_id_hash(const channel_t
*chan
)
121 return (unsigned) chan
->global_identifier
;
124 channel_id_eq(const channel_t
*a
, const channel_t
*b
)
126 return a
->global_identifier
== b
->global_identifier
;
128 HT_PROTOTYPE(channel_gid_map
, channel_t
, gidmap_node
,
129 channel_id_hash
, channel_id_eq
);
130 HT_GENERATE2(channel_gid_map
, channel_t
, gidmap_node
,
131 channel_id_hash
, channel_id_eq
,
132 0.6, tor_reallocarray_
, tor_free_
);
134 HANDLE_IMPL(channel
, channel_t
,)
136 /* Counter for ID numbers */
137 static uint64_t n_channels_allocated
= 0;
139 /* Digest->channel map
141 * Similar to the one used in connection_or.c, this maps from the identity
142 * digest of a remote endpoint to a channel_t to that endpoint. Channels
143 * should be placed here when registered and removed when they close or error.
144 * If more than one channel exists, follow the next_with_same_id pointer
147 static HT_HEAD(channel_idmap
, channel_idmap_entry_t
) channel_identity_map
=
150 typedef struct channel_idmap_entry_t
{
151 HT_ENTRY(channel_idmap_entry_t
) node
;
152 uint8_t digest
[DIGEST_LEN
];
153 TOR_LIST_HEAD(channel_list_t
, channel_t
) channel_list
;
154 } channel_idmap_entry_t
;
156 static inline unsigned
157 channel_idmap_hash(const channel_idmap_entry_t
*ent
)
159 return (unsigned) siphash24g(ent
->digest
, DIGEST_LEN
);
163 channel_idmap_eq(const channel_idmap_entry_t
*a
,
164 const channel_idmap_entry_t
*b
)
166 return tor_memeq(a
->digest
, b
->digest
, DIGEST_LEN
);
169 HT_PROTOTYPE(channel_idmap
, channel_idmap_entry_t
, node
, channel_idmap_hash
,
171 HT_GENERATE2(channel_idmap
, channel_idmap_entry_t
, node
, channel_idmap_hash
,
172 channel_idmap_eq
, 0.5, tor_reallocarray_
, tor_free_
);
174 /* Functions to maintain the digest map */
175 static void channel_remove_from_digest_map(channel_t
*chan
);
177 static void channel_force_xfree(channel_t
*chan
);
178 static void channel_free_list(smartlist_t
*channels
,
180 static void channel_listener_free_list(smartlist_t
*channels
,
182 static void channel_listener_force_xfree(channel_listener_t
*chan_l
);
184 /***********************************
185 * Channel state utility functions *
186 **********************************/
189 * Indicate whether a given channel state is valid.
192 channel_state_is_valid(channel_state_t state
)
197 case CHANNEL_STATE_CLOSED
:
198 case CHANNEL_STATE_CLOSING
:
199 case CHANNEL_STATE_ERROR
:
200 case CHANNEL_STATE_MAINT
:
201 case CHANNEL_STATE_OPENING
:
202 case CHANNEL_STATE_OPEN
:
205 case CHANNEL_STATE_LAST
:
214 * Indicate whether a given channel listener state is valid.
217 channel_listener_state_is_valid(channel_listener_state_t state
)
222 case CHANNEL_LISTENER_STATE_CLOSED
:
223 case CHANNEL_LISTENER_STATE_LISTENING
:
224 case CHANNEL_LISTENER_STATE_CLOSING
:
225 case CHANNEL_LISTENER_STATE_ERROR
:
228 case CHANNEL_LISTENER_STATE_LAST
:
237 * Indicate whether a channel state transition is valid.
239 * This function takes two channel states and indicates whether a
240 * transition between them is permitted (see the state definitions and
241 * transition table in or.h at the channel_state_t typedef).
244 channel_state_can_transition(channel_state_t from
, channel_state_t to
)
249 case CHANNEL_STATE_CLOSED
:
250 is_valid
= (to
== CHANNEL_STATE_OPENING
);
252 case CHANNEL_STATE_CLOSING
:
253 is_valid
= (to
== CHANNEL_STATE_CLOSED
||
254 to
== CHANNEL_STATE_ERROR
);
256 case CHANNEL_STATE_ERROR
:
259 case CHANNEL_STATE_MAINT
:
260 is_valid
= (to
== CHANNEL_STATE_CLOSING
||
261 to
== CHANNEL_STATE_ERROR
||
262 to
== CHANNEL_STATE_OPEN
);
264 case CHANNEL_STATE_OPENING
:
265 is_valid
= (to
== CHANNEL_STATE_CLOSING
||
266 to
== CHANNEL_STATE_ERROR
||
267 to
== CHANNEL_STATE_OPEN
);
269 case CHANNEL_STATE_OPEN
:
270 is_valid
= (to
== CHANNEL_STATE_CLOSING
||
271 to
== CHANNEL_STATE_ERROR
||
272 to
== CHANNEL_STATE_MAINT
);
274 case CHANNEL_STATE_LAST
:
283 * Indicate whether a channel listener state transition is valid.
285 * This function takes two channel listener states and indicates whether a
286 * transition between them is permitted (see the state definitions and
287 * transition table in or.h at the channel_listener_state_t typedef).
290 channel_listener_state_can_transition(channel_listener_state_t from
,
291 channel_listener_state_t to
)
296 case CHANNEL_LISTENER_STATE_CLOSED
:
297 is_valid
= (to
== CHANNEL_LISTENER_STATE_LISTENING
);
299 case CHANNEL_LISTENER_STATE_CLOSING
:
300 is_valid
= (to
== CHANNEL_LISTENER_STATE_CLOSED
||
301 to
== CHANNEL_LISTENER_STATE_ERROR
);
303 case CHANNEL_LISTENER_STATE_ERROR
:
306 case CHANNEL_LISTENER_STATE_LISTENING
:
307 is_valid
= (to
== CHANNEL_LISTENER_STATE_CLOSING
||
308 to
== CHANNEL_LISTENER_STATE_ERROR
);
310 case CHANNEL_LISTENER_STATE_LAST
:
319 * Return a human-readable description for a channel state.
322 channel_state_to_string(channel_state_t state
)
327 case CHANNEL_STATE_CLOSED
:
330 case CHANNEL_STATE_CLOSING
:
333 case CHANNEL_STATE_ERROR
:
334 descr
= "channel error";
336 case CHANNEL_STATE_MAINT
:
337 descr
= "temporarily suspended for maintenance";
339 case CHANNEL_STATE_OPENING
:
342 case CHANNEL_STATE_OPEN
:
345 case CHANNEL_STATE_LAST
:
347 descr
= "unknown or invalid channel state";
354 * Return a human-readable description for a channel listener state.
357 channel_listener_state_to_string(channel_listener_state_t state
)
362 case CHANNEL_LISTENER_STATE_CLOSED
:
365 case CHANNEL_LISTENER_STATE_CLOSING
:
368 case CHANNEL_LISTENER_STATE_ERROR
:
369 descr
= "channel listener error";
371 case CHANNEL_LISTENER_STATE_LISTENING
:
374 case CHANNEL_LISTENER_STATE_LAST
:
376 descr
= "unknown or invalid channel listener state";
382 /***************************************
383 * Channel registration/unregistration *
384 ***************************************/
387 * Register a channel.
389 * This function registers a newly created channel in the global lists/maps
390 * of active channels.
393 channel_register(channel_t
*chan
)
396 tor_assert(chan
->global_identifier
);
398 /* No-op if already registered */
399 if (chan
->registered
) return;
401 log_debug(LD_CHANNEL
,
402 "Registering channel %p (ID %"PRIu64
") "
403 "in state %s (%d) with digest %s",
404 chan
, (chan
->global_identifier
),
405 channel_state_to_string(chan
->state
), chan
->state
,
406 hex_str(chan
->identity_digest
, DIGEST_LEN
));
408 /* Make sure we have all_channels, then add it */
409 if (!all_channels
) all_channels
= smartlist_new();
410 smartlist_add(all_channels
, chan
);
411 channel_t
*oldval
= HT_REPLACE(channel_gid_map
, &channel_gid_map
, chan
);
412 tor_assert(! oldval
);
414 /* Is it finished? */
415 if (CHANNEL_FINISHED(chan
)) {
416 /* Put it in the finished list, creating it if necessary */
417 if (!finished_channels
) finished_channels
= smartlist_new();
418 smartlist_add(finished_channels
, chan
);
419 mainloop_schedule_postloop_cleanup();
421 /* Put it in the active list, creating it if necessary */
422 if (!active_channels
) active_channels
= smartlist_new();
423 smartlist_add(active_channels
, chan
);
425 if (!CHANNEL_IS_CLOSING(chan
)) {
426 /* It should have a digest set */
427 if (!tor_digest_is_zero(chan
->identity_digest
)) {
428 /* Yeah, we're good, add it to the map */
429 channel_add_to_digest_map(chan
);
432 "Channel %p (global ID %"PRIu64
") "
433 "in state %s (%d) registered with no identity digest",
434 chan
, (chan
->global_identifier
),
435 channel_state_to_string(chan
->state
), chan
->state
);
440 /* Mark it as registered */
441 chan
->registered
= 1;
445 * Unregister a channel.
447 * This function removes a channel from the global lists and maps and is used
448 * when freeing a closed/errored channel.
451 channel_unregister(channel_t
*chan
)
455 /* No-op if not registered */
456 if (!(chan
->registered
)) return;
458 /* Is it finished? */
459 if (CHANNEL_FINISHED(chan
)) {
460 /* Get it out of the finished list */
461 if (finished_channels
) smartlist_remove(finished_channels
, chan
);
463 /* Get it out of the active list */
464 if (active_channels
) smartlist_remove(active_channels
, chan
);
467 /* Get it out of all_channels */
468 if (all_channels
) smartlist_remove(all_channels
, chan
);
469 channel_t
*oldval
= HT_REMOVE(channel_gid_map
, &channel_gid_map
, chan
);
470 tor_assert(oldval
== NULL
|| oldval
== chan
);
472 /* Mark it as unregistered */
473 chan
->registered
= 0;
475 /* Should it be in the digest map? */
476 if (!tor_digest_is_zero(chan
->identity_digest
) &&
477 !(CHANNEL_CONDEMNED(chan
))) {
479 channel_remove_from_digest_map(chan
);
484 * Register a channel listener.
486 * This function registers a newly created channel listener in the global
487 * lists/maps of active channel listeners.
490 channel_listener_register(channel_listener_t
*chan_l
)
494 /* No-op if already registered */
495 if (chan_l
->registered
) return;
497 log_debug(LD_CHANNEL
,
498 "Registering channel listener %p (ID %"PRIu64
") "
500 chan_l
, (chan_l
->global_identifier
),
501 channel_listener_state_to_string(chan_l
->state
),
504 /* Make sure we have all_listeners, then add it */
505 if (!all_listeners
) all_listeners
= smartlist_new();
506 smartlist_add(all_listeners
, chan_l
);
508 /* Is it finished? */
509 if (chan_l
->state
== CHANNEL_LISTENER_STATE_CLOSED
||
510 chan_l
->state
== CHANNEL_LISTENER_STATE_ERROR
) {
511 /* Put it in the finished list, creating it if necessary */
512 if (!finished_listeners
) finished_listeners
= smartlist_new();
513 smartlist_add(finished_listeners
, chan_l
);
515 /* Put it in the active list, creating it if necessary */
516 if (!active_listeners
) active_listeners
= smartlist_new();
517 smartlist_add(active_listeners
, chan_l
);
520 /* Mark it as registered */
521 chan_l
->registered
= 1;
525 * Unregister a channel listener.
527 * This function removes a channel listener from the global lists and maps
528 * and is used when freeing a closed/errored channel listener.
531 channel_listener_unregister(channel_listener_t
*chan_l
)
535 /* No-op if not registered */
536 if (!(chan_l
->registered
)) return;
538 /* Is it finished? */
539 if (chan_l
->state
== CHANNEL_LISTENER_STATE_CLOSED
||
540 chan_l
->state
== CHANNEL_LISTENER_STATE_ERROR
) {
541 /* Get it out of the finished list */
542 if (finished_listeners
) smartlist_remove(finished_listeners
, chan_l
);
544 /* Get it out of the active list */
545 if (active_listeners
) smartlist_remove(active_listeners
, chan_l
);
548 /* Get it out of all_listeners */
549 if (all_listeners
) smartlist_remove(all_listeners
, chan_l
);
551 /* Mark it as unregistered */
552 chan_l
->registered
= 0;
555 /*********************************
556 * Channel digest map maintenance
557 *********************************/
560 * Add a channel to the digest map.
562 * This function adds a channel to the digest map and inserts it into the
563 * correct linked list if channels with that remote endpoint identity digest
567 channel_add_to_digest_map(channel_t
*chan
)
569 channel_idmap_entry_t
*ent
, search
;
573 /* Assert that the state makes sense */
574 tor_assert(!CHANNEL_CONDEMNED(chan
));
576 /* Assert that there is a digest */
577 tor_assert(!tor_digest_is_zero(chan
->identity_digest
));
579 memcpy(search
.digest
, chan
->identity_digest
, DIGEST_LEN
);
580 ent
= HT_FIND(channel_idmap
, &channel_identity_map
, &search
);
582 ent
= tor_malloc(sizeof(channel_idmap_entry_t
));
583 memcpy(ent
->digest
, chan
->identity_digest
, DIGEST_LEN
);
584 TOR_LIST_INIT(&ent
->channel_list
);
585 HT_INSERT(channel_idmap
, &channel_identity_map
, ent
);
587 TOR_LIST_INSERT_HEAD(&ent
->channel_list
, chan
, next_with_same_id
);
589 log_debug(LD_CHANNEL
,
590 "Added channel %p (global ID %"PRIu64
") "
591 "to identity map in state %s (%d) with digest %s",
592 chan
, (chan
->global_identifier
),
593 channel_state_to_string(chan
->state
), chan
->state
,
594 hex_str(chan
->identity_digest
, DIGEST_LEN
));
598 * Remove a channel from the digest map.
600 * This function removes a channel from the digest map and the linked list of
601 * channels for that digest if more than one exists.
604 channel_remove_from_digest_map(channel_t
*chan
)
606 channel_idmap_entry_t
*ent
, search
;
610 /* Assert that there is a digest */
611 tor_assert(!tor_digest_is_zero(chan
->identity_digest
));
613 /* Pull it out of its list, wherever that list is */
614 TOR_LIST_REMOVE(chan
, next_with_same_id
);
616 memcpy(search
.digest
, chan
->identity_digest
, DIGEST_LEN
);
617 ent
= HT_FIND(channel_idmap
, &channel_identity_map
, &search
);
619 /* Look for it in the map */
621 /* Okay, it's here */
623 if (TOR_LIST_EMPTY(&ent
->channel_list
)) {
624 HT_REMOVE(channel_idmap
, &channel_identity_map
, ent
);
628 log_debug(LD_CHANNEL
,
629 "Removed channel %p (global ID %"PRIu64
") from "
630 "identity map in state %s (%d) with digest %s",
631 chan
, (chan
->global_identifier
),
632 channel_state_to_string(chan
->state
), chan
->state
,
633 hex_str(chan
->identity_digest
, DIGEST_LEN
));
635 /* Shouldn't happen */
637 "Trying to remove channel %p (global ID %"PRIu64
") with "
638 "digest %s from identity map, but couldn't find any with "
640 chan
, (chan
->global_identifier
),
641 hex_str(chan
->identity_digest
, DIGEST_LEN
));
645 /****************************
646 * Channel lookup functions *
647 ***************************/
650 * Find channel by global ID.
652 * This function searches for a channel by the global_identifier assigned
653 * at initialization time. This identifier is unique for the lifetime of the
657 channel_find_by_global_id(uint64_t global_identifier
)
660 channel_t
*rv
= NULL
;
662 lookup
.global_identifier
= global_identifier
;
663 rv
= HT_FIND(channel_gid_map
, &channel_gid_map
, &lookup
);
665 tor_assert(rv
->global_identifier
== global_identifier
);
671 /** Return true iff <b>chan</b> matches <b>rsa_id_digest</b> and <b>ed_id</b>.
672 * as its identity keys. If either is NULL, do not check for a match. */
674 channel_remote_identity_matches(const channel_t
*chan
,
675 const char *rsa_id_digest
,
676 const ed25519_public_key_t
*ed_id
)
681 if (tor_memneq(rsa_id_digest
, chan
->identity_digest
, DIGEST_LEN
))
685 if (tor_memneq(ed_id
->pubkey
, chan
->ed25519_identity
.pubkey
,
693 * Find channel by RSA/Ed25519 identity of of the remote endpoint.
695 * This function looks up a channel by the digest of its remote endpoint's RSA
696 * identity key. If <b>ed_id</b> is provided and nonzero, only a channel
697 * matching the <b>ed_id</b> will be returned.
699 * It's possible that more than one channel to a given endpoint exists. Use
700 * channel_next_with_rsa_identity() to walk the list of channels; make sure
701 * to test for Ed25519 identity match too (as appropriate)
704 channel_find_by_remote_identity(const char *rsa_id_digest
,
705 const ed25519_public_key_t
*ed_id
)
707 channel_t
*rv
= NULL
;
708 channel_idmap_entry_t
*ent
, search
;
710 tor_assert(rsa_id_digest
); /* For now, we require that every channel have
711 * an RSA identity, and that every lookup
712 * contain an RSA identity */
713 if (ed_id
&& ed25519_public_key_is_zero(ed_id
)) {
714 /* Treat zero as meaning "We don't care about the presence or absence of
715 * an Ed key", not "There must be no Ed key". */
719 memcpy(search
.digest
, rsa_id_digest
, DIGEST_LEN
);
720 ent
= HT_FIND(channel_idmap
, &channel_identity_map
, &search
);
722 rv
= TOR_LIST_FIRST(&ent
->channel_list
);
724 while (rv
&& ! channel_remote_identity_matches(rv
, rsa_id_digest
, ed_id
)) {
725 rv
= channel_next_with_rsa_identity(rv
);
732 * Get next channel with digest.
734 * This function takes a channel and finds the next channel in the list
735 * with the same digest.
738 channel_next_with_rsa_identity(channel_t
*chan
)
742 return TOR_LIST_NEXT(chan
, next_with_same_id
);
746 * Relays run this once an hour to look over our list of channels to other
747 * relays. It prints out some statistics if there are multiple connections
750 * This function is similar to connection_or_set_bad_connections(),
751 * and probably could be adapted to replace it, if it was modified to actually
752 * take action on any of these connections.
755 channel_check_for_duplicates(void)
757 channel_idmap_entry_t
**iter
;
759 int total_dirauth_connections
= 0, total_dirauths
= 0;
760 int total_relay_connections
= 0, total_relays
= 0, total_canonical
= 0;
761 int total_half_canonical
= 0;
762 int total_gt_one_connection
= 0, total_gt_two_connections
= 0;
763 int total_gt_four_connections
= 0;
765 HT_FOREACH(iter
, channel_idmap
, &channel_identity_map
) {
766 int connections_to_relay
= 0;
767 const char *id_digest
= (char *) (*iter
)->digest
;
769 /* Only consider relay connections */
770 if (!connection_or_digest_is_known_relay(id_digest
))
775 const bool is_dirauth
= router_digest_is_trusted_dir(id_digest
);
779 for (chan
= TOR_LIST_FIRST(&(*iter
)->channel_list
); chan
;
780 chan
= channel_next_with_rsa_identity(chan
)) {
782 if (CHANNEL_CONDEMNED(chan
) || !CHANNEL_IS_OPEN(chan
))
785 connections_to_relay
++;
786 total_relay_connections
++;
788 total_dirauth_connections
++;
790 if (chan
->is_canonical(chan
)) total_canonical
++;
792 if (!chan
->is_canonical_to_peer
&& chan
->is_canonical(chan
)) {
793 total_half_canonical
++;
797 if (connections_to_relay
> 1) total_gt_one_connection
++;
798 if (connections_to_relay
> 2) total_gt_two_connections
++;
799 if (connections_to_relay
> 4) total_gt_four_connections
++;
802 /* Don't bother warning about excessive connections unless we have
803 * at least this many connections, total.
805 #define MIN_RELAY_CONNECTIONS_TO_WARN 25
806 /* If the average number of connections for a regular relay is more than
807 * this, that's too high.
809 #define MAX_AVG_RELAY_CONNECTIONS 1.5
810 /* If the average number of connections for a dirauth is more than
811 * this, that's too high.
813 #define MAX_AVG_DIRAUTH_CONNECTIONS 4
815 /* How many connections total would be okay, given the number of
816 * relays and dirauths that we have connections to? */
817 const int max_tolerable_connections
= (int)(
818 (total_relays
-total_dirauths
) * MAX_AVG_RELAY_CONNECTIONS
+
819 total_dirauths
* MAX_AVG_DIRAUTH_CONNECTIONS
);
821 /* If we average 1.5 or more connections per relay, something is wrong */
822 if (total_relays
> MIN_RELAY_CONNECTIONS_TO_WARN
&&
823 total_relay_connections
> max_tolerable_connections
) {
825 "Your relay has a very large number of connections to other relays. "
826 "Is your outbound address the same as your relay address? "
827 "Found %d connections to %d relays. Found %d current canonical "
828 "connections, in %d of which we were a non-canonical peer. "
829 "%d relays had more than 1 connection, %d had more than 2, and "
830 "%d had more than 4 connections.",
831 total_relay_connections
, total_relays
, total_canonical
,
832 total_half_canonical
, total_gt_one_connection
,
833 total_gt_two_connections
, total_gt_four_connections
);
835 log_info(LD_OR
, "Performed connection pruning. "
836 "Found %d connections to %d relays. Found %d current canonical "
837 "connections, in %d of which we were a non-canonical peer. "
838 "%d relays had more than 1 connection, %d had more than 2, and "
839 "%d had more than 4 connections.",
840 total_relay_connections
, total_relays
, total_canonical
,
841 total_half_canonical
, total_gt_one_connection
,
842 total_gt_two_connections
, total_gt_four_connections
);
847 * Initialize a channel.
849 * This function should be called by subclasses to set up some per-channel
850 * variables. I.e., this is the superclass constructor. Before this, the
851 * channel should be allocated with tor_malloc_zero().
854 channel_init(channel_t
*chan
)
858 /* Assign an ID and bump the counter */
859 chan
->global_identifier
= ++n_channels_allocated
;
862 chan
->timestamp_last_had_circuits
= time(NULL
);
864 /* Warn about exhausted circuit IDs no more than hourly. */
865 chan
->last_warned_circ_ids_exhausted
.rate
= 3600;
867 /* Initialize list entries. */
868 memset(&chan
->next_with_same_id
, 0, sizeof(chan
->next_with_same_id
));
871 channel_timestamp_created(chan
);
873 /* It hasn't been open yet. */
874 chan
->has_been_open
= 0;
876 /* Scheduler state is idle */
877 chan
->scheduler_state
= SCHED_CHAN_IDLE
;
879 /* Channel is not in the scheduler heap. */
880 chan
->sched_heap_idx
= -1;
884 * Initialize a channel listener.
886 * This function should be called by subclasses to set up some per-channel
887 * variables. I.e., this is the superclass constructor. Before this, the
888 * channel listener should be allocated with tor_malloc_zero().
891 channel_init_listener(channel_listener_t
*chan_l
)
895 /* Assign an ID and bump the counter */
896 chan_l
->global_identifier
= ++n_channels_allocated
;
899 channel_listener_timestamp_created(chan_l
);
903 * Free a channel; nothing outside of channel.c and subclasses should call
904 * this - it frees channels after they have closed and been unregistered.
907 channel_free_(channel_t
*chan
)
911 /* It must be closed or errored */
912 tor_assert(CHANNEL_FINISHED(chan
));
914 /* It must be deregistered */
915 tor_assert(!(chan
->registered
));
917 log_debug(LD_CHANNEL
,
918 "Freeing channel %"PRIu64
" at %p",
919 (chan
->global_identifier
), chan
);
921 /* Get this one out of the scheduler */
922 scheduler_release_channel(chan
);
925 * Get rid of cmux policy before we do anything, so cmux policies don't
926 * see channels in weird half-freed states.
929 circuitmux_set_policy(chan
->cmux
, NULL
);
932 /* Remove all timers and associated handle entries now */
933 timer_free(chan
->padding_timer
);
934 channel_handle_free(chan
->timer_handle
);
935 channel_handles_clear(chan
);
937 /* Call a free method if there is one */
938 if (chan
->free_fn
) chan
->free_fn(chan
);
940 channel_clear_remote_end(chan
);
942 /* Get rid of cmux */
944 circuitmux_detach_all_circuits(chan
->cmux
, NULL
);
945 circuitmux_mark_destroyed_circids_usable(chan
->cmux
, chan
);
946 circuitmux_free(chan
->cmux
);
954 * Free a channel listener; nothing outside of channel.c and subclasses
955 * should call this - it frees channel listeners after they have closed and
959 channel_listener_free_(channel_listener_t
*chan_l
)
963 log_debug(LD_CHANNEL
,
964 "Freeing channel_listener_t %"PRIu64
" at %p",
965 (chan_l
->global_identifier
),
968 /* It must be closed or errored */
969 tor_assert(chan_l
->state
== CHANNEL_LISTENER_STATE_CLOSED
||
970 chan_l
->state
== CHANNEL_LISTENER_STATE_ERROR
);
971 /* It must be deregistered */
972 tor_assert(!(chan_l
->registered
));
974 /* Call a free method if there is one */
975 if (chan_l
->free_fn
) chan_l
->free_fn(chan_l
);
981 * Free a channel and skip the state/registration asserts; this internal-
982 * use-only function should be called only from channel_free_all() when
983 * shutting down the Tor process.
986 channel_force_xfree(channel_t
*chan
)
990 log_debug(LD_CHANNEL
,
991 "Force-freeing channel %"PRIu64
" at %p",
992 (chan
->global_identifier
), chan
);
994 /* Get this one out of the scheduler */
995 scheduler_release_channel(chan
);
998 * Get rid of cmux policy before we do anything, so cmux policies don't
999 * see channels in weird half-freed states.
1002 circuitmux_set_policy(chan
->cmux
, NULL
);
1005 /* Remove all timers and associated handle entries now */
1006 timer_free(chan
->padding_timer
);
1007 channel_handle_free(chan
->timer_handle
);
1008 channel_handles_clear(chan
);
1010 /* Call a free method if there is one */
1011 if (chan
->free_fn
) chan
->free_fn(chan
);
1013 channel_clear_remote_end(chan
);
1015 /* Get rid of cmux */
1017 circuitmux_free(chan
->cmux
);
1025 * Free a channel listener and skip the state/registration asserts; this
1026 * internal-use-only function should be called only from channel_free_all()
1027 * when shutting down the Tor process.
1030 channel_listener_force_xfree(channel_listener_t
*chan_l
)
1034 log_debug(LD_CHANNEL
,
1035 "Force-freeing channel_listener_t %"PRIu64
" at %p",
1036 (chan_l
->global_identifier
),
1039 /* Call a free method if there is one */
1040 if (chan_l
->free_fn
) chan_l
->free_fn(chan_l
);
1043 * The incoming list just gets emptied and freed; we request close on
1044 * any channels we find there, but since we got called while shutting
1045 * down they will get deregistered and freed elsewhere anyway.
1047 if (chan_l
->incoming_list
) {
1048 SMARTLIST_FOREACH_BEGIN(chan_l
->incoming_list
,
1049 channel_t
*, qchan
) {
1050 channel_mark_for_close(qchan
);
1051 } SMARTLIST_FOREACH_END(qchan
);
1053 smartlist_free(chan_l
->incoming_list
);
1054 chan_l
->incoming_list
= NULL
;
1061 * Set the listener for a channel listener.
1063 * This function sets the handler for new incoming channels on a channel
1067 channel_listener_set_listener_fn(channel_listener_t
*chan_l
,
1068 channel_listener_fn_ptr listener
)
1071 tor_assert(chan_l
->state
== CHANNEL_LISTENER_STATE_LISTENING
);
1073 log_debug(LD_CHANNEL
,
1074 "Setting listener callback for channel listener %p "
1075 "(global ID %"PRIu64
") to %p",
1076 chan_l
, (chan_l
->global_identifier
),
1079 chan_l
->listener
= listener
;
1080 if (chan_l
->listener
) channel_listener_process_incoming(chan_l
);
1084 * Return the fixed-length cell handler for a channel.
1086 * This function gets the handler for incoming fixed-length cells installed
1089 channel_cell_handler_fn_ptr
1090 channel_get_cell_handler(channel_t
*chan
)
1094 if (CHANNEL_CAN_HANDLE_CELLS(chan
))
1095 return chan
->cell_handler
;
1101 * Set both cell handlers for a channel.
1103 * This function sets both the fixed-length and variable length cell handlers
1107 channel_set_cell_handlers(channel_t
*chan
,
1108 channel_cell_handler_fn_ptr cell_handler
)
1111 tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan
));
1113 log_debug(LD_CHANNEL
,
1114 "Setting cell_handler callback for channel %p to %p",
1115 chan
, cell_handler
);
1118 chan
->cell_handler
= cell_handler
;
1122 * On closing channels
1124 * There are three functions that close channels, for use in
1125 * different circumstances:
1127 * - Use channel_mark_for_close() for most cases
1128 * - Use channel_close_from_lower_layer() if you are connection_or.c
1129 * and the other end closes the underlying connection.
1130 * - Use channel_close_for_error() if you are connection_or.c and
1131 * some sort of error has occurred.
1135 * Mark a channel for closure.
1137 * This function tries to close a channel_t; it will go into the CLOSING
1138 * state, and eventually the lower layer should put it into the CLOSED or
1139 * ERROR state. Then, channel_run_cleanup() will eventually free it.
1142 channel_mark_for_close(channel_t
*chan
)
1144 tor_assert(chan
!= NULL
);
1145 tor_assert(chan
->close
!= NULL
);
1147 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1148 if (CHANNEL_CONDEMNED(chan
))
1151 log_debug(LD_CHANNEL
,
1152 "Closing channel %p (global ID %"PRIu64
") "
1154 chan
, (chan
->global_identifier
));
1156 /* Note closing by request from above */
1157 chan
->reason_for_closing
= CHANNEL_CLOSE_REQUESTED
;
1159 /* Change state to CLOSING */
1160 channel_change_state(chan
, CHANNEL_STATE_CLOSING
);
1162 /* Tell the lower layer */
1166 * It's up to the lower layer to change state to CLOSED or ERROR when we're
1167 * ready; we'll try to free channels that are in the finished list from
1168 * channel_run_cleanup(). The lower layer should do this by calling
1174 * Mark a channel listener for closure.
1176 * This function tries to close a channel_listener_t; it will go into the
1177 * CLOSING state, and eventually the lower layer should put it into the CLOSED
1178 * or ERROR state. Then, channel_run_cleanup() will eventually free it.
1181 channel_listener_mark_for_close(channel_listener_t
*chan_l
)
1183 tor_assert(chan_l
!= NULL
);
1184 tor_assert(chan_l
->close
!= NULL
);
1186 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1187 if (chan_l
->state
== CHANNEL_LISTENER_STATE_CLOSING
||
1188 chan_l
->state
== CHANNEL_LISTENER_STATE_CLOSED
||
1189 chan_l
->state
== CHANNEL_LISTENER_STATE_ERROR
) return;
1191 log_debug(LD_CHANNEL
,
1192 "Closing channel listener %p (global ID %"PRIu64
") "
1194 chan_l
, (chan_l
->global_identifier
));
1196 /* Note closing by request from above */
1197 chan_l
->reason_for_closing
= CHANNEL_LISTENER_CLOSE_REQUESTED
;
1199 /* Change state to CLOSING */
1200 channel_listener_change_state(chan_l
, CHANNEL_LISTENER_STATE_CLOSING
);
1202 /* Tell the lower layer */
1203 chan_l
->close(chan_l
);
1206 * It's up to the lower layer to change state to CLOSED or ERROR when we're
1207 * ready; we'll try to free channels that are in the finished list from
1208 * channel_run_cleanup(). The lower layer should do this by calling
1209 * channel_listener_closed().
1214 * Close a channel from the lower layer.
1216 * Notify the channel code that the channel is being closed due to a non-error
1217 * condition in the lower layer. This does not call the close() method, since
1218 * the lower layer already knows.
1221 channel_close_from_lower_layer(channel_t
*chan
)
1223 tor_assert(chan
!= NULL
);
1225 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1226 if (CHANNEL_CONDEMNED(chan
))
1229 log_debug(LD_CHANNEL
,
1230 "Closing channel %p (global ID %"PRIu64
") "
1231 "due to lower-layer event",
1232 chan
, (chan
->global_identifier
));
1234 /* Note closing by event from below */
1235 chan
->reason_for_closing
= CHANNEL_CLOSE_FROM_BELOW
;
1237 /* Change state to CLOSING */
1238 channel_change_state(chan
, CHANNEL_STATE_CLOSING
);
1242 * Notify that the channel is being closed due to an error condition.
1244 * This function is called by the lower layer implementing the transport
1245 * when a channel must be closed due to an error condition. This does not
1246 * call the channel's close method, since the lower layer already knows.
1249 channel_close_for_error(channel_t
*chan
)
1251 tor_assert(chan
!= NULL
);
1253 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1254 if (CHANNEL_CONDEMNED(chan
))
1257 log_debug(LD_CHANNEL
,
1258 "Closing channel %p due to lower-layer error",
1261 /* Note closing by event from below */
1262 chan
->reason_for_closing
= CHANNEL_CLOSE_FOR_ERROR
;
1264 /* Change state to CLOSING */
1265 channel_change_state(chan
, CHANNEL_STATE_CLOSING
);
1269 * Notify that the lower layer is finished closing the channel.
1271 * This function should be called by the lower layer when a channel
1272 * is finished closing and it should be regarded as inactive and
1273 * freed by the channel code.
1276 channel_closed(channel_t
*chan
)
1279 tor_assert(CHANNEL_CONDEMNED(chan
));
1281 /* No-op if already inactive */
1282 if (CHANNEL_FINISHED(chan
))
1285 /* Inform any pending (not attached) circs that they should
1287 if (! chan
->has_been_open
)
1288 circuit_n_chan_done(chan
, 0, 0);
1290 /* Now close all the attached circuits on it. */
1291 circuit_unlink_all_from_channel(chan
, END_CIRC_REASON_CHANNEL_CLOSED
);
1293 if (chan
->reason_for_closing
!= CHANNEL_CLOSE_FOR_ERROR
) {
1294 channel_change_state(chan
, CHANNEL_STATE_CLOSED
);
1296 channel_change_state(chan
, CHANNEL_STATE_ERROR
);
1301 * Clear the identity_digest of a channel.
1303 * This function clears the identity digest of the remote endpoint for a
1304 * channel; this is intended for use by the lower layer.
1307 channel_clear_identity_digest(channel_t
*chan
)
1309 int state_not_in_map
;
1313 log_debug(LD_CHANNEL
,
1314 "Clearing remote endpoint digest on channel %p with "
1315 "global ID %"PRIu64
,
1316 chan
, (chan
->global_identifier
));
1318 state_not_in_map
= CHANNEL_CONDEMNED(chan
);
1320 if (!state_not_in_map
&& chan
->registered
&&
1321 !tor_digest_is_zero(chan
->identity_digest
))
1322 /* if it's registered get it out of the digest map */
1323 channel_remove_from_digest_map(chan
);
1325 memset(chan
->identity_digest
, 0,
1326 sizeof(chan
->identity_digest
));
1330 * Set the identity_digest of a channel.
1332 * This function sets the identity digest of the remote endpoint for a
1333 * channel; this is intended for use by the lower layer.
1336 channel_set_identity_digest(channel_t
*chan
,
1337 const char *identity_digest
,
1338 const ed25519_public_key_t
*ed_identity
)
1340 int was_in_digest_map
, should_be_in_digest_map
, state_not_in_map
;
1344 log_debug(LD_CHANNEL
,
1345 "Setting remote endpoint digest on channel %p with "
1346 "global ID %"PRIu64
" to digest %s",
1347 chan
, (chan
->global_identifier
),
1349 hex_str(identity_digest
, DIGEST_LEN
) : "(null)");
1351 state_not_in_map
= CHANNEL_CONDEMNED(chan
);
1354 !state_not_in_map
&&
1356 !tor_digest_is_zero(chan
->identity_digest
);
1357 should_be_in_digest_map
=
1358 !state_not_in_map
&&
1361 !tor_digest_is_zero(identity_digest
));
1363 if (was_in_digest_map
)
1364 /* We should always remove it; we'll add it back if we're writing
1367 channel_remove_from_digest_map(chan
);
1369 if (identity_digest
) {
1370 memcpy(chan
->identity_digest
,
1372 sizeof(chan
->identity_digest
));
1374 memset(chan
->identity_digest
, 0,
1375 sizeof(chan
->identity_digest
));
1378 memcpy(&chan
->ed25519_identity
, ed_identity
, sizeof(*ed_identity
));
1380 memset(&chan
->ed25519_identity
, 0, sizeof(*ed_identity
));
1383 /* Put it in the digest map if we should */
1384 if (should_be_in_digest_map
)
1385 channel_add_to_digest_map(chan
);
1389 * Clear the remote end metadata (identity_digest) of a channel.
1391 * This function clears all the remote end info from a channel; this is
1392 * intended for use by the lower layer.
1395 channel_clear_remote_end(channel_t
*chan
)
1397 int state_not_in_map
;
1401 log_debug(LD_CHANNEL
,
1402 "Clearing remote endpoint identity on channel %p with "
1403 "global ID %"PRIu64
,
1404 chan
, (chan
->global_identifier
));
1406 state_not_in_map
= CHANNEL_CONDEMNED(chan
);
1408 if (!state_not_in_map
&& chan
->registered
&&
1409 !tor_digest_is_zero(chan
->identity_digest
))
1410 /* if it's registered get it out of the digest map */
1411 channel_remove_from_digest_map(chan
);
1413 memset(chan
->identity_digest
, 0,
1414 sizeof(chan
->identity_digest
));
1418 * Write to a channel the given packed cell.
1420 * Two possible errors can happen. Either the channel is not opened or the
1421 * lower layer (specialized channel) failed to write it. In both cases, it is
1422 * the caller responsibility to free the cell.
1425 write_packed_cell(channel_t
*chan
, packed_cell_t
*cell
)
1429 uint8_t command
= packed_cell_get_command(cell
, chan
->wide_circ_ids
);
1434 /* Assert that the state makes sense for a cell write */
1435 tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan
));
1439 if (packed_cell_is_destroy(chan
, cell
, &circ_id
)) {
1440 channel_note_destroy_not_pending(chan
, circ_id
);
1444 /* For statistical purposes, figure out how big this cell is */
1445 cell_bytes
= get_cell_network_size(chan
->wide_circ_ids
);
1447 /* Can we send it right out? If so, try */
1448 if (!CHANNEL_IS_OPEN(chan
)) {
1452 /* Write the cell on the connection's outbuf. */
1453 if (chan
->write_packed_cell(chan
, cell
) < 0) {
1456 /* Timestamp for transmission */
1457 channel_timestamp_xmit(chan
);
1458 /* Update the counter */
1459 ++(chan
->n_cells_xmitted
);
1460 chan
->n_bytes_xmitted
+= cell_bytes
;
1461 /* Successfully sent the cell. */
1464 /* Update padding statistics for the packed codepath.. */
1465 rep_hist_padding_count_write(PADDING_TYPE_TOTAL
);
1466 if (command
== CELL_PADDING
)
1467 rep_hist_padding_count_write(PADDING_TYPE_CELL
);
1468 if (chan
->padding_enabled
) {
1469 rep_hist_padding_count_write(PADDING_TYPE_ENABLED_TOTAL
);
1470 if (command
== CELL_PADDING
)
1471 rep_hist_padding_count_write(PADDING_TYPE_ENABLED_CELL
);
1479 * Write a packed cell to a channel.
1481 * Write a packed cell to a channel using the write_cell() method. This is
1482 * called by the transport-independent code to deliver a packed cell to a
1483 * channel for transmission.
1485 * Return 0 on success else a negative value. In both cases, the caller should
1486 * not access the cell anymore, it is freed both on success and error.
1489 channel_write_packed_cell(channel_t
*chan
, packed_cell_t
*cell
)
1496 if (CHANNEL_IS_CLOSING(chan
)) {
1497 log_debug(LD_CHANNEL
, "Discarding %p on closing channel %p with "
1498 "global ID %"PRIu64
, cell
, chan
,
1499 (chan
->global_identifier
));
1502 log_debug(LD_CHANNEL
,
1503 "Writing %p to channel %p with global ID "
1504 "%"PRIu64
, cell
, chan
, (chan
->global_identifier
));
1506 ret
= write_packed_cell(chan
, cell
);
1509 /* Whatever happens, we free the cell. Either an error occurred or the cell
1510 * was put on the connection outbuf, both cases we have ownership of the
1511 * cell and we free it. */
1512 packed_cell_free(cell
);
1517 * Change channel state.
1519 * This internal and subclass use only function is used to change channel
1520 * state, performing all transition validity checks and whatever actions
1521 * are appropriate to the state transition in question.
1524 channel_change_state_(channel_t
*chan
, channel_state_t to_state
)
1526 channel_state_t from_state
;
1527 unsigned char was_active
, is_active
;
1528 unsigned char was_in_id_map
, is_in_id_map
;
1531 from_state
= chan
->state
;
1533 tor_assert(channel_state_is_valid(from_state
));
1534 tor_assert(channel_state_is_valid(to_state
));
1535 tor_assert(channel_state_can_transition(chan
->state
, to_state
));
1537 /* Check for no-op transitions */
1538 if (from_state
== to_state
) {
1539 log_debug(LD_CHANNEL
,
1540 "Got no-op transition from \"%s\" to itself on channel %p"
1541 "(global ID %"PRIu64
")",
1542 channel_state_to_string(to_state
),
1543 chan
, (chan
->global_identifier
));
1547 /* If we're going to a closing or closed state, we must have a reason set */
1548 if (to_state
== CHANNEL_STATE_CLOSING
||
1549 to_state
== CHANNEL_STATE_CLOSED
||
1550 to_state
== CHANNEL_STATE_ERROR
) {
1551 tor_assert(chan
->reason_for_closing
!= CHANNEL_NOT_CLOSING
);
1554 log_debug(LD_CHANNEL
,
1555 "Changing state of channel %p (global ID %"PRIu64
1556 ") from \"%s\" to \"%s\"",
1558 (chan
->global_identifier
),
1559 channel_state_to_string(chan
->state
),
1560 channel_state_to_string(to_state
));
1562 chan
->state
= to_state
;
1564 /* Need to add to the right lists if the channel is registered */
1565 if (chan
->registered
) {
1566 was_active
= !(from_state
== CHANNEL_STATE_CLOSED
||
1567 from_state
== CHANNEL_STATE_ERROR
);
1568 is_active
= !(to_state
== CHANNEL_STATE_CLOSED
||
1569 to_state
== CHANNEL_STATE_ERROR
);
1571 /* Need to take off active list and put on finished list? */
1572 if (was_active
&& !is_active
) {
1573 if (active_channels
) smartlist_remove(active_channels
, chan
);
1574 if (!finished_channels
) finished_channels
= smartlist_new();
1575 smartlist_add(finished_channels
, chan
);
1576 mainloop_schedule_postloop_cleanup();
1578 /* Need to put on active list? */
1579 else if (!was_active
&& is_active
) {
1580 if (finished_channels
) smartlist_remove(finished_channels
, chan
);
1581 if (!active_channels
) active_channels
= smartlist_new();
1582 smartlist_add(active_channels
, chan
);
1585 if (!tor_digest_is_zero(chan
->identity_digest
)) {
1586 /* Now we need to handle the identity map */
1587 was_in_id_map
= !(from_state
== CHANNEL_STATE_CLOSING
||
1588 from_state
== CHANNEL_STATE_CLOSED
||
1589 from_state
== CHANNEL_STATE_ERROR
);
1590 is_in_id_map
= !(to_state
== CHANNEL_STATE_CLOSING
||
1591 to_state
== CHANNEL_STATE_CLOSED
||
1592 to_state
== CHANNEL_STATE_ERROR
);
1594 if (!was_in_id_map
&& is_in_id_map
) channel_add_to_digest_map(chan
);
1595 else if (was_in_id_map
&& !is_in_id_map
)
1596 channel_remove_from_digest_map(chan
);
1601 * If we're going to a closed/closing state, we don't need scheduling any
1602 * more; in CHANNEL_STATE_MAINT we can't accept writes.
1604 if (to_state
== CHANNEL_STATE_CLOSING
||
1605 to_state
== CHANNEL_STATE_CLOSED
||
1606 to_state
== CHANNEL_STATE_ERROR
) {
1607 scheduler_release_channel(chan
);
1608 } else if (to_state
== CHANNEL_STATE_MAINT
) {
1609 scheduler_channel_doesnt_want_writes(chan
);
1614 * As channel_change_state_, but change the state to any state but open.
1617 channel_change_state(channel_t
*chan
, channel_state_t to_state
)
1619 tor_assert(to_state
!= CHANNEL_STATE_OPEN
);
1620 channel_change_state_(chan
, to_state
);
1624 * As channel_change_state, but change the state to open.
1627 channel_change_state_open(channel_t
*chan
)
1629 channel_change_state_(chan
, CHANNEL_STATE_OPEN
);
1631 /* Tell circuits if we opened and stuff */
1632 channel_do_open_actions(chan
);
1633 chan
->has_been_open
= 1;
1637 * Change channel listener state.
1639 * This internal and subclass use only function is used to change channel
1640 * listener state, performing all transition validity checks and whatever
1641 * actions are appropriate to the state transition in question.
1644 channel_listener_change_state(channel_listener_t
*chan_l
,
1645 channel_listener_state_t to_state
)
1647 channel_listener_state_t from_state
;
1648 unsigned char was_active
, is_active
;
1651 from_state
= chan_l
->state
;
1653 tor_assert(channel_listener_state_is_valid(from_state
));
1654 tor_assert(channel_listener_state_is_valid(to_state
));
1655 tor_assert(channel_listener_state_can_transition(chan_l
->state
, to_state
));
1657 /* Check for no-op transitions */
1658 if (from_state
== to_state
) {
1659 log_debug(LD_CHANNEL
,
1660 "Got no-op transition from \"%s\" to itself on channel "
1661 "listener %p (global ID %"PRIu64
")",
1662 channel_listener_state_to_string(to_state
),
1663 chan_l
, (chan_l
->global_identifier
));
1667 /* If we're going to a closing or closed state, we must have a reason set */
1668 if (to_state
== CHANNEL_LISTENER_STATE_CLOSING
||
1669 to_state
== CHANNEL_LISTENER_STATE_CLOSED
||
1670 to_state
== CHANNEL_LISTENER_STATE_ERROR
) {
1671 tor_assert(chan_l
->reason_for_closing
!= CHANNEL_LISTENER_NOT_CLOSING
);
1674 log_debug(LD_CHANNEL
,
1675 "Changing state of channel listener %p (global ID %"PRIu64
1676 "from \"%s\" to \"%s\"",
1677 chan_l
, (chan_l
->global_identifier
),
1678 channel_listener_state_to_string(chan_l
->state
),
1679 channel_listener_state_to_string(to_state
));
1681 chan_l
->state
= to_state
;
1683 /* Need to add to the right lists if the channel listener is registered */
1684 if (chan_l
->registered
) {
1685 was_active
= !(from_state
== CHANNEL_LISTENER_STATE_CLOSED
||
1686 from_state
== CHANNEL_LISTENER_STATE_ERROR
);
1687 is_active
= !(to_state
== CHANNEL_LISTENER_STATE_CLOSED
||
1688 to_state
== CHANNEL_LISTENER_STATE_ERROR
);
1690 /* Need to take off active list and put on finished list? */
1691 if (was_active
&& !is_active
) {
1692 if (active_listeners
) smartlist_remove(active_listeners
, chan_l
);
1693 if (!finished_listeners
) finished_listeners
= smartlist_new();
1694 smartlist_add(finished_listeners
, chan_l
);
1695 mainloop_schedule_postloop_cleanup();
1697 /* Need to put on active list? */
1698 else if (!was_active
&& is_active
) {
1699 if (finished_listeners
) smartlist_remove(finished_listeners
, chan_l
);
1700 if (!active_listeners
) active_listeners
= smartlist_new();
1701 smartlist_add(active_listeners
, chan_l
);
1705 if (to_state
== CHANNEL_LISTENER_STATE_CLOSED
||
1706 to_state
== CHANNEL_LISTENER_STATE_ERROR
) {
1707 tor_assert(!(chan_l
->incoming_list
) ||
1708 smartlist_len(chan_l
->incoming_list
) == 0);
1712 /* Maximum number of cells that is allowed to flush at once within
1713 * channel_flush_some_cells(). */
1714 #define MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED 256
1717 * Try to flush cells of the given channel chan up to a maximum of num_cells.
1719 * This is called by the scheduler when it wants to flush cells from the
1720 * channel's circuit queue(s) to the connection outbuf (not yet on the wire).
1722 * If the channel is not in state CHANNEL_STATE_OPEN, this does nothing and
1723 * will return 0 meaning no cells were flushed.
1725 * If num_cells is -1, we'll try to flush up to the maximum cells allowed
1726 * defined in MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED.
1728 * On success, the number of flushed cells are returned and it can never be
1729 * above num_cells. If 0 is returned, no cells were flushed either because the
1730 * channel was not opened or we had no cells on the channel. A negative number
1731 * can NOT be sent back.
1733 * This function is part of the fast path. */
1735 channel_flush_some_cells
, (channel_t
*chan
, ssize_t num_cells
))
1737 unsigned int unlimited
= 0;
1738 ssize_t flushed
= 0;
1739 int clamped_num_cells
;
1743 if (num_cells
< 0) unlimited
= 1;
1744 if (!unlimited
&& num_cells
<= flushed
) goto done
;
1746 /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
1747 if (CHANNEL_IS_OPEN(chan
)) {
1748 if (circuitmux_num_cells(chan
->cmux
) > 0) {
1749 /* Calculate number of cells, including clamp */
1751 clamped_num_cells
= MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED
;
1753 if (num_cells
- flushed
>
1754 MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED
) {
1755 clamped_num_cells
= MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED
;
1757 clamped_num_cells
= (int)(num_cells
- flushed
);
1761 /* Try to get more cells from any active circuits */
1762 flushed
= channel_flush_from_first_active_circuit(
1763 chan
, clamped_num_cells
);
1772 * Check if any cells are available.
1774 * This is used by the scheduler to know if the channel has more to flush
1775 * after a scheduling round.
1778 channel_more_to_flush
, (channel_t
*chan
))
1782 if (circuitmux_num_cells(chan
->cmux
) > 0) return 1;
1789 * Notify the channel we're done flushing the output in the lower layer.
1791 * Connection.c will call this when we've flushed the output; there's some
1792 * dirreq-related maintenance to do.
1795 channel_notify_flushed(channel_t
*chan
)
1799 if (chan
->dirreq_id
!= 0)
1800 geoip_change_dirreq_state(chan
->dirreq_id
,
1802 DIRREQ_CHANNEL_BUFFER_FLUSHED
);
1806 * Process the queue of incoming channels on a listener.
1808 * Use a listener's registered callback to process as many entries in the
1809 * queue of incoming channels as possible.
1812 channel_listener_process_incoming(channel_listener_t
*listener
)
1814 tor_assert(listener
);
1817 * CHANNEL_LISTENER_STATE_CLOSING permitted because we drain the queue
1818 * while closing a listener.
1820 tor_assert(listener
->state
== CHANNEL_LISTENER_STATE_LISTENING
||
1821 listener
->state
== CHANNEL_LISTENER_STATE_CLOSING
);
1822 tor_assert(listener
->listener
);
1824 log_debug(LD_CHANNEL
,
1825 "Processing queue of incoming connections for channel "
1826 "listener %p (global ID %"PRIu64
")",
1827 listener
, (listener
->global_identifier
));
1829 if (!(listener
->incoming_list
)) return;
1831 SMARTLIST_FOREACH_BEGIN(listener
->incoming_list
,
1832 channel_t
*, chan
) {
1835 log_debug(LD_CHANNEL
,
1836 "Handling incoming channel %p (%"PRIu64
") "
1837 "for listener %p (%"PRIu64
")",
1839 (chan
->global_identifier
),
1841 (listener
->global_identifier
));
1842 /* Make sure this is set correctly */
1843 channel_mark_incoming(chan
);
1844 listener
->listener(listener
, chan
);
1845 } SMARTLIST_FOREACH_END(chan
);
1847 smartlist_free(listener
->incoming_list
);
1848 listener
->incoming_list
= NULL
;
1852 * Take actions required when a channel becomes open.
1854 * Handle actions we should do when we know a channel is open; a lot of
1855 * this comes from the old connection_or_set_state_open() of connection_or.c.
1857 * Because of this mechanism, future channel_t subclasses should take care
1858 * not to change a channel from CHANNEL_STATE_OPENING to CHANNEL_STATE_OPEN
1859 * until there is positive confirmation that the network is operational.
1860 * In particular, anything UDP-based should not make this transition until a
1861 * packet is received from the other side.
1864 channel_do_open_actions(channel_t
*chan
)
1866 tor_addr_t remote_addr
;
1868 time_t now
= time(NULL
);
1869 int close_origin_circuits
= 0;
1873 started_here
= channel_is_outgoing(chan
);
1876 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
1877 router_set_status(chan
->identity_digest
, 1);
1879 /* only report it to the geoip module if it's a client */
1880 if (channel_is_client(chan
)) {
1881 if (channel_get_addr_if_possible(chan
, &remote_addr
)) {
1882 char *transport_name
= NULL
;
1883 channel_tls_t
*tlschan
= BASE_CHAN_TO_TLS(chan
);
1884 if (chan
->get_transport_name(chan
, &transport_name
) < 0)
1885 transport_name
= NULL
;
1887 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
,
1888 &remote_addr
, transport_name
,
1890 tor_free(transport_name
);
1891 /* Notify the DoS subsystem of a new client. */
1892 if (tlschan
&& tlschan
->conn
) {
1893 dos_new_client_conn(tlschan
->conn
, transport_name
);
1896 /* Otherwise the underlying transport can't tell us this, so skip it */
1900 /* Disable or reduce padding according to user prefs. */
1901 if (chan
->padding_enabled
|| get_options()->ConnectionPadding
== 1) {
1902 if (!get_options()->ConnectionPadding
) {
1903 /* Disable if torrc disabled */
1904 channelpadding_disable_padding_on_channel(chan
);
1905 } else if (rend_service_allow_non_anonymous_connection(get_options()) &&
1906 !networkstatus_get_param(NULL
,
1907 CHANNELPADDING_SOS_PARAM
,
1908 CHANNELPADDING_SOS_DEFAULT
, 0, 1)) {
1909 /* Disable if we're using RSOS and the consensus disabled padding
1911 channelpadding_disable_padding_on_channel(chan
);
1912 } else if (get_options()->ReducedConnectionPadding
) {
1913 /* Padding can be forced and/or reduced by clients, regardless of if
1914 * the channel supports it */
1915 channelpadding_reduce_padding_on_channel(chan
);
1919 circuit_n_chan_done(chan
, 1, close_origin_circuits
);
1923 * Queue an incoming channel on a listener.
1925 * Internal and subclass use only function to queue an incoming channel from
1926 * a listener. A subclass of channel_listener_t should call this when a new
1927 * incoming channel is created.
1930 channel_listener_queue_incoming(channel_listener_t
*listener
,
1931 channel_t
*incoming
)
1933 int need_to_queue
= 0;
1935 tor_assert(listener
);
1936 tor_assert(listener
->state
== CHANNEL_LISTENER_STATE_LISTENING
);
1937 tor_assert(incoming
);
1939 log_debug(LD_CHANNEL
,
1940 "Queueing incoming channel %p (global ID %"PRIu64
") on "
1941 "channel listener %p (global ID %"PRIu64
")",
1942 incoming
, (incoming
->global_identifier
),
1943 listener
, (listener
->global_identifier
));
1945 /* Do we need to queue it, or can we just call the listener right away? */
1946 if (!(listener
->listener
)) need_to_queue
= 1;
1947 if (listener
->incoming_list
&&
1948 (smartlist_len(listener
->incoming_list
) > 0))
1951 /* If we need to queue and have no queue, create one */
1952 if (need_to_queue
&& !(listener
->incoming_list
)) {
1953 listener
->incoming_list
= smartlist_new();
1956 /* Bump the counter and timestamp it */
1957 channel_listener_timestamp_active(listener
);
1958 channel_listener_timestamp_accepted(listener
);
1959 ++(listener
->n_accepted
);
1961 /* If we don't need to queue, process it right away */
1962 if (!need_to_queue
) {
1963 tor_assert(listener
->listener
);
1964 listener
->listener(listener
, incoming
);
1967 * Otherwise, we need to queue; queue and then process the queue if
1971 tor_assert(listener
->incoming_list
);
1972 smartlist_add(listener
->incoming_list
, incoming
);
1973 if (listener
->listener
) channel_listener_process_incoming(listener
);
1978 * Process a cell from the given channel.
1981 channel_process_cell(channel_t
*chan
, cell_t
*cell
)
1984 tor_assert(CHANNEL_IS_CLOSING(chan
) || CHANNEL_IS_MAINT(chan
) ||
1985 CHANNEL_IS_OPEN(chan
));
1988 /* Nothing we can do if we have no registered cell handlers */
1989 if (!chan
->cell_handler
)
1992 /* Timestamp for receiving */
1993 channel_timestamp_recv(chan
);
1994 /* Update received counter. */
1995 ++(chan
->n_cells_recved
);
1996 chan
->n_bytes_recved
+= get_cell_network_size(chan
->wide_circ_ids
);
1998 log_debug(LD_CHANNEL
,
1999 "Processing incoming cell_t %p for channel %p (global ID "
2000 "%"PRIu64
")", cell
, chan
,
2001 (chan
->global_identifier
));
2002 chan
->cell_handler(chan
, cell
);
2005 /** If <b>packed_cell</b> on <b>chan</b> is a destroy cell, then set
2006 * *<b>circid_out</b> to its circuit ID, and return true. Otherwise, return
2008 /* XXXX Move this function. */
2010 packed_cell_is_destroy(channel_t
*chan
,
2011 const packed_cell_t
*packed_cell
,
2012 circid_t
*circid_out
)
2014 if (chan
->wide_circ_ids
) {
2015 if (packed_cell
->body
[4] == CELL_DESTROY
) {
2016 *circid_out
= ntohl(get_uint32(packed_cell
->body
));
2020 if (packed_cell
->body
[2] == CELL_DESTROY
) {
2021 *circid_out
= ntohs(get_uint16(packed_cell
->body
));
2029 * Send destroy cell on a channel.
2031 * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
2032 * onto channel <b>chan</b>. Don't perform range-checking on reason:
2033 * we may want to propagate reasons from other cells.
2036 channel_send_destroy(circid_t circ_id
, channel_t
*chan
, int reason
)
2040 log_warn(LD_BUG
, "Attempted to send a destroy cell for circID 0 "
2041 "on a channel %"PRIu64
" at %p in state %s (%d)",
2042 (chan
->global_identifier
),
2043 chan
, channel_state_to_string(chan
->state
),
2048 /* Check to make sure we can send on this channel first */
2049 if (!CHANNEL_CONDEMNED(chan
) && chan
->cmux
) {
2050 channel_note_destroy_pending(chan
, circ_id
);
2051 circuitmux_append_destroy_cell(chan
, chan
->cmux
, circ_id
, reason
);
2053 "Sending destroy (circID %u) on channel %p "
2054 "(global ID %"PRIu64
")",
2055 (unsigned)circ_id
, chan
,
2056 (chan
->global_identifier
));
2059 "Someone called channel_send_destroy() for circID %u "
2060 "on a channel %"PRIu64
" at %p in state %s (%d)",
2061 (unsigned)circ_id
, (chan
->global_identifier
),
2062 chan
, channel_state_to_string(chan
->state
),
2070 * Dump channel statistics to the log.
2072 * This is called from dumpstats() in main.c and spams the log with
2073 * statistics on channels.
2076 channel_dumpstats(int severity
)
2078 if (all_channels
&& smartlist_len(all_channels
) > 0) {
2079 tor_log(severity
, LD_GENERAL
,
2080 "Dumping statistics about %d channels:",
2081 smartlist_len(all_channels
));
2082 tor_log(severity
, LD_GENERAL
,
2083 "%d are active, and %d are done and waiting for cleanup",
2084 (active_channels
!= NULL
) ?
2085 smartlist_len(active_channels
) : 0,
2086 (finished_channels
!= NULL
) ?
2087 smartlist_len(finished_channels
) : 0);
2089 SMARTLIST_FOREACH(all_channels
, channel_t
*, chan
,
2090 channel_dump_statistics(chan
, severity
));
2092 tor_log(severity
, LD_GENERAL
,
2093 "Done spamming about channels now");
2095 tor_log(severity
, LD_GENERAL
,
2096 "No channels to dump");
2101 * Dump channel listener statistics to the log.
2103 * This is called from dumpstats() in main.c and spams the log with
2104 * statistics on channel listeners.
2107 channel_listener_dumpstats(int severity
)
2109 if (all_listeners
&& smartlist_len(all_listeners
) > 0) {
2110 tor_log(severity
, LD_GENERAL
,
2111 "Dumping statistics about %d channel listeners:",
2112 smartlist_len(all_listeners
));
2113 tor_log(severity
, LD_GENERAL
,
2114 "%d are active and %d are done and waiting for cleanup",
2115 (active_listeners
!= NULL
) ?
2116 smartlist_len(active_listeners
) : 0,
2117 (finished_listeners
!= NULL
) ?
2118 smartlist_len(finished_listeners
) : 0);
2120 SMARTLIST_FOREACH(all_listeners
, channel_listener_t
*, chan_l
,
2121 channel_listener_dump_statistics(chan_l
, severity
));
2123 tor_log(severity
, LD_GENERAL
,
2124 "Done spamming about channel listeners now");
2126 tor_log(severity
, LD_GENERAL
,
2127 "No channel listeners to dump");
2132 * Clean up channels.
2134 * This gets called periodically from run_scheduled_events() in main.c;
2135 * it cleans up after closed channels.
2138 channel_run_cleanup(void)
2140 channel_t
*tmp
= NULL
;
2142 /* Check if we need to do anything */
2143 if (!finished_channels
|| smartlist_len(finished_channels
) == 0) return;
2145 /* Iterate through finished_channels and get rid of them */
2146 SMARTLIST_FOREACH_BEGIN(finished_channels
, channel_t
*, curr
) {
2148 /* Remove it from the list */
2149 SMARTLIST_DEL_CURRENT(finished_channels
, curr
);
2150 /* Also unregister it */
2151 channel_unregister(tmp
);
2152 /* ... and free it */
2154 } SMARTLIST_FOREACH_END(curr
);
2158 * Clean up channel listeners.
2160 * This gets called periodically from run_scheduled_events() in main.c;
2161 * it cleans up after closed channel listeners.
2164 channel_listener_run_cleanup(void)
2166 channel_listener_t
*tmp
= NULL
;
2168 /* Check if we need to do anything */
2169 if (!finished_listeners
|| smartlist_len(finished_listeners
) == 0) return;
2171 /* Iterate through finished_channels and get rid of them */
2172 SMARTLIST_FOREACH_BEGIN(finished_listeners
, channel_listener_t
*, curr
) {
2174 /* Remove it from the list */
2175 SMARTLIST_DEL_CURRENT(finished_listeners
, curr
);
2176 /* Also unregister it */
2177 channel_listener_unregister(tmp
);
2178 /* ... and free it */
2179 channel_listener_free(tmp
);
2180 } SMARTLIST_FOREACH_END(curr
);
2184 * Free a list of channels for channel_free_all().
2187 channel_free_list(smartlist_t
*channels
, int mark_for_close
)
2189 if (!channels
) return;
2191 SMARTLIST_FOREACH_BEGIN(channels
, channel_t
*, curr
) {
2192 /* Deregister and free it */
2194 log_debug(LD_CHANNEL
,
2195 "Cleaning up channel %p (global ID %"PRIu64
") "
2197 curr
, (curr
->global_identifier
),
2198 channel_state_to_string(curr
->state
), curr
->state
);
2199 /* Detach circuits early so they can find the channel */
2201 circuitmux_detach_all_circuits(curr
->cmux
, NULL
);
2203 SMARTLIST_DEL_CURRENT(channels
, curr
);
2204 channel_unregister(curr
);
2205 if (mark_for_close
) {
2206 if (!CHANNEL_CONDEMNED(curr
)) {
2207 channel_mark_for_close(curr
);
2209 channel_force_xfree(curr
);
2210 } else channel_free(curr
);
2211 } SMARTLIST_FOREACH_END(curr
);
2215 * Free a list of channel listeners for channel_free_all().
2218 channel_listener_free_list(smartlist_t
*listeners
, int mark_for_close
)
2220 if (!listeners
) return;
2222 SMARTLIST_FOREACH_BEGIN(listeners
, channel_listener_t
*, curr
) {
2223 /* Deregister and free it */
2225 log_debug(LD_CHANNEL
,
2226 "Cleaning up channel listener %p (global ID %"PRIu64
") "
2228 curr
, (curr
->global_identifier
),
2229 channel_listener_state_to_string(curr
->state
), curr
->state
);
2230 channel_listener_unregister(curr
);
2231 if (mark_for_close
) {
2232 if (!(curr
->state
== CHANNEL_LISTENER_STATE_CLOSING
||
2233 curr
->state
== CHANNEL_LISTENER_STATE_CLOSED
||
2234 curr
->state
== CHANNEL_LISTENER_STATE_ERROR
)) {
2235 channel_listener_mark_for_close(curr
);
2237 channel_listener_force_xfree(curr
);
2238 } else channel_listener_free(curr
);
2239 } SMARTLIST_FOREACH_END(curr
);
2243 * Close all channels and free everything.
2245 * This gets called from tor_free_all() in main.c to clean up on exit.
2246 * It will close all registered channels and free associated storage,
2247 * then free the all_channels, active_channels, listening_channels and
2248 * finished_channels lists and also channel_identity_map.
2251 channel_free_all(void)
2253 log_debug(LD_CHANNEL
,
2254 "Shutting down channels...");
2256 /* First, let's go for finished channels */
2257 if (finished_channels
) {
2258 channel_free_list(finished_channels
, 0);
2259 smartlist_free(finished_channels
);
2260 finished_channels
= NULL
;
2263 /* Now the finished listeners */
2264 if (finished_listeners
) {
2265 channel_listener_free_list(finished_listeners
, 0);
2266 smartlist_free(finished_listeners
);
2267 finished_listeners
= NULL
;
2270 /* Now all active channels */
2271 if (active_channels
) {
2272 channel_free_list(active_channels
, 1);
2273 smartlist_free(active_channels
);
2274 active_channels
= NULL
;
2277 /* Now all active listeners */
2278 if (active_listeners
) {
2279 channel_listener_free_list(active_listeners
, 1);
2280 smartlist_free(active_listeners
);
2281 active_listeners
= NULL
;
2284 /* Now all channels, in case any are left over */
2286 channel_free_list(all_channels
, 1);
2287 smartlist_free(all_channels
);
2288 all_channels
= NULL
;
2291 /* Now all listeners, in case any are left over */
2292 if (all_listeners
) {
2293 channel_listener_free_list(all_listeners
, 1);
2294 smartlist_free(all_listeners
);
2295 all_listeners
= NULL
;
2298 /* Now free channel_identity_map */
2299 log_debug(LD_CHANNEL
,
2300 "Freeing channel_identity_map");
2301 /* Geez, anything still left over just won't die ... let it leak then */
2302 HT_CLEAR(channel_idmap
, &channel_identity_map
);
2304 /* Same with channel_gid_map */
2305 log_debug(LD_CHANNEL
,
2306 "Freeing channel_gid_map");
2307 HT_CLEAR(channel_gid_map
, &channel_gid_map
);
2309 log_debug(LD_CHANNEL
,
2310 "Done cleaning up after channels");
2314 * Connect to a given addr/port/digest.
2316 * This sets up a new outgoing channel; in the future if multiple
2317 * channel_t subclasses are available, this is where the selection policy
2318 * should go. It may also be desirable to fold port into tor_addr_t
2319 * or make a new type including a tor_addr_t and port, so we have a
2320 * single abstract object encapsulating all the protocol details of
2321 * how to contact an OR.
2324 channel_connect(const tor_addr_t
*addr
, uint16_t port
,
2325 const char *id_digest
,
2326 const ed25519_public_key_t
*ed_id
)
2328 return channel_tls_connect(addr
, port
, id_digest
, ed_id
);
2332 * Decide which of two channels to prefer for extending a circuit.
2334 * This function is called while extending a circuit and returns true iff
2335 * a is 'better' than b. The most important criterion here is that a
2336 * canonical channel is always better than a non-canonical one, but the
2337 * number of circuits and the age are used as tie-breakers.
2339 * This is based on the former connection_or_is_better() of connection_or.c
2342 channel_is_better(channel_t
*a
, channel_t
*b
)
2344 int a_is_canonical
, b_is_canonical
;
2349 /* If one channel is bad for new circuits, and the other isn't,
2350 * use the one that is still good. */
2351 if (!channel_is_bad_for_new_circs(a
) && channel_is_bad_for_new_circs(b
))
2353 if (channel_is_bad_for_new_circs(a
) && !channel_is_bad_for_new_circs(b
))
2356 /* Check if one is canonical and the other isn't first */
2357 a_is_canonical
= channel_is_canonical(a
);
2358 b_is_canonical
= channel_is_canonical(b
);
2360 if (a_is_canonical
&& !b_is_canonical
) return 1;
2361 if (!a_is_canonical
&& b_is_canonical
) return 0;
2363 /* Check if we suspect that one of the channels will be preferred
2365 if (a
->is_canonical_to_peer
&& !b
->is_canonical_to_peer
) return 1;
2366 if (!a
->is_canonical_to_peer
&& b
->is_canonical_to_peer
) return 0;
2369 * Okay, if we're here they tied on canonicity. Prefer the older
2370 * connection, so that the adversary can't create a new connection
2371 * and try to switch us over to it (which will leak information
2372 * about long-lived circuits). Additionally, switching connections
2373 * too often makes us more vulnerable to attacks like Torscan and
2374 * passive netflow-based equivalents.
2376 * Connections will still only live for at most a week, due to
2377 * the check in connection_or_group_set_badness() against
2378 * TIME_BEFORE_OR_CONN_IS_TOO_OLD, which marks old connections as
2379 * unusable for new circuits after 1 week. That check sets
2380 * is_bad_for_new_circs, which is checked in channel_get_for_extend().
2382 * We check channel_is_bad_for_new_circs() above here anyway, for safety.
2384 if (channel_when_created(a
) < channel_when_created(b
)) return 1;
2385 else if (channel_when_created(a
) > channel_when_created(b
)) return 0;
2387 if (channel_num_circuits(a
) > channel_num_circuits(b
)) return 1;
2392 * Get a channel to extend a circuit.
2394 * Given the desired relay identity, pick a suitable channel to extend a
2395 * circuit to the target IPv4 or IPv6 address requsted by the client. Search
2396 * for an existing channel for the requested endpoint. Make sure the channel
2397 * is usable for new circuits, and matches one of the target addresses.
2399 * Try to return the best channel. But if there is no good channel, set
2400 * *msg_out to a message describing the channel's state and our next action,
2401 * and set *launch_out to a boolean indicated whether the caller should try to
2402 * launch a new channel with channel_connect().
2404 MOCK_IMPL(channel_t
*,
2405 channel_get_for_extend
,(const char *rsa_id_digest
,
2406 const ed25519_public_key_t
*ed_id
,
2407 const tor_addr_t
*target_ipv4_addr
,
2408 const tor_addr_t
*target_ipv6_addr
,
2409 const char **msg_out
,
2412 channel_t
*chan
, *best
= NULL
;
2413 int n_inprogress_goodaddr
= 0, n_old
= 0;
2414 int n_noncanonical
= 0;
2416 tor_assert(msg_out
);
2417 tor_assert(launch_out
);
2419 chan
= channel_find_by_remote_identity(rsa_id_digest
, ed_id
);
2421 /* Walk the list of channels */
2422 for (; chan
; chan
= channel_next_with_rsa_identity(chan
)) {
2423 tor_assert(tor_memeq(chan
->identity_digest
,
2424 rsa_id_digest
, DIGEST_LEN
));
2426 if (CHANNEL_CONDEMNED(chan
))
2429 /* Never return a channel on which the other end appears to be
2431 if (channel_is_client(chan
)) {
2435 /* The Ed25519 key has to match too */
2436 if (!channel_remote_identity_matches(chan
, rsa_id_digest
, ed_id
)) {
2440 const bool matches_target
=
2441 channel_matches_target_addr_for_extend(chan
,
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
2449 ++n_inprogress_goodaddr
;
2453 /* Never return a connection that shouldn't be used for circs. */
2454 if (channel_is_bad_for_new_circs(chan
)) {
2459 /* Only return canonical connections or connections where the address
2460 * is the address we wanted. */
2461 if (!channel_is_canonical(chan
) && !matches_target
) {
2467 best
= chan
; /* If we have no 'best' so far, this one is good enough. */
2471 if (channel_is_better(chan
, best
))
2476 *msg_out
= "Connection is fine; using it.";
2479 } else if (n_inprogress_goodaddr
) {
2480 *msg_out
= "Connection in progress; waiting.";
2483 } else if (n_old
|| n_noncanonical
) {
2484 *msg_out
= "Connections all too old, or too non-canonical. "
2485 " Launching a new one.";
2489 *msg_out
= "Not connected. Connecting.";
2496 * Describe the transport subclass for a channel.
2498 * Invoke a method to get a string description of the lower-layer
2499 * transport for this channel.
2502 channel_describe_transport(channel_t
*chan
)
2505 tor_assert(chan
->describe_transport
);
2507 return chan
->describe_transport(chan
);
2511 * Describe the transport subclass for a channel listener.
2513 * Invoke a method to get a string description of the lower-layer
2514 * transport for this channel listener.
2517 channel_listener_describe_transport(channel_listener_t
*chan_l
)
2520 tor_assert(chan_l
->describe_transport
);
2522 return chan_l
->describe_transport(chan_l
);
2526 * Dump channel statistics.
2528 * Dump statistics for one channel to the log.
2531 channel_dump_statistics
, (channel_t
*chan
, int severity
))
2533 double avg
, interval
, age
;
2534 time_t now
= time(NULL
);
2535 tor_addr_t remote_addr
;
2536 int have_remote_addr
;
2537 char *remote_addr_str
;
2541 age
= (double)(now
- chan
->timestamp_created
);
2543 tor_log(severity
, LD_GENERAL
,
2544 "Channel %"PRIu64
" (at %p) with transport %s is in state "
2546 (chan
->global_identifier
), chan
,
2547 channel_describe_transport(chan
),
2548 channel_state_to_string(chan
->state
), chan
->state
);
2549 tor_log(severity
, LD_GENERAL
,
2550 " * Channel %"PRIu64
" was created at %"PRIu64
2551 " (%"PRIu64
" seconds ago) "
2552 "and last active at %"PRIu64
" (%"PRIu64
" seconds ago)",
2553 (chan
->global_identifier
),
2554 (uint64_t)(chan
->timestamp_created
),
2555 (uint64_t)(now
- chan
->timestamp_created
),
2556 (uint64_t)(chan
->timestamp_active
),
2557 (uint64_t)(now
- chan
->timestamp_active
));
2559 /* Handle digest. */
2560 if (!tor_digest_is_zero(chan
->identity_digest
)) {
2561 tor_log(severity
, LD_GENERAL
,
2562 " * Channel %"PRIu64
" says it is connected "
2563 "to an OR with digest %s",
2564 (chan
->global_identifier
),
2565 hex_str(chan
->identity_digest
, DIGEST_LEN
));
2567 tor_log(severity
, LD_GENERAL
,
2568 " * Channel %"PRIu64
" does not know the digest"
2569 " of the OR it is connected to",
2570 (chan
->global_identifier
));
2573 /* Handle remote address and descriptions */
2574 have_remote_addr
= channel_get_addr_if_possible(chan
, &remote_addr
);
2575 if (have_remote_addr
) {
2576 char *actual
= tor_strdup(channel_get_actual_remote_descr(chan
));
2577 remote_addr_str
= tor_addr_to_str_dup(&remote_addr
);
2578 tor_log(severity
, LD_GENERAL
,
2579 " * Channel %"PRIu64
" says its remote address"
2580 " is %s, and gives a canonical description of \"%s\" and an "
2581 "actual description of \"%s\"",
2582 (chan
->global_identifier
),
2583 safe_str(remote_addr_str
),
2584 safe_str(channel_get_canonical_remote_descr(chan
)),
2586 tor_free(remote_addr_str
);
2589 char *actual
= tor_strdup(channel_get_actual_remote_descr(chan
));
2590 tor_log(severity
, LD_GENERAL
,
2591 " * Channel %"PRIu64
" does not know its remote "
2592 "address, but gives a canonical description of \"%s\" and an "
2593 "actual description of \"%s\"",
2594 (chan
->global_identifier
),
2595 channel_get_canonical_remote_descr(chan
),
2601 tor_log(severity
, LD_GENERAL
,
2602 " * Channel %"PRIu64
" has these marks: %s %s %s %s %s",
2603 (chan
->global_identifier
),
2604 channel_is_bad_for_new_circs(chan
) ?
2605 "bad_for_new_circs" : "!bad_for_new_circs",
2606 channel_is_canonical(chan
) ?
2607 "canonical" : "!canonical",
2608 channel_is_client(chan
) ?
2609 "client" : "!client",
2610 channel_is_local(chan
) ?
2612 channel_is_incoming(chan
) ?
2613 "incoming" : "outgoing");
2615 /* Describe circuits */
2616 tor_log(severity
, LD_GENERAL
,
2617 " * Channel %"PRIu64
" has %d active circuits out of"
2619 (chan
->global_identifier
),
2620 (chan
->cmux
!= NULL
) ?
2621 circuitmux_num_active_circuits(chan
->cmux
) : 0,
2622 (chan
->cmux
!= NULL
) ?
2623 circuitmux_num_circuits(chan
->cmux
) : 0);
2625 /* Describe timestamps */
2626 tor_log(severity
, LD_GENERAL
,
2627 " * Channel %"PRIu64
" was last used by a "
2628 "client at %"PRIu64
" (%"PRIu64
" seconds ago)",
2629 (chan
->global_identifier
),
2630 (uint64_t)(chan
->timestamp_client
),
2631 (uint64_t)(now
- chan
->timestamp_client
));
2632 tor_log(severity
, LD_GENERAL
,
2633 " * Channel %"PRIu64
" last received a cell "
2634 "at %"PRIu64
" (%"PRIu64
" seconds ago)",
2635 (chan
->global_identifier
),
2636 (uint64_t)(chan
->timestamp_recv
),
2637 (uint64_t)(now
- chan
->timestamp_recv
));
2638 tor_log(severity
, LD_GENERAL
,
2639 " * Channel %"PRIu64
" last transmitted a cell "
2640 "at %"PRIu64
" (%"PRIu64
" seconds ago)",
2641 (chan
->global_identifier
),
2642 (uint64_t)(chan
->timestamp_xmit
),
2643 (uint64_t)(now
- chan
->timestamp_xmit
));
2645 /* Describe counters and rates */
2646 tor_log(severity
, LD_GENERAL
,
2647 " * Channel %"PRIu64
" has received "
2648 "%"PRIu64
" bytes in %"PRIu64
" cells and transmitted "
2649 "%"PRIu64
" bytes in %"PRIu64
" cells",
2650 (chan
->global_identifier
),
2651 (chan
->n_bytes_recved
),
2652 (chan
->n_cells_recved
),
2653 (chan
->n_bytes_xmitted
),
2654 (chan
->n_cells_xmitted
));
2655 if (now
> chan
->timestamp_created
&&
2656 chan
->timestamp_created
> 0) {
2657 if (chan
->n_bytes_recved
> 0) {
2658 avg
= (double)(chan
->n_bytes_recved
) / age
;
2659 tor_log(severity
, LD_GENERAL
,
2660 " * Channel %"PRIu64
" has averaged %f "
2661 "bytes received per second",
2662 (chan
->global_identifier
), avg
);
2664 if (chan
->n_cells_recved
> 0) {
2665 avg
= (double)(chan
->n_cells_recved
) / age
;
2667 tor_log(severity
, LD_GENERAL
,
2668 " * Channel %"PRIu64
" has averaged %f "
2669 "cells received per second",
2670 (chan
->global_identifier
), avg
);
2671 } else if (avg
>= 0.0) {
2672 interval
= 1.0 / avg
;
2673 tor_log(severity
, LD_GENERAL
,
2674 " * Channel %"PRIu64
" has averaged %f "
2675 "seconds between received cells",
2676 (chan
->global_identifier
), interval
);
2679 if (chan
->n_bytes_xmitted
> 0) {
2680 avg
= (double)(chan
->n_bytes_xmitted
) / age
;
2681 tor_log(severity
, LD_GENERAL
,
2682 " * Channel %"PRIu64
" has averaged %f "
2683 "bytes transmitted per second",
2684 (chan
->global_identifier
), avg
);
2686 if (chan
->n_cells_xmitted
> 0) {
2687 avg
= (double)(chan
->n_cells_xmitted
) / age
;
2689 tor_log(severity
, LD_GENERAL
,
2690 " * Channel %"PRIu64
" has averaged %f "
2691 "cells transmitted per second",
2692 (chan
->global_identifier
), avg
);
2693 } else if (avg
>= 0.0) {
2694 interval
= 1.0 / avg
;
2695 tor_log(severity
, LD_GENERAL
,
2696 " * Channel %"PRIu64
" has averaged %f "
2697 "seconds between transmitted cells",
2698 (chan
->global_identifier
), interval
);
2703 /* Dump anything the lower layer has to say */
2704 channel_dump_transport_statistics(chan
, severity
);
2708 * Dump channel listener statistics.
2710 * Dump statistics for one channel listener to the log.
2713 channel_listener_dump_statistics(channel_listener_t
*chan_l
, int severity
)
2715 double avg
, interval
, age
;
2716 time_t now
= time(NULL
);
2720 age
= (double)(now
- chan_l
->timestamp_created
);
2722 tor_log(severity
, LD_GENERAL
,
2723 "Channel listener %"PRIu64
" (at %p) with transport %s is in "
2725 (chan_l
->global_identifier
), chan_l
,
2726 channel_listener_describe_transport(chan_l
),
2727 channel_listener_state_to_string(chan_l
->state
), chan_l
->state
);
2728 tor_log(severity
, LD_GENERAL
,
2729 " * Channel listener %"PRIu64
" was created at %"PRIu64
2730 " (%"PRIu64
" seconds ago) "
2731 "and last active at %"PRIu64
" (%"PRIu64
" seconds ago)",
2732 (chan_l
->global_identifier
),
2733 (uint64_t)(chan_l
->timestamp_created
),
2734 (uint64_t)(now
- chan_l
->timestamp_created
),
2735 (uint64_t)(chan_l
->timestamp_active
),
2736 (uint64_t)(now
- chan_l
->timestamp_active
));
2738 tor_log(severity
, LD_GENERAL
,
2739 " * Channel listener %"PRIu64
" last accepted an incoming "
2740 "channel at %"PRIu64
" (%"PRIu64
" seconds ago) "
2741 "and has accepted %"PRIu64
" channels in total",
2742 (chan_l
->global_identifier
),
2743 (uint64_t)(chan_l
->timestamp_accepted
),
2744 (uint64_t)(now
- chan_l
->timestamp_accepted
),
2745 (uint64_t)(chan_l
->n_accepted
));
2748 * If it's sensible to do so, get the rate of incoming channels on this
2751 if (now
> chan_l
->timestamp_created
&&
2752 chan_l
->timestamp_created
> 0 &&
2753 chan_l
->n_accepted
> 0) {
2754 avg
= (double)(chan_l
->n_accepted
) / age
;
2756 tor_log(severity
, LD_GENERAL
,
2757 " * Channel listener %"PRIu64
" has averaged %f incoming "
2758 "channels per second",
2759 (chan_l
->global_identifier
), avg
);
2760 } else if (avg
>= 0.0) {
2761 interval
= 1.0 / avg
;
2762 tor_log(severity
, LD_GENERAL
,
2763 " * Channel listener %"PRIu64
" has averaged %f seconds "
2764 "between incoming channels",
2765 (chan_l
->global_identifier
), interval
);
2769 /* Dump anything the lower layer has to say */
2770 channel_listener_dump_transport_statistics(chan_l
, severity
);
2774 * Invoke transport-specific stats dump for channel.
2776 * If there is a lower-layer statistics dump method, invoke it.
2779 channel_dump_transport_statistics(channel_t
*chan
, int severity
)
2783 if (chan
->dumpstats
) chan
->dumpstats(chan
, severity
);
2787 * Invoke transport-specific stats dump for channel listener.
2789 * If there is a lower-layer statistics dump method, invoke it.
2792 channel_listener_dump_transport_statistics(channel_listener_t
*chan_l
,
2797 if (chan_l
->dumpstats
) chan_l
->dumpstats(chan_l
, severity
);
2801 * Return text description of the remote endpoint.
2803 * This function return a test provided by the lower layer of the remote
2804 * endpoint for this channel; it should specify the actual address connected
2807 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
2808 * may invalidate the return value from this function.
2811 channel_get_actual_remote_descr(channel_t
*chan
)
2814 tor_assert(chan
->get_remote_descr
);
2816 /* Param 1 indicates the actual description */
2817 return chan
->get_remote_descr(chan
, GRD_FLAG_ORIGINAL
);
2821 * Return the text address of the remote endpoint.
2823 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
2824 * may invalidate the return value from this function.
2827 channel_get_actual_remote_address(channel_t
*chan
)
2829 /* Param 1 indicates the actual description */
2830 return chan
->get_remote_descr(chan
, GRD_FLAG_ORIGINAL
|GRD_FLAG_ADDR_ONLY
);
2834 * Return text description of the remote endpoint canonical address.
2836 * This function return a test provided by the lower layer of the remote
2837 * endpoint for this channel; it should use the known canonical address for
2838 * this OR's identity digest if possible.
2840 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
2841 * may invalidate the return value from this function.
2843 MOCK_IMPL(const char *,
2844 channel_get_canonical_remote_descr
,(channel_t
*chan
))
2847 tor_assert(chan
->get_remote_descr
);
2849 /* Param 0 indicates the canonicalized description */
2850 return chan
->get_remote_descr(chan
, 0);
2854 * Get remote address if possible.
2856 * Write the remote address out to a tor_addr_t if the underlying transport
2857 * supports this operation, and return 1. Return 0 if the underlying transport
2858 * doesn't let us do this.
2861 channel_get_addr_if_possible
,(channel_t
*chan
, tor_addr_t
*addr_out
))
2864 tor_assert(addr_out
);
2866 if (chan
->get_remote_addr
)
2867 return chan
->get_remote_addr(chan
, addr_out
);
2868 /* Else no support, method not implemented */
2873 * Return true iff the channel has any cells on the connection outbuf waiting
2874 * to be sent onto the network.
2877 channel_has_queued_writes(channel_t
*chan
)
2880 tor_assert(chan
->has_queued_writes
);
2882 /* Check with the lower layer */
2883 return chan
->has_queued_writes(chan
);
2887 * Check the is_bad_for_new_circs flag.
2889 * This function returns the is_bad_for_new_circs flag of the specified
2893 channel_is_bad_for_new_circs(channel_t
*chan
)
2897 return chan
->is_bad_for_new_circs
;
2901 * Mark a channel as bad for new circuits.
2903 * Set the is_bad_for_new_circs_flag on chan.
2906 channel_mark_bad_for_new_circs(channel_t
*chan
)
2910 chan
->is_bad_for_new_circs
= 1;
2914 * Get the client flag.
2916 * This returns the client flag of a channel, which will be set if
2917 * command_process_create_cell() in command.c thinks this is a connection
2921 channel_is_client(const channel_t
*chan
)
2925 return chan
->is_client
;
2929 * Set the client flag.
2931 * Mark a channel as being from a client.
2934 channel_mark_client(channel_t
*chan
)
2938 chan
->is_client
= 1;
2942 * Clear the client flag.
2944 * Mark a channel as being _not_ from a client.
2947 channel_clear_client(channel_t
*chan
)
2951 chan
->is_client
= 0;
2955 * Get the canonical flag for a channel.
2957 * This returns the is_canonical for a channel; this flag is determined by
2958 * the lower layer and can't be set in a transport-independent way.
2961 channel_is_canonical(channel_t
*chan
)
2964 tor_assert(chan
->is_canonical
);
2966 return chan
->is_canonical(chan
);
2970 * Test incoming flag.
2972 * This function gets the incoming flag; this is set when a listener spawns
2973 * a channel. If this returns true the channel was remotely initiated.
2976 channel_is_incoming(channel_t
*chan
)
2980 return chan
->is_incoming
;
2984 * Set the incoming flag.
2986 * This function is called when a channel arrives on a listening channel
2987 * to mark it as incoming.
2990 channel_mark_incoming(channel_t
*chan
)
2994 chan
->is_incoming
= 1;
3000 * This function gets the local flag; the lower layer should set this when
3001 * setting up the channel if is_local_addr() is true for all of the
3002 * destinations it will communicate with on behalf of this channel. It's
3003 * used to decide whether to declare the network reachable when seeing incoming
3004 * traffic on the channel.
3007 channel_is_local(channel_t
*chan
)
3011 return chan
->is_local
;
3015 * Set the local flag.
3017 * This internal-only function should be called by the lower layer if the
3018 * channel is to a local address. See channel_is_local() above or the
3019 * description of the is_local bit in channel.h.
3022 channel_mark_local(channel_t
*chan
)
3030 * Mark a channel as remote.
3032 * This internal-only function should be called by the lower layer if the
3033 * channel is not to a local address but has previously been marked local.
3034 * See channel_is_local() above or the description of the is_local bit in
3038 channel_mark_remote(channel_t
*chan
)
3046 * Test outgoing flag.
3048 * This function gets the outgoing flag; this is the inverse of the incoming
3049 * bit set when a listener spawns a channel. If this returns true the channel
3050 * was locally initiated.
3053 channel_is_outgoing(channel_t
*chan
)
3057 return !(chan
->is_incoming
);
3061 * Mark a channel as outgoing.
3063 * This function clears the incoming flag and thus marks a channel as
3067 channel_mark_outgoing(channel_t
*chan
)
3071 chan
->is_incoming
= 0;
3074 /************************
3075 * Flow control queries *
3076 ***********************/
3079 * Estimate the number of writeable cells.
3081 * Ask the lower layer for an estimate of how many cells it can accept.
3084 channel_num_cells_writeable(channel_t
*chan
)
3089 tor_assert(chan
->num_cells_writeable
);
3091 if (chan
->state
== CHANNEL_STATE_OPEN
) {
3092 /* Query lower layer */
3093 result
= chan
->num_cells_writeable(chan
);
3094 if (result
< 0) result
= 0;
3096 /* No cells are writeable in any other state */
3103 /*********************
3104 * Timestamp updates *
3105 ********************/
3108 * Update the created timestamp for a channel.
3110 * This updates the channel's created timestamp and should only be called
3111 * from channel_init().
3114 channel_timestamp_created(channel_t
*chan
)
3116 time_t now
= time(NULL
);
3120 chan
->timestamp_created
= now
;
3124 * Update the created timestamp for a channel listener.
3126 * This updates the channel listener's created timestamp and should only be
3127 * called from channel_init_listener().
3130 channel_listener_timestamp_created(channel_listener_t
*chan_l
)
3132 time_t now
= time(NULL
);
3136 chan_l
->timestamp_created
= now
;
3140 * Update the last active timestamp for a channel.
3142 * This function updates the channel's last active timestamp; it should be
3143 * called by the lower layer whenever there is activity on the channel which
3144 * does not lead to a cell being transmitted or received; the active timestamp
3145 * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
3146 * but it should be updated for things like the v3 handshake and stuff that
3147 * produce activity only visible to the lower layer.
3150 channel_timestamp_active(channel_t
*chan
)
3152 time_t now
= time(NULL
);
3155 monotime_coarse_get(&chan
->timestamp_xfer
);
3157 chan
->timestamp_active
= now
;
3159 /* Clear any potential netflow padding timer. We're active */
3160 monotime_coarse_zero(&chan
->next_padding_time
);
3164 * Update the last active timestamp for a channel listener.
3167 channel_listener_timestamp_active(channel_listener_t
*chan_l
)
3169 time_t now
= time(NULL
);
3173 chan_l
->timestamp_active
= now
;
3177 * Update the last accepted timestamp.
3179 * This function updates the channel listener's last accepted timestamp; it
3180 * should be called whenever a new incoming channel is accepted on a
3184 channel_listener_timestamp_accepted(channel_listener_t
*chan_l
)
3186 time_t now
= time(NULL
);
3190 chan_l
->timestamp_active
= now
;
3191 chan_l
->timestamp_accepted
= now
;
3195 * Update client timestamp.
3197 * This function is called by relay.c to timestamp a channel that appears to
3198 * be used as a client.
3201 channel_timestamp_client(channel_t
*chan
)
3203 time_t now
= time(NULL
);
3207 chan
->timestamp_client
= now
;
3211 * Update the recv timestamp.
3213 * This is called whenever we get an incoming cell from the lower layer.
3214 * This also updates the active timestamp.
3217 channel_timestamp_recv(channel_t
*chan
)
3219 time_t now
= time(NULL
);
3221 monotime_coarse_get(&chan
->timestamp_xfer
);
3223 chan
->timestamp_active
= now
;
3224 chan
->timestamp_recv
= now
;
3226 /* Clear any potential netflow padding timer. We're active */
3227 monotime_coarse_zero(&chan
->next_padding_time
);
3231 * Update the xmit timestamp.
3233 * This is called whenever we pass an outgoing cell to the lower layer. This
3234 * also updates the active timestamp.
3237 channel_timestamp_xmit(channel_t
*chan
)
3239 time_t now
= time(NULL
);
3242 monotime_coarse_get(&chan
->timestamp_xfer
);
3244 chan
->timestamp_active
= now
;
3245 chan
->timestamp_xmit
= now
;
3247 /* Clear any potential netflow padding timer. We're active */
3248 monotime_coarse_zero(&chan
->next_padding_time
);
3251 /***************************************************************
3252 * Timestamp queries - see above for definitions of timestamps *
3253 **************************************************************/
3256 * Query created timestamp for a channel.
3259 channel_when_created(channel_t
*chan
)
3263 return chan
->timestamp_created
;
3267 * Query client timestamp.
3270 channel_when_last_client(channel_t
*chan
)
3274 return chan
->timestamp_client
;
3278 * Query xmit timestamp.
3281 channel_when_last_xmit(channel_t
*chan
)
3285 return chan
->timestamp_xmit
;
3289 * Check if a channel matches an extend_info_t.
3291 * This function calls the lower layer and asks if this channel matches a
3292 * given extend_info_t.
3295 channel_matches_extend_info(channel_t
*chan
, extend_info_t
*extend_info
)
3298 tor_assert(chan
->matches_extend_info
);
3299 tor_assert(extend_info
);
3301 return chan
->matches_extend_info(chan
, extend_info
);
3305 * Check if a channel matches the given target IPv4 or IPv6 addresses.
3306 * If either address matches, return true. If neither address matches,
3309 * Both addresses can't be NULL.
3311 * This function calls into the lower layer and asks if this channel thinks
3312 * it matches the target addresses for circuit extension purposes.
3315 channel_matches_target_addr_for_extend(channel_t
*chan
,
3316 const tor_addr_t
*target_ipv4_addr
,
3317 const tor_addr_t
*target_ipv6_addr
)
3320 tor_assert(chan
->matches_target
);
3322 IF_BUG_ONCE(!target_ipv4_addr
&& !target_ipv6_addr
)
3325 if (target_ipv4_addr
&& chan
->matches_target(chan
, target_ipv4_addr
))
3328 if (target_ipv6_addr
&& chan
->matches_target(chan
, target_ipv6_addr
))
3335 * Return the total number of circuits used by a channel.
3337 * @param chan Channel to query
3338 * @return Number of circuits using this as n_chan or p_chan
3341 channel_num_circuits(channel_t
*chan
)
3345 return chan
->num_n_circuits
+
3346 chan
->num_p_circuits
;
3350 * Set up circuit ID generation.
3352 * This is called when setting up a channel and replaces the old
3353 * connection_or_set_circid_type().
3356 channel_set_circid_type
,(channel_t
*chan
,
3357 crypto_pk_t
*identity_rcvd
,
3358 int consider_identity
))
3361 crypto_pk_t
*our_identity
;
3365 started_here
= channel_is_outgoing(chan
);
3367 if (! consider_identity
) {
3369 chan
->circ_id_type
= CIRC_ID_TYPE_HIGHER
;
3371 chan
->circ_id_type
= CIRC_ID_TYPE_LOWER
;
3375 our_identity
= started_here
?
3376 get_tlsclient_identity_key() : get_server_identity_key();
3378 if (identity_rcvd
) {
3379 if (crypto_pk_cmp_keys(our_identity
, identity_rcvd
) < 0) {
3380 chan
->circ_id_type
= CIRC_ID_TYPE_LOWER
;
3382 chan
->circ_id_type
= CIRC_ID_TYPE_HIGHER
;
3385 chan
->circ_id_type
= CIRC_ID_TYPE_NEITHER
;
3390 channel_sort_by_ed25519_identity(const void **a_
, const void **b_
)
3392 const channel_t
*a
= *a_
,
3394 return fast_memcmp(&a
->ed25519_identity
.pubkey
,
3395 &b
->ed25519_identity
.pubkey
,
3396 sizeof(a
->ed25519_identity
.pubkey
));
3399 /** Helper for channel_update_bad_for_new_circs(): Perform the
3400 * channel_update_bad_for_new_circs operation on all channels in <b>lst</b>,
3401 * all of which MUST have the same RSA ID. (They MAY have different
3404 channel_rsa_id_group_set_badness(struct channel_list_t
*lst
, int force
)
3406 /*XXXX This function should really be about channels. 15056 */
3407 channel_t
*chan
= TOR_LIST_FIRST(lst
);
3412 /* if there is only one channel, don't bother looping */
3413 if (PREDICT_LIKELY(!TOR_LIST_NEXT(chan
, next_with_same_id
))) {
3414 connection_or_single_set_badness_(
3415 time(NULL
), BASE_CHAN_TO_TLS(chan
)->conn
, force
);
3419 smartlist_t
*channels
= smartlist_new();
3421 TOR_LIST_FOREACH(chan
, lst
, next_with_same_id
) {
3422 if (BASE_CHAN_TO_TLS(chan
)->conn
) {
3423 smartlist_add(channels
, chan
);
3427 smartlist_sort(channels
, channel_sort_by_ed25519_identity
);
3429 const ed25519_public_key_t
*common_ed25519_identity
= NULL
;
3430 /* it would be more efficient to do a slice, but this case is rare */
3431 smartlist_t
*or_conns
= smartlist_new();
3432 SMARTLIST_FOREACH_BEGIN(channels
, channel_t
*, channel
) {
3433 tor_assert(channel
); // Suppresses some compiler warnings.
3435 if (!common_ed25519_identity
)
3436 common_ed25519_identity
= &channel
->ed25519_identity
;
3438 if (! ed25519_pubkey_eq(&channel
->ed25519_identity
,
3439 common_ed25519_identity
)) {
3440 connection_or_group_set_badness_(or_conns
, force
);
3441 smartlist_clear(or_conns
);
3442 common_ed25519_identity
= &channel
->ed25519_identity
;
3445 smartlist_add(or_conns
, BASE_CHAN_TO_TLS(channel
)->conn
);
3446 } SMARTLIST_FOREACH_END(channel
);
3448 connection_or_group_set_badness_(or_conns
, force
);
3450 /* XXXX 15056 we may want to do something special with connections that have
3451 * no set Ed25519 identity! */
3453 smartlist_free(or_conns
);
3454 smartlist_free(channels
);
3457 /** Go through all the channels (or if <b>digest</b> is non-NULL, just
3458 * the OR connections with that digest), and set the is_bad_for_new_circs
3459 * flag based on the rules in connection_or_group_set_badness() (or just
3460 * always set it if <b>force</b> is true).
3463 channel_update_bad_for_new_circs(const char *digest
, int force
)
3466 channel_idmap_entry_t
*ent
;
3467 channel_idmap_entry_t search
;
3468 memset(&search
, 0, sizeof(search
));
3469 memcpy(search
.digest
, digest
, DIGEST_LEN
);
3470 ent
= HT_FIND(channel_idmap
, &channel_identity_map
, &search
);
3472 channel_rsa_id_group_set_badness(&ent
->channel_list
, force
);
3477 /* no digest; just look at everything. */
3478 channel_idmap_entry_t
**iter
;
3479 HT_FOREACH(iter
, channel_idmap
, &channel_identity_map
) {
3480 channel_rsa_id_group_set_badness(&(*iter
)->channel_list
, force
);