1 /* * Copyright (c) 2012-2021, 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 subsystem.
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/hs/hs_service.h"
75 #include "feature/nodelist/dirlist.h"
76 #include "feature/nodelist/networkstatus.h"
77 #include "feature/nodelist/nodelist.h"
78 #include "feature/nodelist/routerlist.h"
79 #include "feature/relay/router.h"
80 #include "feature/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 /* Global lists of channels */
89 /* All channel_t instances */
90 static smartlist_t
*all_channels
= NULL
;
92 /* All channel_t instances not in ERROR or CLOSED states */
93 static smartlist_t
*active_channels
= NULL
;
95 /* All channel_t instances in ERROR or CLOSED states */
96 static smartlist_t
*finished_channels
= NULL
;
98 /* All channel_listener_t instances */
99 static smartlist_t
*all_listeners
= NULL
;
101 /* All channel_listener_t instances in LISTENING state */
102 static smartlist_t
*active_listeners
= NULL
;
104 /* All channel_listener_t instances in LISTENING state */
105 static smartlist_t
*finished_listeners
= NULL
;
107 /** Map from channel->global_identifier to channel. Contains the same
108 * elements as all_channels. */
109 static HT_HEAD(channel_gid_map
, channel_t
) channel_gid_map
= HT_INITIALIZER();
112 channel_id_hash(const channel_t
*chan
)
114 return (unsigned) chan
->global_identifier
;
117 channel_id_eq(const channel_t
*a
, const channel_t
*b
)
119 return a
->global_identifier
== b
->global_identifier
;
121 HT_PROTOTYPE(channel_gid_map
, channel_t
, gidmap_node
,
122 channel_id_hash
, channel_id_eq
);
123 HT_GENERATE2(channel_gid_map
, channel_t
, gidmap_node
,
124 channel_id_hash
, channel_id_eq
,
125 0.6, tor_reallocarray_
, tor_free_
);
127 HANDLE_IMPL(channel
, channel_t
,)
129 /* Counter for ID numbers */
130 static uint64_t n_channels_allocated
= 0;
132 /* Digest->channel map
134 * Similar to the one used in connection_or.c, this maps from the identity
135 * digest of a remote endpoint to a channel_t to that endpoint. Channels
136 * should be placed here when registered and removed when they close or error.
137 * If more than one channel exists, follow the next_with_same_id pointer
140 static HT_HEAD(channel_idmap
, channel_idmap_entry_t
) channel_identity_map
=
143 typedef struct channel_idmap_entry_t
{
144 HT_ENTRY(channel_idmap_entry_t
) node
;
145 uint8_t digest
[DIGEST_LEN
];
146 TOR_LIST_HEAD(channel_list_t
, channel_t
) channel_list
;
147 } channel_idmap_entry_t
;
149 static inline unsigned
150 channel_idmap_hash(const channel_idmap_entry_t
*ent
)
152 return (unsigned) siphash24g(ent
->digest
, DIGEST_LEN
);
156 channel_idmap_eq(const channel_idmap_entry_t
*a
,
157 const channel_idmap_entry_t
*b
)
159 return tor_memeq(a
->digest
, b
->digest
, DIGEST_LEN
);
162 HT_PROTOTYPE(channel_idmap
, channel_idmap_entry_t
, node
, channel_idmap_hash
,
164 HT_GENERATE2(channel_idmap
, channel_idmap_entry_t
, node
, channel_idmap_hash
,
165 channel_idmap_eq
, 0.5, tor_reallocarray_
, tor_free_
);
167 /* Functions to maintain the digest map */
168 static void channel_remove_from_digest_map(channel_t
*chan
);
170 static void channel_force_xfree(channel_t
*chan
);
171 static void channel_free_list(smartlist_t
*channels
,
173 static void channel_listener_free_list(smartlist_t
*channels
,
175 static void channel_listener_force_xfree(channel_listener_t
*chan_l
);
177 /***********************************
178 * Channel state utility functions *
179 **********************************/
182 * Indicate whether a given channel state is valid.
185 channel_state_is_valid(channel_state_t state
)
190 case CHANNEL_STATE_CLOSED
:
191 case CHANNEL_STATE_CLOSING
:
192 case CHANNEL_STATE_ERROR
:
193 case CHANNEL_STATE_MAINT
:
194 case CHANNEL_STATE_OPENING
:
195 case CHANNEL_STATE_OPEN
:
198 case CHANNEL_STATE_LAST
:
207 * Indicate whether a given channel listener state is valid.
210 channel_listener_state_is_valid(channel_listener_state_t state
)
215 case CHANNEL_LISTENER_STATE_CLOSED
:
216 case CHANNEL_LISTENER_STATE_LISTENING
:
217 case CHANNEL_LISTENER_STATE_CLOSING
:
218 case CHANNEL_LISTENER_STATE_ERROR
:
221 case CHANNEL_LISTENER_STATE_LAST
:
230 * Indicate whether a channel state transition is valid.
232 * This function takes two channel states and indicates whether a
233 * transition between them is permitted (see the state definitions and
234 * transition table in or.h at the channel_state_t typedef).
237 channel_state_can_transition(channel_state_t from
, channel_state_t to
)
242 case CHANNEL_STATE_CLOSED
:
243 is_valid
= (to
== CHANNEL_STATE_OPENING
);
245 case CHANNEL_STATE_CLOSING
:
246 is_valid
= (to
== CHANNEL_STATE_CLOSED
||
247 to
== CHANNEL_STATE_ERROR
);
249 case CHANNEL_STATE_ERROR
:
252 case CHANNEL_STATE_MAINT
:
253 is_valid
= (to
== CHANNEL_STATE_CLOSING
||
254 to
== CHANNEL_STATE_ERROR
||
255 to
== CHANNEL_STATE_OPEN
);
257 case CHANNEL_STATE_OPENING
:
258 is_valid
= (to
== CHANNEL_STATE_CLOSING
||
259 to
== CHANNEL_STATE_ERROR
||
260 to
== CHANNEL_STATE_OPEN
);
262 case CHANNEL_STATE_OPEN
:
263 is_valid
= (to
== CHANNEL_STATE_CLOSING
||
264 to
== CHANNEL_STATE_ERROR
||
265 to
== CHANNEL_STATE_MAINT
);
267 case CHANNEL_STATE_LAST
:
276 * Indicate whether a channel listener state transition is valid.
278 * This function takes two channel listener states and indicates whether a
279 * transition between them is permitted (see the state definitions and
280 * transition table in or.h at the channel_listener_state_t typedef).
283 channel_listener_state_can_transition(channel_listener_state_t from
,
284 channel_listener_state_t to
)
289 case CHANNEL_LISTENER_STATE_CLOSED
:
290 is_valid
= (to
== CHANNEL_LISTENER_STATE_LISTENING
);
292 case CHANNEL_LISTENER_STATE_CLOSING
:
293 is_valid
= (to
== CHANNEL_LISTENER_STATE_CLOSED
||
294 to
== CHANNEL_LISTENER_STATE_ERROR
);
296 case CHANNEL_LISTENER_STATE_ERROR
:
299 case CHANNEL_LISTENER_STATE_LISTENING
:
300 is_valid
= (to
== CHANNEL_LISTENER_STATE_CLOSING
||
301 to
== CHANNEL_LISTENER_STATE_ERROR
);
303 case CHANNEL_LISTENER_STATE_LAST
:
312 * Return a human-readable description for a channel state.
315 channel_state_to_string(channel_state_t state
)
320 case CHANNEL_STATE_CLOSED
:
323 case CHANNEL_STATE_CLOSING
:
326 case CHANNEL_STATE_ERROR
:
327 descr
= "channel error";
329 case CHANNEL_STATE_MAINT
:
330 descr
= "temporarily suspended for maintenance";
332 case CHANNEL_STATE_OPENING
:
335 case CHANNEL_STATE_OPEN
:
338 case CHANNEL_STATE_LAST
:
340 descr
= "unknown or invalid channel state";
347 * Return a human-readable description for a channel listener state.
350 channel_listener_state_to_string(channel_listener_state_t state
)
355 case CHANNEL_LISTENER_STATE_CLOSED
:
358 case CHANNEL_LISTENER_STATE_CLOSING
:
361 case CHANNEL_LISTENER_STATE_ERROR
:
362 descr
= "channel listener error";
364 case CHANNEL_LISTENER_STATE_LISTENING
:
367 case CHANNEL_LISTENER_STATE_LAST
:
369 descr
= "unknown or invalid channel listener state";
375 /***************************************
376 * Channel registration/unregistration *
377 ***************************************/
380 * Register a channel.
382 * This function registers a newly created channel in the global lists/maps
383 * of active channels.
386 channel_register(channel_t
*chan
)
389 tor_assert(chan
->global_identifier
);
391 /* No-op if already registered */
392 if (chan
->registered
) return;
394 log_debug(LD_CHANNEL
,
395 "Registering channel %p (ID %"PRIu64
") "
396 "in state %s (%d) with digest %s",
397 chan
, (chan
->global_identifier
),
398 channel_state_to_string(chan
->state
), chan
->state
,
399 hex_str(chan
->identity_digest
, DIGEST_LEN
));
401 /* Make sure we have all_channels, then add it */
402 if (!all_channels
) all_channels
= smartlist_new();
403 smartlist_add(all_channels
, chan
);
404 channel_t
*oldval
= HT_REPLACE(channel_gid_map
, &channel_gid_map
, chan
);
405 tor_assert(! oldval
);
407 /* Is it finished? */
408 if (CHANNEL_FINISHED(chan
)) {
409 /* Put it in the finished list, creating it if necessary */
410 if (!finished_channels
) finished_channels
= smartlist_new();
411 smartlist_add(finished_channels
, chan
);
412 mainloop_schedule_postloop_cleanup();
414 /* Put it in the active list, creating it if necessary */
415 if (!active_channels
) active_channels
= smartlist_new();
416 smartlist_add(active_channels
, chan
);
418 if (!CHANNEL_IS_CLOSING(chan
)) {
419 /* It should have a digest set */
420 if (!tor_digest_is_zero(chan
->identity_digest
)) {
421 /* Yeah, we're good, add it to the map */
422 channel_add_to_digest_map(chan
);
425 "Channel %p (global ID %"PRIu64
") "
426 "in state %s (%d) registered with no identity digest",
427 chan
, (chan
->global_identifier
),
428 channel_state_to_string(chan
->state
), chan
->state
);
433 /* Mark it as registered */
434 chan
->registered
= 1;
438 * Unregister a channel.
440 * This function removes a channel from the global lists and maps and is used
441 * when freeing a closed/errored channel.
444 channel_unregister(channel_t
*chan
)
448 /* No-op if not registered */
449 if (!(chan
->registered
)) return;
451 /* Is it finished? */
452 if (CHANNEL_FINISHED(chan
)) {
453 /* Get it out of the finished list */
454 if (finished_channels
) smartlist_remove(finished_channels
, chan
);
456 /* Get it out of the active list */
457 if (active_channels
) smartlist_remove(active_channels
, chan
);
460 /* Get it out of all_channels */
461 if (all_channels
) smartlist_remove(all_channels
, chan
);
462 channel_t
*oldval
= HT_REMOVE(channel_gid_map
, &channel_gid_map
, chan
);
463 tor_assert(oldval
== NULL
|| oldval
== chan
);
465 /* Mark it as unregistered */
466 chan
->registered
= 0;
468 /* Should it be in the digest map? */
469 if (!tor_digest_is_zero(chan
->identity_digest
) &&
470 !(CHANNEL_CONDEMNED(chan
))) {
472 channel_remove_from_digest_map(chan
);
477 * Register a channel listener.
479 * This function registers a newly created channel listener in the global
480 * lists/maps of active channel listeners.
483 channel_listener_register(channel_listener_t
*chan_l
)
487 /* No-op if already registered */
488 if (chan_l
->registered
) return;
490 log_debug(LD_CHANNEL
,
491 "Registering channel listener %p (ID %"PRIu64
") "
493 chan_l
, (chan_l
->global_identifier
),
494 channel_listener_state_to_string(chan_l
->state
),
497 /* Make sure we have all_listeners, then add it */
498 if (!all_listeners
) all_listeners
= smartlist_new();
499 smartlist_add(all_listeners
, chan_l
);
501 /* Is it finished? */
502 if (chan_l
->state
== CHANNEL_LISTENER_STATE_CLOSED
||
503 chan_l
->state
== CHANNEL_LISTENER_STATE_ERROR
) {
504 /* Put it in the finished list, creating it if necessary */
505 if (!finished_listeners
) finished_listeners
= smartlist_new();
506 smartlist_add(finished_listeners
, chan_l
);
508 /* Put it in the active list, creating it if necessary */
509 if (!active_listeners
) active_listeners
= smartlist_new();
510 smartlist_add(active_listeners
, chan_l
);
513 /* Mark it as registered */
514 chan_l
->registered
= 1;
518 * Unregister a channel listener.
520 * This function removes a channel listener from the global lists and maps
521 * and is used when freeing a closed/errored channel listener.
524 channel_listener_unregister(channel_listener_t
*chan_l
)
528 /* No-op if not registered */
529 if (!(chan_l
->registered
)) return;
531 /* Is it finished? */
532 if (chan_l
->state
== CHANNEL_LISTENER_STATE_CLOSED
||
533 chan_l
->state
== CHANNEL_LISTENER_STATE_ERROR
) {
534 /* Get it out of the finished list */
535 if (finished_listeners
) smartlist_remove(finished_listeners
, chan_l
);
537 /* Get it out of the active list */
538 if (active_listeners
) smartlist_remove(active_listeners
, chan_l
);
541 /* Get it out of all_listeners */
542 if (all_listeners
) smartlist_remove(all_listeners
, chan_l
);
544 /* Mark it as unregistered */
545 chan_l
->registered
= 0;
548 /*********************************
549 * Channel digest map maintenance
550 *********************************/
553 * Add a channel to the digest map.
555 * This function adds a channel to the digest map and inserts it into the
556 * correct linked list if channels with that remote endpoint identity digest
560 channel_add_to_digest_map(channel_t
*chan
)
562 channel_idmap_entry_t
*ent
, search
;
566 /* Assert that the state makes sense */
567 tor_assert(!CHANNEL_CONDEMNED(chan
));
569 /* Assert that there is a digest */
570 tor_assert(!tor_digest_is_zero(chan
->identity_digest
));
572 memcpy(search
.digest
, chan
->identity_digest
, DIGEST_LEN
);
573 ent
= HT_FIND(channel_idmap
, &channel_identity_map
, &search
);
575 ent
= tor_malloc(sizeof(channel_idmap_entry_t
));
576 memcpy(ent
->digest
, chan
->identity_digest
, DIGEST_LEN
);
577 TOR_LIST_INIT(&ent
->channel_list
);
578 HT_INSERT(channel_idmap
, &channel_identity_map
, ent
);
580 TOR_LIST_INSERT_HEAD(&ent
->channel_list
, chan
, next_with_same_id
);
582 log_debug(LD_CHANNEL
,
583 "Added channel %p (global ID %"PRIu64
") "
584 "to identity map in state %s (%d) with digest %s",
585 chan
, (chan
->global_identifier
),
586 channel_state_to_string(chan
->state
), chan
->state
,
587 hex_str(chan
->identity_digest
, DIGEST_LEN
));
591 * Remove a channel from the digest map.
593 * This function removes a channel from the digest map and the linked list of
594 * channels for that digest if more than one exists.
597 channel_remove_from_digest_map(channel_t
*chan
)
599 channel_idmap_entry_t
*ent
, search
;
603 /* Assert that there is a digest */
604 tor_assert(!tor_digest_is_zero(chan
->identity_digest
));
606 /* Pull it out of its list, wherever that list is */
607 TOR_LIST_REMOVE(chan
, next_with_same_id
);
609 memcpy(search
.digest
, chan
->identity_digest
, DIGEST_LEN
);
610 ent
= HT_FIND(channel_idmap
, &channel_identity_map
, &search
);
612 /* Look for it in the map */
614 /* Okay, it's here */
616 if (TOR_LIST_EMPTY(&ent
->channel_list
)) {
617 HT_REMOVE(channel_idmap
, &channel_identity_map
, ent
);
621 log_debug(LD_CHANNEL
,
622 "Removed channel %p (global ID %"PRIu64
") from "
623 "identity map in state %s (%d) with digest %s",
624 chan
, (chan
->global_identifier
),
625 channel_state_to_string(chan
->state
), chan
->state
,
626 hex_str(chan
->identity_digest
, DIGEST_LEN
));
628 /* Shouldn't happen */
630 "Trying to remove channel %p (global ID %"PRIu64
") with "
631 "digest %s from identity map, but couldn't find any with "
633 chan
, (chan
->global_identifier
),
634 hex_str(chan
->identity_digest
, DIGEST_LEN
));
638 /****************************
639 * Channel lookup functions *
640 ***************************/
643 * Find channel by global ID.
645 * This function searches for a channel by the global_identifier assigned
646 * at initialization time. This identifier is unique for the lifetime of the
650 channel_find_by_global_id(uint64_t global_identifier
)
653 channel_t
*rv
= NULL
;
655 lookup
.global_identifier
= global_identifier
;
656 rv
= HT_FIND(channel_gid_map
, &channel_gid_map
, &lookup
);
658 tor_assert(rv
->global_identifier
== global_identifier
);
664 /** Return true iff <b>chan</b> matches <b>rsa_id_digest</b> and <b>ed_id</b>.
665 * as its identity keys. If either is NULL, do not check for a match. */
667 channel_remote_identity_matches(const channel_t
*chan
,
668 const char *rsa_id_digest
,
669 const ed25519_public_key_t
*ed_id
)
674 if (tor_memneq(rsa_id_digest
, chan
->identity_digest
, DIGEST_LEN
))
678 if (tor_memneq(ed_id
->pubkey
, chan
->ed25519_identity
.pubkey
,
686 * Find channel by RSA/Ed25519 identity of of the remote endpoint.
688 * This function looks up a channel by the digest of its remote endpoint's RSA
689 * identity key. If <b>ed_id</b> is provided and nonzero, only a channel
690 * matching the <b>ed_id</b> will be returned.
692 * It's possible that more than one channel to a given endpoint exists. Use
693 * channel_next_with_rsa_identity() to walk the list of channels; make sure
694 * to test for Ed25519 identity match too (as appropriate)
697 channel_find_by_remote_identity(const char *rsa_id_digest
,
698 const ed25519_public_key_t
*ed_id
)
700 channel_t
*rv
= NULL
;
701 channel_idmap_entry_t
*ent
, search
;
703 tor_assert(rsa_id_digest
); /* For now, we require that every channel have
704 * an RSA identity, and that every lookup
705 * contain an RSA identity */
706 if (ed_id
&& ed25519_public_key_is_zero(ed_id
)) {
707 /* Treat zero as meaning "We don't care about the presence or absence of
708 * an Ed key", not "There must be no Ed key". */
712 memcpy(search
.digest
, rsa_id_digest
, DIGEST_LEN
);
713 ent
= HT_FIND(channel_idmap
, &channel_identity_map
, &search
);
715 rv
= TOR_LIST_FIRST(&ent
->channel_list
);
717 while (rv
&& ! channel_remote_identity_matches(rv
, rsa_id_digest
, ed_id
)) {
718 rv
= channel_next_with_rsa_identity(rv
);
725 * Get next channel with digest.
727 * This function takes a channel and finds the next channel in the list
728 * with the same digest.
731 channel_next_with_rsa_identity(channel_t
*chan
)
735 return TOR_LIST_NEXT(chan
, next_with_same_id
);
739 * Relays run this once an hour to look over our list of channels to other
740 * relays. It prints out some statistics if there are multiple connections
743 * This function is similar to connection_or_set_bad_connections(),
744 * and probably could be adapted to replace it, if it was modified to actually
745 * take action on any of these connections.
748 channel_check_for_duplicates(void)
750 channel_idmap_entry_t
**iter
;
752 int total_dirauth_connections
= 0, total_dirauths
= 0;
753 int total_relay_connections
= 0, total_relays
= 0, total_canonical
= 0;
754 int total_half_canonical
= 0;
755 int total_gt_one_connection
= 0, total_gt_two_connections
= 0;
756 int total_gt_four_connections
= 0;
758 HT_FOREACH(iter
, channel_idmap
, &channel_identity_map
) {
759 int connections_to_relay
= 0;
760 const char *id_digest
= (char *) (*iter
)->digest
;
762 /* Only consider relay connections */
763 if (!connection_or_digest_is_known_relay(id_digest
))
768 const bool is_dirauth
= router_digest_is_trusted_dir(id_digest
);
772 for (chan
= TOR_LIST_FIRST(&(*iter
)->channel_list
); chan
;
773 chan
= channel_next_with_rsa_identity(chan
)) {
775 if (CHANNEL_CONDEMNED(chan
) || !CHANNEL_IS_OPEN(chan
))
778 connections_to_relay
++;
779 total_relay_connections
++;
781 total_dirauth_connections
++;
783 if (chan
->is_canonical(chan
)) total_canonical
++;
785 if (!chan
->is_canonical_to_peer
&& chan
->is_canonical(chan
)) {
786 total_half_canonical
++;
790 if (connections_to_relay
> 1) total_gt_one_connection
++;
791 if (connections_to_relay
> 2) total_gt_two_connections
++;
792 if (connections_to_relay
> 4) total_gt_four_connections
++;
795 /* Don't bother warning about excessive connections unless we have
796 * at least this many connections, total.
798 #define MIN_RELAY_CONNECTIONS_TO_WARN 25
799 /* If the average number of connections for a regular relay is more than
800 * this, that's too high.
802 #define MAX_AVG_RELAY_CONNECTIONS 1.5
803 /* If the average number of connections for a dirauth is more than
804 * this, that's too high.
806 #define MAX_AVG_DIRAUTH_CONNECTIONS 4
808 /* How many connections total would be okay, given the number of
809 * relays and dirauths that we have connections to? */
810 const int max_tolerable_connections
= (int)(
811 (total_relays
-total_dirauths
) * MAX_AVG_RELAY_CONNECTIONS
+
812 total_dirauths
* MAX_AVG_DIRAUTH_CONNECTIONS
);
814 /* If we average 1.5 or more connections per relay, something is wrong */
815 if (total_relays
> MIN_RELAY_CONNECTIONS_TO_WARN
&&
816 total_relay_connections
> max_tolerable_connections
) {
818 "Your relay has a very large number of connections to other relays. "
819 "Is your outbound address the same as your relay address? "
820 "Found %d connections to %d relays. Found %d current canonical "
821 "connections, in %d of which we were a non-canonical peer. "
822 "%d relays had more than 1 connection, %d had more than 2, and "
823 "%d had more than 4 connections.",
824 total_relay_connections
, total_relays
, total_canonical
,
825 total_half_canonical
, total_gt_one_connection
,
826 total_gt_two_connections
, total_gt_four_connections
);
828 log_info(LD_OR
, "Performed connection pruning. "
829 "Found %d connections to %d relays. Found %d current canonical "
830 "connections, in %d of which we were a non-canonical peer. "
831 "%d relays had more than 1 connection, %d had more than 2, and "
832 "%d had more than 4 connections.",
833 total_relay_connections
, total_relays
, total_canonical
,
834 total_half_canonical
, total_gt_one_connection
,
835 total_gt_two_connections
, total_gt_four_connections
);
840 * Initialize a channel.
842 * This function should be called by subclasses to set up some per-channel
843 * variables. I.e., this is the superclass constructor. Before this, the
844 * channel should be allocated with tor_malloc_zero().
847 channel_init(channel_t
*chan
)
851 /* Assign an ID and bump the counter */
852 chan
->global_identifier
= ++n_channels_allocated
;
855 chan
->timestamp_last_had_circuits
= time(NULL
);
857 /* Warn about exhausted circuit IDs no more than hourly. */
858 chan
->last_warned_circ_ids_exhausted
.rate
= 3600;
860 /* Initialize list entries. */
861 memset(&chan
->next_with_same_id
, 0, sizeof(chan
->next_with_same_id
));
864 channel_timestamp_created(chan
);
866 /* It hasn't been open yet. */
867 chan
->has_been_open
= 0;
869 /* Scheduler state is idle */
870 chan
->scheduler_state
= SCHED_CHAN_IDLE
;
872 /* Channel is not in the scheduler heap. */
873 chan
->sched_heap_idx
= -1;
875 tor_addr_make_unspec(&chan
->addr_according_to_peer
);
879 * Initialize a channel listener.
881 * This function should be called by subclasses to set up some per-channel
882 * variables. I.e., this is the superclass constructor. Before this, the
883 * channel listener should be allocated with tor_malloc_zero().
886 channel_init_listener(channel_listener_t
*chan_l
)
890 /* Assign an ID and bump the counter */
891 chan_l
->global_identifier
= ++n_channels_allocated
;
894 channel_listener_timestamp_created(chan_l
);
898 * Free a channel; nothing outside of channel.c and subclasses should call
899 * this - it frees channels after they have closed and been unregistered.
902 channel_free_(channel_t
*chan
)
906 /* It must be closed or errored */
907 tor_assert(CHANNEL_FINISHED(chan
));
909 /* It must be deregistered */
910 tor_assert(!(chan
->registered
));
912 log_debug(LD_CHANNEL
,
913 "Freeing channel %"PRIu64
" at %p",
914 (chan
->global_identifier
), chan
);
916 /* Get this one out of the scheduler */
917 scheduler_release_channel(chan
);
920 * Get rid of cmux policy before we do anything, so cmux policies don't
921 * see channels in weird half-freed states.
924 circuitmux_set_policy(chan
->cmux
, NULL
);
927 /* Remove all timers and associated handle entries now */
928 timer_free(chan
->padding_timer
);
929 channel_handle_free(chan
->timer_handle
);
930 channel_handles_clear(chan
);
932 /* Call a free method if there is one */
933 if (chan
->free_fn
) chan
->free_fn(chan
);
935 channel_clear_remote_end(chan
);
937 /* Get rid of cmux */
939 circuitmux_detach_all_circuits(chan
->cmux
, NULL
);
940 circuitmux_mark_destroyed_circids_usable(chan
->cmux
, chan
);
941 circuitmux_free(chan
->cmux
);
949 * Free a channel listener; nothing outside of channel.c and subclasses
950 * should call this - it frees channel listeners after they have closed and
954 channel_listener_free_(channel_listener_t
*chan_l
)
958 log_debug(LD_CHANNEL
,
959 "Freeing channel_listener_t %"PRIu64
" at %p",
960 (chan_l
->global_identifier
),
963 /* It must be closed or errored */
964 tor_assert(chan_l
->state
== CHANNEL_LISTENER_STATE_CLOSED
||
965 chan_l
->state
== CHANNEL_LISTENER_STATE_ERROR
);
966 /* It must be deregistered */
967 tor_assert(!(chan_l
->registered
));
969 /* Call a free method if there is one */
970 if (chan_l
->free_fn
) chan_l
->free_fn(chan_l
);
976 * Free a channel and skip the state/registration asserts; this internal-
977 * use-only function should be called only from channel_free_all() when
978 * shutting down the Tor process.
981 channel_force_xfree(channel_t
*chan
)
985 log_debug(LD_CHANNEL
,
986 "Force-freeing channel %"PRIu64
" at %p",
987 (chan
->global_identifier
), chan
);
989 /* Get this one out of the scheduler */
990 scheduler_release_channel(chan
);
993 * Get rid of cmux policy before we do anything, so cmux policies don't
994 * see channels in weird half-freed states.
997 circuitmux_set_policy(chan
->cmux
, NULL
);
1000 /* Remove all timers and associated handle entries now */
1001 timer_free(chan
->padding_timer
);
1002 channel_handle_free(chan
->timer_handle
);
1003 channel_handles_clear(chan
);
1005 /* Call a free method if there is one */
1006 if (chan
->free_fn
) chan
->free_fn(chan
);
1008 channel_clear_remote_end(chan
);
1010 /* Get rid of cmux */
1012 circuitmux_free(chan
->cmux
);
1020 * Free a channel listener and skip the state/registration asserts; this
1021 * internal-use-only function should be called only from channel_free_all()
1022 * when shutting down the Tor process.
1025 channel_listener_force_xfree(channel_listener_t
*chan_l
)
1029 log_debug(LD_CHANNEL
,
1030 "Force-freeing channel_listener_t %"PRIu64
" at %p",
1031 (chan_l
->global_identifier
),
1034 /* Call a free method if there is one */
1035 if (chan_l
->free_fn
) chan_l
->free_fn(chan_l
);
1038 * The incoming list just gets emptied and freed; we request close on
1039 * any channels we find there, but since we got called while shutting
1040 * down they will get deregistered and freed elsewhere anyway.
1042 if (chan_l
->incoming_list
) {
1043 SMARTLIST_FOREACH_BEGIN(chan_l
->incoming_list
,
1044 channel_t
*, qchan
) {
1045 channel_mark_for_close(qchan
);
1046 } SMARTLIST_FOREACH_END(qchan
);
1048 smartlist_free(chan_l
->incoming_list
);
1049 chan_l
->incoming_list
= NULL
;
1056 * Set the listener for a channel listener.
1058 * This function sets the handler for new incoming channels on a channel
1062 channel_listener_set_listener_fn(channel_listener_t
*chan_l
,
1063 channel_listener_fn_ptr listener
)
1066 tor_assert(chan_l
->state
== CHANNEL_LISTENER_STATE_LISTENING
);
1068 log_debug(LD_CHANNEL
,
1069 "Setting listener callback for channel listener %p "
1070 "(global ID %"PRIu64
") to %p",
1071 chan_l
, (chan_l
->global_identifier
),
1074 chan_l
->listener
= listener
;
1075 if (chan_l
->listener
) channel_listener_process_incoming(chan_l
);
1079 * Return the fixed-length cell handler for a channel.
1081 * This function gets the handler for incoming fixed-length cells installed
1084 channel_cell_handler_fn_ptr
1085 channel_get_cell_handler(channel_t
*chan
)
1089 if (CHANNEL_CAN_HANDLE_CELLS(chan
))
1090 return chan
->cell_handler
;
1096 * Set both cell handlers for a channel.
1098 * This function sets both the fixed-length and variable length cell handlers
1102 channel_set_cell_handlers(channel_t
*chan
,
1103 channel_cell_handler_fn_ptr cell_handler
)
1106 tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan
));
1108 log_debug(LD_CHANNEL
,
1109 "Setting cell_handler callback for channel %p to %p",
1110 chan
, cell_handler
);
1113 chan
->cell_handler
= cell_handler
;
1117 * On closing channels
1119 * There are three functions that close channels, for use in
1120 * different circumstances:
1122 * - Use channel_mark_for_close() for most cases
1123 * - Use channel_close_from_lower_layer() if you are connection_or.c
1124 * and the other end closes the underlying connection.
1125 * - Use channel_close_for_error() if you are connection_or.c and
1126 * some sort of error has occurred.
1130 * Mark a channel for closure.
1132 * This function tries to close a channel_t; it will go into the CLOSING
1133 * state, and eventually the lower layer should put it into the CLOSED or
1134 * ERROR state. Then, channel_run_cleanup() will eventually free it.
1137 channel_mark_for_close(channel_t
*chan
)
1139 tor_assert(chan
!= NULL
);
1140 tor_assert(chan
->close
!= NULL
);
1142 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1143 if (CHANNEL_CONDEMNED(chan
))
1146 log_debug(LD_CHANNEL
,
1147 "Closing channel %p (global ID %"PRIu64
") "
1149 chan
, (chan
->global_identifier
));
1151 /* Note closing by request from above */
1152 chan
->reason_for_closing
= CHANNEL_CLOSE_REQUESTED
;
1154 /* Change state to CLOSING */
1155 channel_change_state(chan
, CHANNEL_STATE_CLOSING
);
1157 /* Tell the lower layer */
1161 * It's up to the lower layer to change state to CLOSED or ERROR when we're
1162 * ready; we'll try to free channels that are in the finished list from
1163 * channel_run_cleanup(). The lower layer should do this by calling
1169 * Mark a channel listener for closure.
1171 * This function tries to close a channel_listener_t; it will go into the
1172 * CLOSING state, and eventually the lower layer should put it into the CLOSED
1173 * or ERROR state. Then, channel_run_cleanup() will eventually free it.
1176 channel_listener_mark_for_close(channel_listener_t
*chan_l
)
1178 tor_assert(chan_l
!= NULL
);
1179 tor_assert(chan_l
->close
!= NULL
);
1181 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1182 if (chan_l
->state
== CHANNEL_LISTENER_STATE_CLOSING
||
1183 chan_l
->state
== CHANNEL_LISTENER_STATE_CLOSED
||
1184 chan_l
->state
== CHANNEL_LISTENER_STATE_ERROR
) return;
1186 log_debug(LD_CHANNEL
,
1187 "Closing channel listener %p (global ID %"PRIu64
") "
1189 chan_l
, (chan_l
->global_identifier
));
1191 /* Note closing by request from above */
1192 chan_l
->reason_for_closing
= CHANNEL_LISTENER_CLOSE_REQUESTED
;
1194 /* Change state to CLOSING */
1195 channel_listener_change_state(chan_l
, CHANNEL_LISTENER_STATE_CLOSING
);
1197 /* Tell the lower layer */
1198 chan_l
->close(chan_l
);
1201 * It's up to the lower layer to change state to CLOSED or ERROR when we're
1202 * ready; we'll try to free channels that are in the finished list from
1203 * channel_run_cleanup(). The lower layer should do this by calling
1204 * channel_listener_closed().
1209 * Close a channel from the lower layer.
1211 * Notify the channel code that the channel is being closed due to a non-error
1212 * condition in the lower layer. This does not call the close() method, since
1213 * the lower layer already knows.
1216 channel_close_from_lower_layer(channel_t
*chan
)
1218 tor_assert(chan
!= NULL
);
1220 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1221 if (CHANNEL_CONDEMNED(chan
))
1224 log_debug(LD_CHANNEL
,
1225 "Closing channel %p (global ID %"PRIu64
") "
1226 "due to lower-layer event",
1227 chan
, (chan
->global_identifier
));
1229 /* Note closing by event from below */
1230 chan
->reason_for_closing
= CHANNEL_CLOSE_FROM_BELOW
;
1232 /* Change state to CLOSING */
1233 channel_change_state(chan
, CHANNEL_STATE_CLOSING
);
1237 * Notify that the channel is being closed due to an error condition.
1239 * This function is called by the lower layer implementing the transport
1240 * when a channel must be closed due to an error condition. This does not
1241 * call the channel's close method, since the lower layer already knows.
1244 channel_close_for_error(channel_t
*chan
)
1246 tor_assert(chan
!= NULL
);
1248 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1249 if (CHANNEL_CONDEMNED(chan
))
1252 log_debug(LD_CHANNEL
,
1253 "Closing channel %p due to lower-layer error",
1256 /* Note closing by event from below */
1257 chan
->reason_for_closing
= CHANNEL_CLOSE_FOR_ERROR
;
1259 /* Change state to CLOSING */
1260 channel_change_state(chan
, CHANNEL_STATE_CLOSING
);
1264 * Notify that the lower layer is finished closing the channel.
1266 * This function should be called by the lower layer when a channel
1267 * is finished closing and it should be regarded as inactive and
1268 * freed by the channel code.
1271 channel_closed(channel_t
*chan
)
1274 tor_assert(CHANNEL_CONDEMNED(chan
));
1276 /* No-op if already inactive */
1277 if (CHANNEL_FINISHED(chan
))
1280 /* Inform any pending (not attached) circs that they should
1282 if (! chan
->has_been_open
)
1283 circuit_n_chan_done(chan
, 0, 0);
1285 /* Now close all the attached circuits on it. */
1286 circuit_unlink_all_from_channel(chan
, END_CIRC_REASON_CHANNEL_CLOSED
);
1288 if (chan
->reason_for_closing
!= CHANNEL_CLOSE_FOR_ERROR
) {
1289 channel_change_state(chan
, CHANNEL_STATE_CLOSED
);
1291 channel_change_state(chan
, CHANNEL_STATE_ERROR
);
1296 * Clear the identity_digest of a channel.
1298 * This function clears the identity digest of the remote endpoint for a
1299 * channel; this is intended for use by the lower layer.
1302 channel_clear_identity_digest(channel_t
*chan
)
1304 int state_not_in_map
;
1308 log_debug(LD_CHANNEL
,
1309 "Clearing remote endpoint digest on channel %p with "
1310 "global ID %"PRIu64
,
1311 chan
, (chan
->global_identifier
));
1313 state_not_in_map
= CHANNEL_CONDEMNED(chan
);
1315 if (!state_not_in_map
&& chan
->registered
&&
1316 !tor_digest_is_zero(chan
->identity_digest
))
1317 /* if it's registered get it out of the digest map */
1318 channel_remove_from_digest_map(chan
);
1320 memset(chan
->identity_digest
, 0,
1321 sizeof(chan
->identity_digest
));
1325 * Set the identity_digest of a channel.
1327 * This function sets the identity digest of the remote endpoint for a
1328 * channel; this is intended for use by the lower layer.
1331 channel_set_identity_digest(channel_t
*chan
,
1332 const char *identity_digest
,
1333 const ed25519_public_key_t
*ed_identity
)
1335 int was_in_digest_map
, should_be_in_digest_map
, state_not_in_map
;
1339 log_debug(LD_CHANNEL
,
1340 "Setting remote endpoint digest on channel %p with "
1341 "global ID %"PRIu64
" to digest %s",
1342 chan
, (chan
->global_identifier
),
1344 hex_str(identity_digest
, DIGEST_LEN
) : "(null)");
1346 state_not_in_map
= CHANNEL_CONDEMNED(chan
);
1349 !state_not_in_map
&&
1351 !tor_digest_is_zero(chan
->identity_digest
);
1352 should_be_in_digest_map
=
1353 !state_not_in_map
&&
1356 !tor_digest_is_zero(identity_digest
));
1358 if (was_in_digest_map
)
1359 /* We should always remove it; we'll add it back if we're writing
1362 channel_remove_from_digest_map(chan
);
1364 if (identity_digest
) {
1365 memcpy(chan
->identity_digest
,
1367 sizeof(chan
->identity_digest
));
1369 memset(chan
->identity_digest
, 0,
1370 sizeof(chan
->identity_digest
));
1373 memcpy(&chan
->ed25519_identity
, ed_identity
, sizeof(*ed_identity
));
1375 memset(&chan
->ed25519_identity
, 0, sizeof(*ed_identity
));
1378 /* Put it in the digest map if we should */
1379 if (should_be_in_digest_map
)
1380 channel_add_to_digest_map(chan
);
1384 * Clear the remote end metadata (identity_digest) of a channel.
1386 * This function clears all the remote end info from a channel; this is
1387 * intended for use by the lower layer.
1390 channel_clear_remote_end(channel_t
*chan
)
1392 int state_not_in_map
;
1396 log_debug(LD_CHANNEL
,
1397 "Clearing remote endpoint identity on channel %p with "
1398 "global ID %"PRIu64
,
1399 chan
, (chan
->global_identifier
));
1401 state_not_in_map
= CHANNEL_CONDEMNED(chan
);
1403 if (!state_not_in_map
&& chan
->registered
&&
1404 !tor_digest_is_zero(chan
->identity_digest
))
1405 /* if it's registered get it out of the digest map */
1406 channel_remove_from_digest_map(chan
);
1408 memset(chan
->identity_digest
, 0,
1409 sizeof(chan
->identity_digest
));
1413 * Write to a channel the given packed cell.
1415 * Two possible errors can happen. Either the channel is not opened or the
1416 * lower layer (specialized channel) failed to write it. In both cases, it is
1417 * the caller responsibility to free the cell.
1420 write_packed_cell(channel_t
*chan
, packed_cell_t
*cell
)
1424 uint8_t command
= packed_cell_get_command(cell
, chan
->wide_circ_ids
);
1429 /* Assert that the state makes sense for a cell write */
1430 tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan
));
1434 if (packed_cell_is_destroy(chan
, cell
, &circ_id
)) {
1435 channel_note_destroy_not_pending(chan
, circ_id
);
1439 /* For statistical purposes, figure out how big this cell is */
1440 cell_bytes
= get_cell_network_size(chan
->wide_circ_ids
);
1442 /* Can we send it right out? If so, try */
1443 if (!CHANNEL_IS_OPEN(chan
)) {
1447 /* Write the cell on the connection's outbuf. */
1448 if (chan
->write_packed_cell(chan
, cell
) < 0) {
1451 /* Timestamp for transmission */
1452 channel_timestamp_xmit(chan
);
1453 /* Update the counter */
1454 ++(chan
->n_cells_xmitted
);
1455 chan
->n_bytes_xmitted
+= cell_bytes
;
1456 /* Successfully sent the cell. */
1459 /* Update padding statistics for the packed codepath.. */
1460 rep_hist_padding_count_write(PADDING_TYPE_TOTAL
);
1461 if (command
== CELL_PADDING
)
1462 rep_hist_padding_count_write(PADDING_TYPE_CELL
);
1463 if (chan
->padding_enabled
) {
1464 rep_hist_padding_count_write(PADDING_TYPE_ENABLED_TOTAL
);
1465 if (command
== CELL_PADDING
)
1466 rep_hist_padding_count_write(PADDING_TYPE_ENABLED_CELL
);
1474 * Write a packed cell to a channel.
1476 * Write a packed cell to a channel using the write_cell() method. This is
1477 * called by the transport-independent code to deliver a packed cell to a
1478 * channel for transmission.
1480 * Return 0 on success else a negative value. In both cases, the caller should
1481 * not access the cell anymore, it is freed both on success and error.
1484 channel_write_packed_cell(channel_t
*chan
, packed_cell_t
*cell
)
1491 if (CHANNEL_IS_CLOSING(chan
)) {
1492 log_debug(LD_CHANNEL
, "Discarding %p on closing channel %p with "
1493 "global ID %"PRIu64
, cell
, chan
,
1494 (chan
->global_identifier
));
1497 log_debug(LD_CHANNEL
,
1498 "Writing %p to channel %p with global ID "
1499 "%"PRIu64
, cell
, chan
, (chan
->global_identifier
));
1501 ret
= write_packed_cell(chan
, cell
);
1504 /* Whatever happens, we free the cell. Either an error occurred or the cell
1505 * was put on the connection outbuf, both cases we have ownership of the
1506 * cell and we free it. */
1507 packed_cell_free(cell
);
1512 * Change channel state.
1514 * This internal and subclass use only function is used to change channel
1515 * state, performing all transition validity checks and whatever actions
1516 * are appropriate to the state transition in question.
1519 channel_change_state_(channel_t
*chan
, channel_state_t to_state
)
1521 channel_state_t from_state
;
1522 unsigned char was_active
, is_active
;
1523 unsigned char was_in_id_map
, is_in_id_map
;
1526 from_state
= chan
->state
;
1528 tor_assert(channel_state_is_valid(from_state
));
1529 tor_assert(channel_state_is_valid(to_state
));
1530 tor_assert(channel_state_can_transition(chan
->state
, to_state
));
1532 /* Check for no-op transitions */
1533 if (from_state
== to_state
) {
1534 log_debug(LD_CHANNEL
,
1535 "Got no-op transition from \"%s\" to itself on channel %p"
1536 "(global ID %"PRIu64
")",
1537 channel_state_to_string(to_state
),
1538 chan
, (chan
->global_identifier
));
1542 /* If we're going to a closing or closed state, we must have a reason set */
1543 if (to_state
== CHANNEL_STATE_CLOSING
||
1544 to_state
== CHANNEL_STATE_CLOSED
||
1545 to_state
== CHANNEL_STATE_ERROR
) {
1546 tor_assert(chan
->reason_for_closing
!= CHANNEL_NOT_CLOSING
);
1549 log_debug(LD_CHANNEL
,
1550 "Changing state of channel %p (global ID %"PRIu64
1551 ") from \"%s\" to \"%s\"",
1553 (chan
->global_identifier
),
1554 channel_state_to_string(chan
->state
),
1555 channel_state_to_string(to_state
));
1557 chan
->state
= to_state
;
1559 /* Need to add to the right lists if the channel is registered */
1560 if (chan
->registered
) {
1561 was_active
= !(from_state
== CHANNEL_STATE_CLOSED
||
1562 from_state
== CHANNEL_STATE_ERROR
);
1563 is_active
= !(to_state
== CHANNEL_STATE_CLOSED
||
1564 to_state
== CHANNEL_STATE_ERROR
);
1566 /* Need to take off active list and put on finished list? */
1567 if (was_active
&& !is_active
) {
1568 if (active_channels
) smartlist_remove(active_channels
, chan
);
1569 if (!finished_channels
) finished_channels
= smartlist_new();
1570 smartlist_add(finished_channels
, chan
);
1571 mainloop_schedule_postloop_cleanup();
1573 /* Need to put on active list? */
1574 else if (!was_active
&& is_active
) {
1575 if (finished_channels
) smartlist_remove(finished_channels
, chan
);
1576 if (!active_channels
) active_channels
= smartlist_new();
1577 smartlist_add(active_channels
, chan
);
1580 if (!tor_digest_is_zero(chan
->identity_digest
)) {
1581 /* Now we need to handle the identity map */
1582 was_in_id_map
= !(from_state
== CHANNEL_STATE_CLOSING
||
1583 from_state
== CHANNEL_STATE_CLOSED
||
1584 from_state
== CHANNEL_STATE_ERROR
);
1585 is_in_id_map
= !(to_state
== CHANNEL_STATE_CLOSING
||
1586 to_state
== CHANNEL_STATE_CLOSED
||
1587 to_state
== CHANNEL_STATE_ERROR
);
1589 if (!was_in_id_map
&& is_in_id_map
) channel_add_to_digest_map(chan
);
1590 else if (was_in_id_map
&& !is_in_id_map
)
1591 channel_remove_from_digest_map(chan
);
1596 * If we're going to a closed/closing state, we don't need scheduling any
1597 * more; in CHANNEL_STATE_MAINT we can't accept writes.
1599 if (to_state
== CHANNEL_STATE_CLOSING
||
1600 to_state
== CHANNEL_STATE_CLOSED
||
1601 to_state
== CHANNEL_STATE_ERROR
) {
1602 scheduler_release_channel(chan
);
1603 } else if (to_state
== CHANNEL_STATE_MAINT
) {
1604 scheduler_channel_doesnt_want_writes(chan
);
1609 * As channel_change_state_, but change the state to any state but open.
1612 channel_change_state(channel_t
*chan
, channel_state_t to_state
)
1614 tor_assert(to_state
!= CHANNEL_STATE_OPEN
);
1615 channel_change_state_(chan
, to_state
);
1619 * As channel_change_state, but change the state to open.
1622 channel_change_state_open(channel_t
*chan
)
1624 channel_change_state_(chan
, CHANNEL_STATE_OPEN
);
1626 /* Tell circuits if we opened and stuff */
1627 channel_do_open_actions(chan
);
1628 chan
->has_been_open
= 1;
1632 * Change channel listener state.
1634 * This internal and subclass use only function is used to change channel
1635 * listener state, performing all transition validity checks and whatever
1636 * actions are appropriate to the state transition in question.
1639 channel_listener_change_state(channel_listener_t
*chan_l
,
1640 channel_listener_state_t to_state
)
1642 channel_listener_state_t from_state
;
1643 unsigned char was_active
, is_active
;
1646 from_state
= chan_l
->state
;
1648 tor_assert(channel_listener_state_is_valid(from_state
));
1649 tor_assert(channel_listener_state_is_valid(to_state
));
1650 tor_assert(channel_listener_state_can_transition(chan_l
->state
, to_state
));
1652 /* Check for no-op transitions */
1653 if (from_state
== to_state
) {
1654 log_debug(LD_CHANNEL
,
1655 "Got no-op transition from \"%s\" to itself on channel "
1656 "listener %p (global ID %"PRIu64
")",
1657 channel_listener_state_to_string(to_state
),
1658 chan_l
, (chan_l
->global_identifier
));
1662 /* If we're going to a closing or closed state, we must have a reason set */
1663 if (to_state
== CHANNEL_LISTENER_STATE_CLOSING
||
1664 to_state
== CHANNEL_LISTENER_STATE_CLOSED
||
1665 to_state
== CHANNEL_LISTENER_STATE_ERROR
) {
1666 tor_assert(chan_l
->reason_for_closing
!= CHANNEL_LISTENER_NOT_CLOSING
);
1669 log_debug(LD_CHANNEL
,
1670 "Changing state of channel listener %p (global ID %"PRIu64
1671 "from \"%s\" to \"%s\"",
1672 chan_l
, (chan_l
->global_identifier
),
1673 channel_listener_state_to_string(chan_l
->state
),
1674 channel_listener_state_to_string(to_state
));
1676 chan_l
->state
= to_state
;
1678 /* Need to add to the right lists if the channel listener is registered */
1679 if (chan_l
->registered
) {
1680 was_active
= !(from_state
== CHANNEL_LISTENER_STATE_CLOSED
||
1681 from_state
== CHANNEL_LISTENER_STATE_ERROR
);
1682 is_active
= !(to_state
== CHANNEL_LISTENER_STATE_CLOSED
||
1683 to_state
== CHANNEL_LISTENER_STATE_ERROR
);
1685 /* Need to take off active list and put on finished list? */
1686 if (was_active
&& !is_active
) {
1687 if (active_listeners
) smartlist_remove(active_listeners
, chan_l
);
1688 if (!finished_listeners
) finished_listeners
= smartlist_new();
1689 smartlist_add(finished_listeners
, chan_l
);
1690 mainloop_schedule_postloop_cleanup();
1692 /* Need to put on active list? */
1693 else if (!was_active
&& is_active
) {
1694 if (finished_listeners
) smartlist_remove(finished_listeners
, chan_l
);
1695 if (!active_listeners
) active_listeners
= smartlist_new();
1696 smartlist_add(active_listeners
, chan_l
);
1700 if (to_state
== CHANNEL_LISTENER_STATE_CLOSED
||
1701 to_state
== CHANNEL_LISTENER_STATE_ERROR
) {
1702 tor_assert(!(chan_l
->incoming_list
) ||
1703 smartlist_len(chan_l
->incoming_list
) == 0);
1707 /* Maximum number of cells that is allowed to flush at once within
1708 * channel_flush_some_cells(). */
1709 #define MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED 256
1712 * Try to flush cells of the given channel chan up to a maximum of num_cells.
1714 * This is called by the scheduler when it wants to flush cells from the
1715 * channel's circuit queue(s) to the connection outbuf (not yet on the wire).
1717 * If the channel is not in state CHANNEL_STATE_OPEN, this does nothing and
1718 * will return 0 meaning no cells were flushed.
1720 * If num_cells is -1, we'll try to flush up to the maximum cells allowed
1721 * defined in MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED.
1723 * On success, the number of flushed cells are returned and it can never be
1724 * above num_cells. If 0 is returned, no cells were flushed either because the
1725 * channel was not opened or we had no cells on the channel. A negative number
1726 * can NOT be sent back.
1728 * This function is part of the fast path. */
1730 channel_flush_some_cells
, (channel_t
*chan
, ssize_t num_cells
))
1732 unsigned int unlimited
= 0;
1733 ssize_t flushed
= 0;
1734 int clamped_num_cells
;
1738 if (num_cells
< 0) unlimited
= 1;
1739 if (!unlimited
&& num_cells
<= flushed
) goto done
;
1741 /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
1742 if (CHANNEL_IS_OPEN(chan
)) {
1743 if (circuitmux_num_cells(chan
->cmux
) > 0) {
1744 /* Calculate number of cells, including clamp */
1746 clamped_num_cells
= MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED
;
1748 if (num_cells
- flushed
>
1749 MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED
) {
1750 clamped_num_cells
= MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED
;
1752 clamped_num_cells
= (int)(num_cells
- flushed
);
1756 /* Try to get more cells from any active circuits */
1757 flushed
= channel_flush_from_first_active_circuit(
1758 chan
, clamped_num_cells
);
1767 * Check if any cells are available.
1769 * This is used by the scheduler to know if the channel has more to flush
1770 * after a scheduling round.
1773 channel_more_to_flush
, (channel_t
*chan
))
1777 if (circuitmux_num_cells(chan
->cmux
) > 0) return 1;
1784 * Notify the channel we're done flushing the output in the lower layer.
1786 * Connection.c will call this when we've flushed the output; there's some
1787 * dirreq-related maintenance to do.
1790 channel_notify_flushed(channel_t
*chan
)
1794 if (chan
->dirreq_id
!= 0)
1795 geoip_change_dirreq_state(chan
->dirreq_id
,
1797 DIRREQ_CHANNEL_BUFFER_FLUSHED
);
1801 * Process the queue of incoming channels on a listener.
1803 * Use a listener's registered callback to process as many entries in the
1804 * queue of incoming channels as possible.
1807 channel_listener_process_incoming(channel_listener_t
*listener
)
1809 tor_assert(listener
);
1812 * CHANNEL_LISTENER_STATE_CLOSING permitted because we drain the queue
1813 * while closing a listener.
1815 tor_assert(listener
->state
== CHANNEL_LISTENER_STATE_LISTENING
||
1816 listener
->state
== CHANNEL_LISTENER_STATE_CLOSING
);
1817 tor_assert(listener
->listener
);
1819 log_debug(LD_CHANNEL
,
1820 "Processing queue of incoming connections for channel "
1821 "listener %p (global ID %"PRIu64
")",
1822 listener
, (listener
->global_identifier
));
1824 if (!(listener
->incoming_list
)) return;
1826 SMARTLIST_FOREACH_BEGIN(listener
->incoming_list
,
1827 channel_t
*, chan
) {
1830 log_debug(LD_CHANNEL
,
1831 "Handling incoming channel %p (%"PRIu64
") "
1832 "for listener %p (%"PRIu64
")",
1834 (chan
->global_identifier
),
1836 (listener
->global_identifier
));
1837 /* Make sure this is set correctly */
1838 channel_mark_incoming(chan
);
1839 listener
->listener(listener
, chan
);
1840 } SMARTLIST_FOREACH_END(chan
);
1842 smartlist_free(listener
->incoming_list
);
1843 listener
->incoming_list
= NULL
;
1847 * Take actions required when a channel becomes open.
1849 * Handle actions we should do when we know a channel is open; a lot of
1850 * this comes from the old connection_or_set_state_open() of connection_or.c.
1852 * Because of this mechanism, future channel_t subclasses should take care
1853 * not to change a channel from CHANNEL_STATE_OPENING to CHANNEL_STATE_OPEN
1854 * until there is positive confirmation that the network is operational.
1855 * In particular, anything UDP-based should not make this transition until a
1856 * packet is received from the other side.
1859 channel_do_open_actions(channel_t
*chan
)
1861 tor_addr_t remote_addr
;
1863 time_t now
= time(NULL
);
1864 int close_origin_circuits
= 0;
1868 started_here
= channel_is_outgoing(chan
);
1871 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
1872 router_set_status(chan
->identity_digest
, 1);
1874 /* only report it to the geoip module if it's a client */
1875 if (channel_is_client(chan
)) {
1876 if (channel_get_addr_if_possible(chan
, &remote_addr
)) {
1877 char *transport_name
= NULL
;
1878 channel_tls_t
*tlschan
= BASE_CHAN_TO_TLS(chan
);
1879 if (chan
->get_transport_name(chan
, &transport_name
) < 0)
1880 transport_name
= NULL
;
1882 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
,
1883 &remote_addr
, transport_name
,
1885 tor_free(transport_name
);
1886 /* Notify the DoS subsystem of a new client. */
1887 if (tlschan
&& tlschan
->conn
) {
1888 dos_new_client_conn(tlschan
->conn
, transport_name
);
1891 /* Otherwise the underlying transport can't tell us this, so skip it */
1895 /* Disable or reduce padding according to user prefs. */
1896 if (chan
->padding_enabled
|| get_options()->ConnectionPadding
== 1) {
1897 if (!get_options()->ConnectionPadding
) {
1898 /* Disable if torrc disabled */
1899 channelpadding_disable_padding_on_channel(chan
);
1900 } else if (hs_service_allow_non_anonymous_connection(get_options()) &&
1901 !networkstatus_get_param(NULL
,
1902 CHANNELPADDING_SOS_PARAM
,
1903 CHANNELPADDING_SOS_DEFAULT
, 0, 1)) {
1904 /* Disable if we're using RSOS and the consensus disabled padding
1906 channelpadding_disable_padding_on_channel(chan
);
1907 } else if (get_options()->ReducedConnectionPadding
) {
1908 /* Padding can be forced and/or reduced by clients, regardless of if
1909 * the channel supports it */
1910 channelpadding_reduce_padding_on_channel(chan
);
1914 circuit_n_chan_done(chan
, 1, close_origin_circuits
);
1918 * Queue an incoming channel on a listener.
1920 * Internal and subclass use only function to queue an incoming channel from
1921 * a listener. A subclass of channel_listener_t should call this when a new
1922 * incoming channel is created.
1925 channel_listener_queue_incoming(channel_listener_t
*listener
,
1926 channel_t
*incoming
)
1928 int need_to_queue
= 0;
1930 tor_assert(listener
);
1931 tor_assert(listener
->state
== CHANNEL_LISTENER_STATE_LISTENING
);
1932 tor_assert(incoming
);
1934 log_debug(LD_CHANNEL
,
1935 "Queueing incoming channel %p (global ID %"PRIu64
") on "
1936 "channel listener %p (global ID %"PRIu64
")",
1937 incoming
, (incoming
->global_identifier
),
1938 listener
, (listener
->global_identifier
));
1940 /* Do we need to queue it, or can we just call the listener right away? */
1941 if (!(listener
->listener
)) need_to_queue
= 1;
1942 if (listener
->incoming_list
&&
1943 (smartlist_len(listener
->incoming_list
) > 0))
1946 /* If we need to queue and have no queue, create one */
1947 if (need_to_queue
&& !(listener
->incoming_list
)) {
1948 listener
->incoming_list
= smartlist_new();
1951 /* Bump the counter and timestamp it */
1952 channel_listener_timestamp_active(listener
);
1953 channel_listener_timestamp_accepted(listener
);
1954 ++(listener
->n_accepted
);
1956 /* If we don't need to queue, process it right away */
1957 if (!need_to_queue
) {
1958 tor_assert(listener
->listener
);
1959 listener
->listener(listener
, incoming
);
1962 * Otherwise, we need to queue; queue and then process the queue if
1966 tor_assert(listener
->incoming_list
);
1967 smartlist_add(listener
->incoming_list
, incoming
);
1968 if (listener
->listener
) channel_listener_process_incoming(listener
);
1973 * Process a cell from the given channel.
1976 channel_process_cell(channel_t
*chan
, cell_t
*cell
)
1979 tor_assert(CHANNEL_IS_CLOSING(chan
) || CHANNEL_IS_MAINT(chan
) ||
1980 CHANNEL_IS_OPEN(chan
));
1983 /* Nothing we can do if we have no registered cell handlers */
1984 if (!chan
->cell_handler
)
1987 /* Timestamp for receiving */
1988 channel_timestamp_recv(chan
);
1989 /* Update received counter. */
1990 ++(chan
->n_cells_recved
);
1991 chan
->n_bytes_recved
+= get_cell_network_size(chan
->wide_circ_ids
);
1993 log_debug(LD_CHANNEL
,
1994 "Processing incoming cell_t %p for channel %p (global ID "
1995 "%"PRIu64
")", cell
, chan
,
1996 (chan
->global_identifier
));
1997 chan
->cell_handler(chan
, cell
);
2000 /** If <b>packed_cell</b> on <b>chan</b> is a destroy cell, then set
2001 * *<b>circid_out</b> to its circuit ID, and return true. Otherwise, return
2003 /* XXXX Move this function. */
2005 packed_cell_is_destroy(channel_t
*chan
,
2006 const packed_cell_t
*packed_cell
,
2007 circid_t
*circid_out
)
2009 if (chan
->wide_circ_ids
) {
2010 if (packed_cell
->body
[4] == CELL_DESTROY
) {
2011 *circid_out
= ntohl(get_uint32(packed_cell
->body
));
2015 if (packed_cell
->body
[2] == CELL_DESTROY
) {
2016 *circid_out
= ntohs(get_uint16(packed_cell
->body
));
2024 * Send destroy cell on a channel.
2026 * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
2027 * onto channel <b>chan</b>. Don't perform range-checking on reason:
2028 * we may want to propagate reasons from other cells.
2031 channel_send_destroy(circid_t circ_id
, channel_t
*chan
, int reason
)
2035 log_warn(LD_BUG
, "Attempted to send a destroy cell for circID 0 "
2036 "on a channel %"PRIu64
" at %p in state %s (%d)",
2037 (chan
->global_identifier
),
2038 chan
, channel_state_to_string(chan
->state
),
2043 /* Check to make sure we can send on this channel first */
2044 if (!CHANNEL_CONDEMNED(chan
) && chan
->cmux
) {
2045 channel_note_destroy_pending(chan
, circ_id
);
2046 circuitmux_append_destroy_cell(chan
, chan
->cmux
, circ_id
, reason
);
2048 "Sending destroy (circID %u) on channel %p "
2049 "(global ID %"PRIu64
")",
2050 (unsigned)circ_id
, chan
,
2051 (chan
->global_identifier
));
2054 "Someone called channel_send_destroy() for circID %u "
2055 "on a channel %"PRIu64
" at %p in state %s (%d)",
2056 (unsigned)circ_id
, (chan
->global_identifier
),
2057 chan
, channel_state_to_string(chan
->state
),
2065 * Dump channel statistics to the log.
2067 * This is called from dumpstats() in main.c and spams the log with
2068 * statistics on channels.
2071 channel_dumpstats(int severity
)
2073 if (all_channels
&& smartlist_len(all_channels
) > 0) {
2074 tor_log(severity
, LD_GENERAL
,
2075 "Dumping statistics about %d channels:",
2076 smartlist_len(all_channels
));
2077 tor_log(severity
, LD_GENERAL
,
2078 "%d are active, and %d are done and waiting for cleanup",
2079 (active_channels
!= NULL
) ?
2080 smartlist_len(active_channels
) : 0,
2081 (finished_channels
!= NULL
) ?
2082 smartlist_len(finished_channels
) : 0);
2084 SMARTLIST_FOREACH(all_channels
, channel_t
*, chan
,
2085 channel_dump_statistics(chan
, severity
));
2087 tor_log(severity
, LD_GENERAL
,
2088 "Done spamming about channels now");
2090 tor_log(severity
, LD_GENERAL
,
2091 "No channels to dump");
2096 * Dump channel listener statistics to the log.
2098 * This is called from dumpstats() in main.c and spams the log with
2099 * statistics on channel listeners.
2102 channel_listener_dumpstats(int severity
)
2104 if (all_listeners
&& smartlist_len(all_listeners
) > 0) {
2105 tor_log(severity
, LD_GENERAL
,
2106 "Dumping statistics about %d channel listeners:",
2107 smartlist_len(all_listeners
));
2108 tor_log(severity
, LD_GENERAL
,
2109 "%d are active and %d are done and waiting for cleanup",
2110 (active_listeners
!= NULL
) ?
2111 smartlist_len(active_listeners
) : 0,
2112 (finished_listeners
!= NULL
) ?
2113 smartlist_len(finished_listeners
) : 0);
2115 SMARTLIST_FOREACH(all_listeners
, channel_listener_t
*, chan_l
,
2116 channel_listener_dump_statistics(chan_l
, severity
));
2118 tor_log(severity
, LD_GENERAL
,
2119 "Done spamming about channel listeners now");
2121 tor_log(severity
, LD_GENERAL
,
2122 "No channel listeners to dump");
2127 * Clean up channels.
2129 * This gets called periodically from run_scheduled_events() in main.c;
2130 * it cleans up after closed channels.
2133 channel_run_cleanup(void)
2135 channel_t
*tmp
= NULL
;
2137 /* Check if we need to do anything */
2138 if (!finished_channels
|| smartlist_len(finished_channels
) == 0) return;
2140 /* Iterate through finished_channels and get rid of them */
2141 SMARTLIST_FOREACH_BEGIN(finished_channels
, channel_t
*, curr
) {
2143 /* Remove it from the list */
2144 SMARTLIST_DEL_CURRENT(finished_channels
, curr
);
2145 /* Also unregister it */
2146 channel_unregister(tmp
);
2147 /* ... and free it */
2149 } SMARTLIST_FOREACH_END(curr
);
2153 * Clean up channel listeners.
2155 * This gets called periodically from run_scheduled_events() in main.c;
2156 * it cleans up after closed channel listeners.
2159 channel_listener_run_cleanup(void)
2161 channel_listener_t
*tmp
= NULL
;
2163 /* Check if we need to do anything */
2164 if (!finished_listeners
|| smartlist_len(finished_listeners
) == 0) return;
2166 /* Iterate through finished_channels and get rid of them */
2167 SMARTLIST_FOREACH_BEGIN(finished_listeners
, channel_listener_t
*, curr
) {
2169 /* Remove it from the list */
2170 SMARTLIST_DEL_CURRENT(finished_listeners
, curr
);
2171 /* Also unregister it */
2172 channel_listener_unregister(tmp
);
2173 /* ... and free it */
2174 channel_listener_free(tmp
);
2175 } SMARTLIST_FOREACH_END(curr
);
2179 * Free a list of channels for channel_free_all().
2182 channel_free_list(smartlist_t
*channels
, int mark_for_close
)
2184 if (!channels
) return;
2186 SMARTLIST_FOREACH_BEGIN(channels
, channel_t
*, curr
) {
2187 /* Deregister and free it */
2189 log_debug(LD_CHANNEL
,
2190 "Cleaning up channel %p (global ID %"PRIu64
") "
2192 curr
, (curr
->global_identifier
),
2193 channel_state_to_string(curr
->state
), curr
->state
);
2194 /* Detach circuits early so they can find the channel */
2196 circuitmux_detach_all_circuits(curr
->cmux
, NULL
);
2198 SMARTLIST_DEL_CURRENT(channels
, curr
);
2199 channel_unregister(curr
);
2200 if (mark_for_close
) {
2201 if (!CHANNEL_CONDEMNED(curr
)) {
2202 channel_mark_for_close(curr
);
2204 channel_force_xfree(curr
);
2205 } else channel_free(curr
);
2206 } SMARTLIST_FOREACH_END(curr
);
2210 * Free a list of channel listeners for channel_free_all().
2213 channel_listener_free_list(smartlist_t
*listeners
, int mark_for_close
)
2215 if (!listeners
) return;
2217 SMARTLIST_FOREACH_BEGIN(listeners
, channel_listener_t
*, curr
) {
2218 /* Deregister and free it */
2220 log_debug(LD_CHANNEL
,
2221 "Cleaning up channel listener %p (global ID %"PRIu64
") "
2223 curr
, (curr
->global_identifier
),
2224 channel_listener_state_to_string(curr
->state
), curr
->state
);
2225 channel_listener_unregister(curr
);
2226 if (mark_for_close
) {
2227 if (!(curr
->state
== CHANNEL_LISTENER_STATE_CLOSING
||
2228 curr
->state
== CHANNEL_LISTENER_STATE_CLOSED
||
2229 curr
->state
== CHANNEL_LISTENER_STATE_ERROR
)) {
2230 channel_listener_mark_for_close(curr
);
2232 channel_listener_force_xfree(curr
);
2233 } else channel_listener_free(curr
);
2234 } SMARTLIST_FOREACH_END(curr
);
2238 * Close all channels and free everything.
2240 * This gets called from tor_free_all() in main.c to clean up on exit.
2241 * It will close all registered channels and free associated storage,
2242 * then free the all_channels, active_channels, listening_channels and
2243 * finished_channels lists and also channel_identity_map.
2246 channel_free_all(void)
2248 log_debug(LD_CHANNEL
,
2249 "Shutting down channels...");
2251 /* First, let's go for finished channels */
2252 if (finished_channels
) {
2253 channel_free_list(finished_channels
, 0);
2254 smartlist_free(finished_channels
);
2255 finished_channels
= NULL
;
2258 /* Now the finished listeners */
2259 if (finished_listeners
) {
2260 channel_listener_free_list(finished_listeners
, 0);
2261 smartlist_free(finished_listeners
);
2262 finished_listeners
= NULL
;
2265 /* Now all active channels */
2266 if (active_channels
) {
2267 channel_free_list(active_channels
, 1);
2268 smartlist_free(active_channels
);
2269 active_channels
= NULL
;
2272 /* Now all active listeners */
2273 if (active_listeners
) {
2274 channel_listener_free_list(active_listeners
, 1);
2275 smartlist_free(active_listeners
);
2276 active_listeners
= NULL
;
2279 /* Now all channels, in case any are left over */
2281 channel_free_list(all_channels
, 1);
2282 smartlist_free(all_channels
);
2283 all_channels
= NULL
;
2286 /* Now all listeners, in case any are left over */
2287 if (all_listeners
) {
2288 channel_listener_free_list(all_listeners
, 1);
2289 smartlist_free(all_listeners
);
2290 all_listeners
= NULL
;
2293 /* Now free channel_identity_map */
2294 log_debug(LD_CHANNEL
,
2295 "Freeing channel_identity_map");
2296 /* Geez, anything still left over just won't die ... let it leak then */
2297 HT_CLEAR(channel_idmap
, &channel_identity_map
);
2299 /* Same with channel_gid_map */
2300 log_debug(LD_CHANNEL
,
2301 "Freeing channel_gid_map");
2302 HT_CLEAR(channel_gid_map
, &channel_gid_map
);
2304 log_debug(LD_CHANNEL
,
2305 "Done cleaning up after channels");
2309 * Connect to a given addr/port/digest.
2311 * This sets up a new outgoing channel; in the future if multiple
2312 * channel_t subclasses are available, this is where the selection policy
2313 * should go. It may also be desirable to fold port into tor_addr_t
2314 * or make a new type including a tor_addr_t and port, so we have a
2315 * single abstract object encapsulating all the protocol details of
2316 * how to contact an OR.
2319 channel_connect(const tor_addr_t
*addr
, uint16_t port
,
2320 const char *id_digest
,
2321 const ed25519_public_key_t
*ed_id
)
2323 return channel_tls_connect(addr
, port
, id_digest
, ed_id
);
2327 * Decide which of two channels to prefer for extending a circuit.
2329 * This function is called while extending a circuit and returns true iff
2330 * a is 'better' than b. The most important criterion here is that a
2331 * canonical channel is always better than a non-canonical one, but the
2332 * number of circuits and the age are used as tie-breakers.
2334 * This is based on the former connection_or_is_better() of connection_or.c
2337 channel_is_better(channel_t
*a
, channel_t
*b
)
2339 int a_is_canonical
, b_is_canonical
;
2344 /* If one channel is bad for new circuits, and the other isn't,
2345 * use the one that is still good. */
2346 if (!channel_is_bad_for_new_circs(a
) && channel_is_bad_for_new_circs(b
))
2348 if (channel_is_bad_for_new_circs(a
) && !channel_is_bad_for_new_circs(b
))
2351 /* Check if one is canonical and the other isn't first */
2352 a_is_canonical
= channel_is_canonical(a
);
2353 b_is_canonical
= channel_is_canonical(b
);
2355 if (a_is_canonical
&& !b_is_canonical
) return 1;
2356 if (!a_is_canonical
&& b_is_canonical
) return 0;
2358 /* Check if we suspect that one of the channels will be preferred
2360 if (a
->is_canonical_to_peer
&& !b
->is_canonical_to_peer
) return 1;
2361 if (!a
->is_canonical_to_peer
&& b
->is_canonical_to_peer
) return 0;
2364 * Okay, if we're here they tied on canonicity. Prefer the older
2365 * connection, so that the adversary can't create a new connection
2366 * and try to switch us over to it (which will leak information
2367 * about long-lived circuits). Additionally, switching connections
2368 * too often makes us more vulnerable to attacks like Torscan and
2369 * passive netflow-based equivalents.
2371 * Connections will still only live for at most a week, due to
2372 * the check in connection_or_group_set_badness() against
2373 * TIME_BEFORE_OR_CONN_IS_TOO_OLD, which marks old connections as
2374 * unusable for new circuits after 1 week. That check sets
2375 * is_bad_for_new_circs, which is checked in channel_get_for_extend().
2377 * We check channel_is_bad_for_new_circs() above here anyway, for safety.
2379 if (channel_when_created(a
) < channel_when_created(b
)) return 1;
2380 else if (channel_when_created(a
) > channel_when_created(b
)) return 0;
2382 if (channel_num_circuits(a
) > channel_num_circuits(b
)) return 1;
2387 * Get a channel to extend a circuit.
2389 * Given the desired relay identity, pick a suitable channel to extend a
2390 * circuit to the target IPv4 or IPv6 address requested by the client. Search
2391 * for an existing channel for the requested endpoint. Make sure the channel
2392 * is usable for new circuits, and matches one of the target addresses.
2394 * Try to return the best channel. But if there is no good channel, set
2395 * *msg_out to a message describing the channel's state and our next action,
2396 * and set *launch_out to a boolean indicated whether the caller should try to
2397 * launch a new channel with channel_connect().
2399 * If `for_origin_circ` is set, mark the channel as interesting for origin
2400 * circuits, and therefore interesting for our bootstrapping reports.
2402 MOCK_IMPL(channel_t
*,
2403 channel_get_for_extend
,(const char *rsa_id_digest
,
2404 const ed25519_public_key_t
*ed_id
,
2405 const tor_addr_t
*target_ipv4_addr
,
2406 const tor_addr_t
*target_ipv6_addr
,
2407 bool for_origin_circ
,
2408 const char **msg_out
,
2411 channel_t
*chan
, *best
= NULL
;
2412 int n_inprogress_goodaddr
= 0, n_old
= 0;
2413 int n_noncanonical
= 0;
2415 tor_assert(msg_out
);
2416 tor_assert(launch_out
);
2418 chan
= channel_find_by_remote_identity(rsa_id_digest
, ed_id
);
2420 /* Walk the list of channels */
2421 for (; chan
; chan
= channel_next_with_rsa_identity(chan
)) {
2422 tor_assert(tor_memeq(chan
->identity_digest
,
2423 rsa_id_digest
, DIGEST_LEN
));
2425 if (CHANNEL_CONDEMNED(chan
))
2428 /* Never return a channel on which the other end appears to be
2430 if (channel_is_client(chan
)) {
2434 /* The Ed25519 key has to match too */
2435 if (!channel_remote_identity_matches(chan
, rsa_id_digest
, ed_id
)) {
2439 const bool matches_target
=
2440 channel_matches_target_addr_for_extend(chan
,
2443 /* Never return a non-open connection. */
2444 if (!CHANNEL_IS_OPEN(chan
)) {
2445 /* If the address matches, don't launch a new connection for this
2447 if (matches_target
) {
2448 ++n_inprogress_goodaddr
;
2449 if (for_origin_circ
) {
2450 /* We were looking for a connection for an origin circuit; this one
2451 * matches, so we'll note that we decided to use it for an origin
2453 channel_mark_as_used_for_origin_circuit(chan
);
2459 /* Never return a connection that shouldn't be used for circs. */
2460 if (channel_is_bad_for_new_circs(chan
)) {
2465 /* Only return canonical connections or connections where the address
2466 * is the address we wanted. */
2467 if (!channel_is_canonical(chan
) && !matches_target
) {
2473 best
= chan
; /* If we have no 'best' so far, this one is good enough. */
2477 if (channel_is_better(chan
, best
))
2482 *msg_out
= "Connection is fine; using it.";
2485 } else if (n_inprogress_goodaddr
) {
2486 *msg_out
= "Connection in progress; waiting.";
2489 } else if (n_old
|| n_noncanonical
) {
2490 *msg_out
= "Connections all too old, or too non-canonical. "
2491 " Launching a new one.";
2495 *msg_out
= "Not connected. Connecting.";
2502 * Describe the transport subclass for a channel.
2504 * Invoke a method to get a string description of the lower-layer
2505 * transport for this channel.
2508 channel_describe_transport(channel_t
*chan
)
2511 tor_assert(chan
->describe_transport
);
2513 return chan
->describe_transport(chan
);
2517 * Describe the transport subclass for a channel listener.
2519 * Invoke a method to get a string description of the lower-layer
2520 * transport for this channel listener.
2523 channel_listener_describe_transport(channel_listener_t
*chan_l
)
2526 tor_assert(chan_l
->describe_transport
);
2528 return chan_l
->describe_transport(chan_l
);
2532 * Dump channel statistics.
2534 * Dump statistics for one channel to the log.
2537 channel_dump_statistics
, (channel_t
*chan
, int severity
))
2539 double avg
, interval
, age
;
2540 time_t now
= time(NULL
);
2541 tor_addr_t remote_addr
;
2542 int have_remote_addr
;
2543 char *remote_addr_str
;
2547 age
= (double)(now
- chan
->timestamp_created
);
2549 tor_log(severity
, LD_GENERAL
,
2550 "Channel %"PRIu64
" (at %p) with transport %s is in state "
2552 (chan
->global_identifier
), chan
,
2553 channel_describe_transport(chan
),
2554 channel_state_to_string(chan
->state
), chan
->state
);
2555 tor_log(severity
, LD_GENERAL
,
2556 " * Channel %"PRIu64
" was created at %"PRIu64
2557 " (%"PRIu64
" seconds ago) "
2558 "and last active at %"PRIu64
" (%"PRIu64
" seconds ago)",
2559 (chan
->global_identifier
),
2560 (uint64_t)(chan
->timestamp_created
),
2561 (uint64_t)(now
- chan
->timestamp_created
),
2562 (uint64_t)(chan
->timestamp_active
),
2563 (uint64_t)(now
- chan
->timestamp_active
));
2565 /* Handle digest. */
2566 if (!tor_digest_is_zero(chan
->identity_digest
)) {
2567 tor_log(severity
, LD_GENERAL
,
2568 " * Channel %"PRIu64
" says it is connected "
2569 "to an OR with digest %s",
2570 (chan
->global_identifier
),
2571 hex_str(chan
->identity_digest
, DIGEST_LEN
));
2573 tor_log(severity
, LD_GENERAL
,
2574 " * Channel %"PRIu64
" does not know the digest"
2575 " of the OR it is connected to",
2576 (chan
->global_identifier
));
2579 /* Handle remote address and descriptions */
2580 have_remote_addr
= channel_get_addr_if_possible(chan
, &remote_addr
);
2581 if (have_remote_addr
) {
2582 char *actual
= tor_strdup(channel_describe_peer(chan
));
2583 remote_addr_str
= tor_addr_to_str_dup(&remote_addr
);
2584 tor_log(severity
, LD_GENERAL
,
2585 " * Channel %"PRIu64
" says its remote address"
2586 " is %s, and gives a canonical description of \"%s\" and an "
2587 "actual description of \"%s\"",
2588 (chan
->global_identifier
),
2589 safe_str(remote_addr_str
),
2590 safe_str(channel_describe_peer(chan
)),
2592 tor_free(remote_addr_str
);
2595 char *actual
= tor_strdup(channel_describe_peer(chan
));
2596 tor_log(severity
, LD_GENERAL
,
2597 " * Channel %"PRIu64
" does not know its remote "
2598 "address, but gives a canonical description of \"%s\" and an "
2599 "actual description of \"%s\"",
2600 (chan
->global_identifier
),
2601 channel_describe_peer(chan
),
2607 tor_log(severity
, LD_GENERAL
,
2608 " * Channel %"PRIu64
" has these marks: %s %s %s %s %s",
2609 (chan
->global_identifier
),
2610 channel_is_bad_for_new_circs(chan
) ?
2611 "bad_for_new_circs" : "!bad_for_new_circs",
2612 channel_is_canonical(chan
) ?
2613 "canonical" : "!canonical",
2614 channel_is_client(chan
) ?
2615 "client" : "!client",
2616 channel_is_local(chan
) ?
2618 channel_is_incoming(chan
) ?
2619 "incoming" : "outgoing");
2621 /* Describe circuits */
2622 tor_log(severity
, LD_GENERAL
,
2623 " * Channel %"PRIu64
" has %d active circuits out of"
2625 (chan
->global_identifier
),
2626 (chan
->cmux
!= NULL
) ?
2627 circuitmux_num_active_circuits(chan
->cmux
) : 0,
2628 (chan
->cmux
!= NULL
) ?
2629 circuitmux_num_circuits(chan
->cmux
) : 0);
2631 /* Describe timestamps */
2632 tor_log(severity
, LD_GENERAL
,
2633 " * Channel %"PRIu64
" was last used by a "
2634 "client at %"PRIu64
" (%"PRIu64
" seconds ago)",
2635 (chan
->global_identifier
),
2636 (uint64_t)(chan
->timestamp_client
),
2637 (uint64_t)(now
- chan
->timestamp_client
));
2638 tor_log(severity
, LD_GENERAL
,
2639 " * Channel %"PRIu64
" last received a cell "
2640 "at %"PRIu64
" (%"PRIu64
" seconds ago)",
2641 (chan
->global_identifier
),
2642 (uint64_t)(chan
->timestamp_recv
),
2643 (uint64_t)(now
- chan
->timestamp_recv
));
2644 tor_log(severity
, LD_GENERAL
,
2645 " * Channel %"PRIu64
" last transmitted a cell "
2646 "at %"PRIu64
" (%"PRIu64
" seconds ago)",
2647 (chan
->global_identifier
),
2648 (uint64_t)(chan
->timestamp_xmit
),
2649 (uint64_t)(now
- chan
->timestamp_xmit
));
2651 /* Describe counters and rates */
2652 tor_log(severity
, LD_GENERAL
,
2653 " * Channel %"PRIu64
" has received "
2654 "%"PRIu64
" bytes in %"PRIu64
" cells and transmitted "
2655 "%"PRIu64
" bytes in %"PRIu64
" cells",
2656 (chan
->global_identifier
),
2657 (chan
->n_bytes_recved
),
2658 (chan
->n_cells_recved
),
2659 (chan
->n_bytes_xmitted
),
2660 (chan
->n_cells_xmitted
));
2661 if (now
> chan
->timestamp_created
&&
2662 chan
->timestamp_created
> 0) {
2663 if (chan
->n_bytes_recved
> 0) {
2664 avg
= (double)(chan
->n_bytes_recved
) / age
;
2665 tor_log(severity
, LD_GENERAL
,
2666 " * Channel %"PRIu64
" has averaged %f "
2667 "bytes received per second",
2668 (chan
->global_identifier
), avg
);
2670 if (chan
->n_cells_recved
> 0) {
2671 avg
= (double)(chan
->n_cells_recved
) / age
;
2673 tor_log(severity
, LD_GENERAL
,
2674 " * Channel %"PRIu64
" has averaged %f "
2675 "cells received per second",
2676 (chan
->global_identifier
), avg
);
2677 } else if (avg
>= 0.0) {
2678 interval
= 1.0 / avg
;
2679 tor_log(severity
, LD_GENERAL
,
2680 " * Channel %"PRIu64
" has averaged %f "
2681 "seconds between received cells",
2682 (chan
->global_identifier
), interval
);
2685 if (chan
->n_bytes_xmitted
> 0) {
2686 avg
= (double)(chan
->n_bytes_xmitted
) / age
;
2687 tor_log(severity
, LD_GENERAL
,
2688 " * Channel %"PRIu64
" has averaged %f "
2689 "bytes transmitted per second",
2690 (chan
->global_identifier
), avg
);
2692 if (chan
->n_cells_xmitted
> 0) {
2693 avg
= (double)(chan
->n_cells_xmitted
) / age
;
2695 tor_log(severity
, LD_GENERAL
,
2696 " * Channel %"PRIu64
" has averaged %f "
2697 "cells transmitted per second",
2698 (chan
->global_identifier
), avg
);
2699 } else if (avg
>= 0.0) {
2700 interval
= 1.0 / avg
;
2701 tor_log(severity
, LD_GENERAL
,
2702 " * Channel %"PRIu64
" has averaged %f "
2703 "seconds between transmitted cells",
2704 (chan
->global_identifier
), interval
);
2709 /* Dump anything the lower layer has to say */
2710 channel_dump_transport_statistics(chan
, severity
);
2714 * Dump channel listener statistics.
2716 * Dump statistics for one channel listener to the log.
2719 channel_listener_dump_statistics(channel_listener_t
*chan_l
, int severity
)
2721 double avg
, interval
, age
;
2722 time_t now
= time(NULL
);
2726 age
= (double)(now
- chan_l
->timestamp_created
);
2728 tor_log(severity
, LD_GENERAL
,
2729 "Channel listener %"PRIu64
" (at %p) with transport %s is in "
2731 (chan_l
->global_identifier
), chan_l
,
2732 channel_listener_describe_transport(chan_l
),
2733 channel_listener_state_to_string(chan_l
->state
), chan_l
->state
);
2734 tor_log(severity
, LD_GENERAL
,
2735 " * Channel listener %"PRIu64
" was created at %"PRIu64
2736 " (%"PRIu64
" seconds ago) "
2737 "and last active at %"PRIu64
" (%"PRIu64
" seconds ago)",
2738 (chan_l
->global_identifier
),
2739 (uint64_t)(chan_l
->timestamp_created
),
2740 (uint64_t)(now
- chan_l
->timestamp_created
),
2741 (uint64_t)(chan_l
->timestamp_active
),
2742 (uint64_t)(now
- chan_l
->timestamp_active
));
2744 tor_log(severity
, LD_GENERAL
,
2745 " * Channel listener %"PRIu64
" last accepted an incoming "
2746 "channel at %"PRIu64
" (%"PRIu64
" seconds ago) "
2747 "and has accepted %"PRIu64
" channels in total",
2748 (chan_l
->global_identifier
),
2749 (uint64_t)(chan_l
->timestamp_accepted
),
2750 (uint64_t)(now
- chan_l
->timestamp_accepted
),
2751 (uint64_t)(chan_l
->n_accepted
));
2754 * If it's sensible to do so, get the rate of incoming channels on this
2757 if (now
> chan_l
->timestamp_created
&&
2758 chan_l
->timestamp_created
> 0 &&
2759 chan_l
->n_accepted
> 0) {
2760 avg
= (double)(chan_l
->n_accepted
) / age
;
2762 tor_log(severity
, LD_GENERAL
,
2763 " * Channel listener %"PRIu64
" has averaged %f incoming "
2764 "channels per second",
2765 (chan_l
->global_identifier
), avg
);
2766 } else if (avg
>= 0.0) {
2767 interval
= 1.0 / avg
;
2768 tor_log(severity
, LD_GENERAL
,
2769 " * Channel listener %"PRIu64
" has averaged %f seconds "
2770 "between incoming channels",
2771 (chan_l
->global_identifier
), interval
);
2775 /* Dump anything the lower layer has to say */
2776 channel_listener_dump_transport_statistics(chan_l
, severity
);
2780 * Invoke transport-specific stats dump for channel.
2782 * If there is a lower-layer statistics dump method, invoke it.
2785 channel_dump_transport_statistics(channel_t
*chan
, int severity
)
2789 if (chan
->dumpstats
) chan
->dumpstats(chan
, severity
);
2793 * Invoke transport-specific stats dump for channel listener.
2795 * If there is a lower-layer statistics dump method, invoke it.
2798 channel_listener_dump_transport_statistics(channel_listener_t
*chan_l
,
2803 if (chan_l
->dumpstats
) chan_l
->dumpstats(chan_l
, severity
);
2807 * Return text description of the remote endpoint canonical address.
2809 * This function returns a human-readable string for logging; nothing
2810 * should parse it or rely on a particular format.
2812 * Subsequent calls to this function may invalidate its return value.
2814 MOCK_IMPL(const char *,
2815 channel_describe_peer
,(channel_t
*chan
))
2818 tor_assert(chan
->describe_peer
);
2820 return chan
->describe_peer(chan
);
2824 * Get the remote address for this channel, if possible.
2826 * Write the remote address out to a tor_addr_t if the underlying transport
2827 * supports this operation, and return 1. Return 0 if the underlying transport
2828 * doesn't let us do this.
2830 * Always returns the "real" address of the peer -- the one we're connected to
2834 channel_get_addr_if_possible
,(const channel_t
*chan
,
2835 tor_addr_t
*addr_out
))
2838 tor_assert(addr_out
);
2839 tor_assert(chan
->get_remote_addr
);
2841 return chan
->get_remote_addr(chan
, addr_out
);
2845 * Return true iff the channel has any cells on the connection outbuf waiting
2846 * to be sent onto the network.
2849 channel_has_queued_writes(channel_t
*chan
)
2852 tor_assert(chan
->has_queued_writes
);
2854 /* Check with the lower layer */
2855 return chan
->has_queued_writes(chan
);
2859 * Check the is_bad_for_new_circs flag.
2861 * This function returns the is_bad_for_new_circs flag of the specified
2865 channel_is_bad_for_new_circs(channel_t
*chan
)
2869 return chan
->is_bad_for_new_circs
;
2873 * Mark a channel as bad for new circuits.
2875 * Set the is_bad_for_new_circs_flag on chan.
2878 channel_mark_bad_for_new_circs(channel_t
*chan
)
2882 chan
->is_bad_for_new_circs
= 1;
2886 * Get the client flag.
2888 * This returns the client flag of a channel, which will be set if
2889 * command_process_create_cell() in command.c thinks this is a connection
2893 channel_is_client(const channel_t
*chan
)
2897 return chan
->is_client
;
2901 * Set the client flag.
2903 * Mark a channel as being from a client.
2906 channel_mark_client(channel_t
*chan
)
2910 chan
->is_client
= 1;
2914 * Clear the client flag.
2916 * Mark a channel as being _not_ from a client.
2919 channel_clear_client(channel_t
*chan
)
2923 chan
->is_client
= 0;
2927 * Get the canonical flag for a channel.
2929 * This returns the is_canonical for a channel; this flag is determined by
2930 * the lower layer and can't be set in a transport-independent way.
2933 channel_is_canonical(channel_t
*chan
)
2936 tor_assert(chan
->is_canonical
);
2938 return chan
->is_canonical(chan
);
2942 * Test incoming flag.
2944 * This function gets the incoming flag; this is set when a listener spawns
2945 * a channel. If this returns true the channel was remotely initiated.
2948 channel_is_incoming(channel_t
*chan
)
2952 return chan
->is_incoming
;
2956 * Set the incoming flag.
2958 * This function is called when a channel arrives on a listening channel
2959 * to mark it as incoming.
2962 channel_mark_incoming(channel_t
*chan
)
2966 chan
->is_incoming
= 1;
2972 * This function gets the local flag; the lower layer should set this when
2973 * setting up the channel if is_local_addr() is true for all of the
2974 * destinations it will communicate with on behalf of this channel. It's
2975 * used to decide whether to declare the network reachable when seeing incoming
2976 * traffic on the channel.
2979 channel_is_local(channel_t
*chan
)
2983 return chan
->is_local
;
2987 * Set the local flag.
2989 * This internal-only function should be called by the lower layer if the
2990 * channel is to a local address. See channel_is_local() above or the
2991 * description of the is_local bit in channel.h.
2994 channel_mark_local(channel_t
*chan
)
3002 * Mark a channel as remote.
3004 * This internal-only function should be called by the lower layer if the
3005 * channel is not to a local address but has previously been marked local.
3006 * See channel_is_local() above or the description of the is_local bit in
3010 channel_mark_remote(channel_t
*chan
)
3018 * Test outgoing flag.
3020 * This function gets the outgoing flag; this is the inverse of the incoming
3021 * bit set when a listener spawns a channel. If this returns true the channel
3022 * was locally initiated.
3025 channel_is_outgoing(channel_t
*chan
)
3029 return !(chan
->is_incoming
);
3033 * Mark a channel as outgoing.
3035 * This function clears the incoming flag and thus marks a channel as
3039 channel_mark_outgoing(channel_t
*chan
)
3043 chan
->is_incoming
= 0;
3046 /************************
3047 * Flow control queries *
3048 ***********************/
3051 * Estimate the number of writeable cells.
3053 * Ask the lower layer for an estimate of how many cells it can accept.
3056 channel_num_cells_writeable(channel_t
*chan
)
3061 tor_assert(chan
->num_cells_writeable
);
3063 if (chan
->state
== CHANNEL_STATE_OPEN
) {
3064 /* Query lower layer */
3065 result
= chan
->num_cells_writeable(chan
);
3066 if (result
< 0) result
= 0;
3068 /* No cells are writeable in any other state */
3075 /*********************
3076 * Timestamp updates *
3077 ********************/
3080 * Update the created timestamp for a channel.
3082 * This updates the channel's created timestamp and should only be called
3083 * from channel_init().
3086 channel_timestamp_created(channel_t
*chan
)
3088 time_t now
= time(NULL
);
3092 chan
->timestamp_created
= now
;
3096 * Update the created timestamp for a channel listener.
3098 * This updates the channel listener's created timestamp and should only be
3099 * called from channel_init_listener().
3102 channel_listener_timestamp_created(channel_listener_t
*chan_l
)
3104 time_t now
= time(NULL
);
3108 chan_l
->timestamp_created
= now
;
3112 * Update the last active timestamp for a channel.
3114 * This function updates the channel's last active timestamp; it should be
3115 * called by the lower layer whenever there is activity on the channel which
3116 * does not lead to a cell being transmitted or received; the active timestamp
3117 * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
3118 * but it should be updated for things like the v3 handshake and stuff that
3119 * produce activity only visible to the lower layer.
3122 channel_timestamp_active(channel_t
*chan
)
3124 time_t now
= time(NULL
);
3127 monotime_coarse_get(&chan
->timestamp_xfer
);
3129 chan
->timestamp_active
= now
;
3131 /* Clear any potential netflow padding timer. We're active */
3132 monotime_coarse_zero(&chan
->next_padding_time
);
3136 * Update the last active timestamp for a channel listener.
3139 channel_listener_timestamp_active(channel_listener_t
*chan_l
)
3141 time_t now
= time(NULL
);
3145 chan_l
->timestamp_active
= now
;
3149 * Update the last accepted timestamp.
3151 * This function updates the channel listener's last accepted timestamp; it
3152 * should be called whenever a new incoming channel is accepted on a
3156 channel_listener_timestamp_accepted(channel_listener_t
*chan_l
)
3158 time_t now
= time(NULL
);
3162 chan_l
->timestamp_active
= now
;
3163 chan_l
->timestamp_accepted
= now
;
3167 * Update client timestamp.
3169 * This function is called by relay.c to timestamp a channel that appears to
3170 * be used as a client.
3173 channel_timestamp_client(channel_t
*chan
)
3175 time_t now
= time(NULL
);
3179 chan
->timestamp_client
= now
;
3183 * Update the recv timestamp.
3185 * This is called whenever we get an incoming cell from the lower layer.
3186 * This also updates the active timestamp.
3189 channel_timestamp_recv(channel_t
*chan
)
3191 time_t now
= time(NULL
);
3193 monotime_coarse_get(&chan
->timestamp_xfer
);
3195 chan
->timestamp_active
= now
;
3196 chan
->timestamp_recv
= now
;
3198 /* Clear any potential netflow padding timer. We're active */
3199 monotime_coarse_zero(&chan
->next_padding_time
);
3203 * Update the xmit timestamp.
3205 * This is called whenever we pass an outgoing cell to the lower layer. This
3206 * also updates the active timestamp.
3209 channel_timestamp_xmit(channel_t
*chan
)
3211 time_t now
= time(NULL
);
3214 monotime_coarse_get(&chan
->timestamp_xfer
);
3216 chan
->timestamp_active
= now
;
3217 chan
->timestamp_xmit
= now
;
3219 /* Clear any potential netflow padding timer. We're active */
3220 monotime_coarse_zero(&chan
->next_padding_time
);
3223 /***************************************************************
3224 * Timestamp queries - see above for definitions of timestamps *
3225 **************************************************************/
3228 * Query created timestamp for a channel.
3231 channel_when_created(channel_t
*chan
)
3235 return chan
->timestamp_created
;
3239 * Query client timestamp.
3242 channel_when_last_client(channel_t
*chan
)
3246 return chan
->timestamp_client
;
3250 * Query xmit timestamp.
3253 channel_when_last_xmit(channel_t
*chan
)
3257 return chan
->timestamp_xmit
;
3261 * Check if a channel matches an extend_info_t.
3263 * This function calls the lower layer and asks if this channel matches a
3264 * given extend_info_t.
3266 * NOTE that this function only checks for an address/port match, and should
3267 * be used only when no identity is available.
3270 channel_matches_extend_info(channel_t
*chan
, extend_info_t
*extend_info
)
3273 tor_assert(chan
->matches_extend_info
);
3274 tor_assert(extend_info
);
3276 return chan
->matches_extend_info(chan
, extend_info
);
3280 * Check if a channel matches the given target IPv4 or IPv6 addresses.
3281 * If either address matches, return true. If neither address matches,
3284 * Both addresses can't be NULL.
3286 * This function calls into the lower layer and asks if this channel thinks
3287 * it matches the target addresses for circuit extension purposes.
3290 channel_matches_target_addr_for_extend(channel_t
*chan
,
3291 const tor_addr_t
*target_ipv4_addr
,
3292 const tor_addr_t
*target_ipv6_addr
)
3295 tor_assert(chan
->matches_target
);
3297 IF_BUG_ONCE(!target_ipv4_addr
&& !target_ipv6_addr
)
3300 if (target_ipv4_addr
&& chan
->matches_target(chan
, target_ipv4_addr
))
3303 if (target_ipv6_addr
&& chan
->matches_target(chan
, target_ipv6_addr
))
3310 * Return the total number of circuits used by a channel.
3312 * @param chan Channel to query
3313 * @return Number of circuits using this as n_chan or p_chan
3316 channel_num_circuits(channel_t
*chan
)
3320 return chan
->num_n_circuits
+
3321 chan
->num_p_circuits
;
3325 * Set up circuit ID generation.
3327 * This is called when setting up a channel and replaces the old
3328 * connection_or_set_circid_type().
3331 channel_set_circid_type
,(channel_t
*chan
,
3332 crypto_pk_t
*identity_rcvd
,
3333 int consider_identity
))
3336 crypto_pk_t
*our_identity
;
3340 started_here
= channel_is_outgoing(chan
);
3342 if (! consider_identity
) {
3344 chan
->circ_id_type
= CIRC_ID_TYPE_HIGHER
;
3346 chan
->circ_id_type
= CIRC_ID_TYPE_LOWER
;
3350 our_identity
= started_here
?
3351 get_tlsclient_identity_key() : get_server_identity_key();
3353 if (identity_rcvd
) {
3354 if (crypto_pk_cmp_keys(our_identity
, identity_rcvd
) < 0) {
3355 chan
->circ_id_type
= CIRC_ID_TYPE_LOWER
;
3357 chan
->circ_id_type
= CIRC_ID_TYPE_HIGHER
;
3360 chan
->circ_id_type
= CIRC_ID_TYPE_NEITHER
;
3365 channel_sort_by_ed25519_identity(const void **a_
, const void **b_
)
3367 const channel_t
*a
= *a_
,
3369 return fast_memcmp(&a
->ed25519_identity
.pubkey
,
3370 &b
->ed25519_identity
.pubkey
,
3371 sizeof(a
->ed25519_identity
.pubkey
));
3374 /** Helper for channel_update_bad_for_new_circs(): Perform the
3375 * channel_update_bad_for_new_circs operation on all channels in <b>lst</b>,
3376 * all of which MUST have the same RSA ID. (They MAY have different
3379 channel_rsa_id_group_set_badness(struct channel_list_t
*lst
, int force
)
3381 /*XXXX This function should really be about channels. 15056 */
3382 channel_t
*chan
= TOR_LIST_FIRST(lst
);
3387 /* if there is only one channel, don't bother looping */
3388 if (PREDICT_LIKELY(!TOR_LIST_NEXT(chan
, next_with_same_id
))) {
3389 connection_or_single_set_badness_(
3390 time(NULL
), BASE_CHAN_TO_TLS(chan
)->conn
, force
);
3394 smartlist_t
*channels
= smartlist_new();
3396 TOR_LIST_FOREACH(chan
, lst
, next_with_same_id
) {
3397 if (BASE_CHAN_TO_TLS(chan
)->conn
) {
3398 smartlist_add(channels
, chan
);
3402 smartlist_sort(channels
, channel_sort_by_ed25519_identity
);
3404 const ed25519_public_key_t
*common_ed25519_identity
= NULL
;
3405 /* it would be more efficient to do a slice, but this case is rare */
3406 smartlist_t
*or_conns
= smartlist_new();
3407 SMARTLIST_FOREACH_BEGIN(channels
, channel_t
*, channel
) {
3408 tor_assert(channel
); // Suppresses some compiler warnings.
3410 if (!common_ed25519_identity
)
3411 common_ed25519_identity
= &channel
->ed25519_identity
;
3413 if (! ed25519_pubkey_eq(&channel
->ed25519_identity
,
3414 common_ed25519_identity
)) {
3415 connection_or_group_set_badness_(or_conns
, force
);
3416 smartlist_clear(or_conns
);
3417 common_ed25519_identity
= &channel
->ed25519_identity
;
3420 smartlist_add(or_conns
, BASE_CHAN_TO_TLS(channel
)->conn
);
3421 } SMARTLIST_FOREACH_END(channel
);
3423 connection_or_group_set_badness_(or_conns
, force
);
3425 /* XXXX 15056 we may want to do something special with connections that have
3426 * no set Ed25519 identity! */
3428 smartlist_free(or_conns
);
3429 smartlist_free(channels
);
3432 /** Go through all the channels (or if <b>digest</b> is non-NULL, just
3433 * the OR connections with that digest), and set the is_bad_for_new_circs
3434 * flag based on the rules in connection_or_group_set_badness() (or just
3435 * always set it if <b>force</b> is true).
3438 channel_update_bad_for_new_circs(const char *digest
, int force
)
3441 channel_idmap_entry_t
*ent
;
3442 channel_idmap_entry_t search
;
3443 memset(&search
, 0, sizeof(search
));
3444 memcpy(search
.digest
, digest
, DIGEST_LEN
);
3445 ent
= HT_FIND(channel_idmap
, &channel_identity_map
, &search
);
3447 channel_rsa_id_group_set_badness(&ent
->channel_list
, force
);
3452 /* no digest; just look at everything. */
3453 channel_idmap_entry_t
**iter
;
3454 HT_FOREACH(iter
, channel_idmap
, &channel_identity_map
) {
3455 channel_rsa_id_group_set_badness(&(*iter
)->channel_list
, force
);