minor updates on upcoming changelog
[tor.git] / src / or / channel.c
blob0b5a7fde9063d92821a46e3e34f70b53ee66fb6a
1 /* * Copyright (c) 2012-2017, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 /**
5 * \file channel.c
7 * \brief OR/OP-to-OR channel abstraction layer. A channel's job is to
8 * transfer cells from Tor instance to Tor instance.
9 * Currently, there is only one implementation of the channel abstraction: in
10 * channeltls.c.
12 * Channels are a higher-level abstraction than or_connection_t: In general,
13 * any means that two Tor relays use to exchange cells, or any means that a
14 * relay and a client use to exchange cells, is a channel.
16 * Channels differ from pluggable transports in that they do not wrap an
17 * underlying protocol over which cells are transmitted: they <em>are</em> the
18 * underlying protocol.
20 * This module defines the generic parts of the channel_t interface, and
21 * provides the machinery necessary for specialized implementations to be
22 * created. At present, there is one specialized implementation in
23 * channeltls.c, which uses connection_or.c to send cells over a TLS
24 * connection.
26 * Every channel implementation is responsible for being able to transmit
27 * cells that are added to it with channel_write_cell() and related functions,
28 * and to receive incoming cells with the channel_queue_cell() and related
29 * functions. See the channel_t documentation for more information.
31 * When new cells arrive on a channel, they are passed to cell handler
32 * functions, which can be set by channel_set_cell_handlers()
33 * functions. (Tor's cell handlers are in command.c.)
35 * Tor flushes cells to channels from relay.c in
36 * channel_flush_from_first_active_circuit().
37 **/
40 * Define this so channel.h gives us things only channel_t subclasses
41 * should touch.
44 #define TOR_CHANNEL_INTERNAL_
46 /* This one's for stuff only channel.c and the test suite should see */
47 #define CHANNEL_PRIVATE_
49 #include "or.h"
50 #include "channel.h"
51 #include "channeltls.h"
52 #include "channelpadding.h"
53 #include "circuitbuild.h"
54 #include "circuitlist.h"
55 #include "circuitstats.h"
56 #include "config.h"
57 #include "connection_or.h" /* For var_cell_free() */
58 #include "circuitmux.h"
59 #include "entrynodes.h"
60 #include "geoip.h"
61 #include "nodelist.h"
62 #include "relay.h"
63 #include "rephist.h"
64 #include "router.h"
65 #include "routerlist.h"
66 #include "scheduler.h"
67 #include "compat_time.h"
68 #include "networkstatus.h"
69 #include "rendservice.h"
71 /* Global lists of channels */
73 /* All channel_t instances */
74 static smartlist_t *all_channels = NULL;
76 /* All channel_t instances not in ERROR or CLOSED states */
77 static smartlist_t *active_channels = NULL;
79 /* All channel_t instances in ERROR or CLOSED states */
80 static smartlist_t *finished_channels = NULL;
82 /* All channel_listener_t instances */
83 static smartlist_t *all_listeners = NULL;
85 /* All channel_listener_t instances in LISTENING state */
86 static smartlist_t *active_listeners = NULL;
88 /* All channel_listener_t instances in LISTENING state */
89 static smartlist_t *finished_listeners = NULL;
91 /** Map from channel->global_identifier to channel. Contains the same
92 * elements as all_channels. */
93 static HT_HEAD(channel_gid_map, channel_s) channel_gid_map = HT_INITIALIZER();
95 static unsigned
96 channel_id_hash(const channel_t *chan)
98 return (unsigned) chan->global_identifier;
100 static int
101 channel_id_eq(const channel_t *a, const channel_t *b)
103 return a->global_identifier == b->global_identifier;
105 HT_PROTOTYPE(channel_gid_map, channel_s, gidmap_node,
106 channel_id_hash, channel_id_eq)
107 HT_GENERATE2(channel_gid_map, channel_s, gidmap_node,
108 channel_id_hash, channel_id_eq,
109 0.6, tor_reallocarray_, tor_free_)
111 HANDLE_IMPL(channel, channel_s,)
113 /* Counter for ID numbers */
114 static uint64_t n_channels_allocated = 0;
116 * Channel global byte/cell counters, for statistics and for scheduler high
117 * /low-water marks.
121 * Total number of cells ever given to any channel with the
122 * channel_write_*_cell() functions.
125 static uint64_t n_channel_cells_queued = 0;
128 * Total number of cells ever passed to a channel lower layer with the
129 * write_*_cell() methods.
132 static uint64_t n_channel_cells_passed_to_lower_layer = 0;
135 * Current number of cells in all channel queues; should be
136 * n_channel_cells_queued - n_channel_cells_passed_to_lower_layer.
139 static uint64_t n_channel_cells_in_queues = 0;
142 * Total number of bytes for all cells ever queued to a channel and
143 * counted in n_channel_cells_queued.
146 static uint64_t n_channel_bytes_queued = 0;
149 * Total number of bytes for all cells ever passed to a channel lower layer
150 * and counted in n_channel_cells_passed_to_lower_layer.
153 static uint64_t n_channel_bytes_passed_to_lower_layer = 0;
156 * Current number of bytes in all channel queues; should be
157 * n_channel_bytes_queued - n_channel_bytes_passed_to_lower_layer.
160 static uint64_t n_channel_bytes_in_queues = 0;
163 * Current total estimated queue size *including lower layer queues and
164 * transmit overhead*
167 STATIC uint64_t estimated_total_queue_size = 0;
169 /* Digest->channel map
171 * Similar to the one used in connection_or.c, this maps from the identity
172 * digest of a remote endpoint to a channel_t to that endpoint. Channels
173 * should be placed here when registered and removed when they close or error.
174 * If more than one channel exists, follow the next_with_same_id pointer
175 * as a linked list.
177 static HT_HEAD(channel_idmap, channel_idmap_entry_s) channel_identity_map =
178 HT_INITIALIZER();
180 typedef struct channel_idmap_entry_s {
181 HT_ENTRY(channel_idmap_entry_s) node;
182 uint8_t digest[DIGEST_LEN];
183 TOR_LIST_HEAD(channel_list_s, channel_s) channel_list;
184 } channel_idmap_entry_t;
186 static inline unsigned
187 channel_idmap_hash(const channel_idmap_entry_t *ent)
189 return (unsigned) siphash24g(ent->digest, DIGEST_LEN);
192 static inline int
193 channel_idmap_eq(const channel_idmap_entry_t *a,
194 const channel_idmap_entry_t *b)
196 return tor_memeq(a->digest, b->digest, DIGEST_LEN);
199 HT_PROTOTYPE(channel_idmap, channel_idmap_entry_s, node, channel_idmap_hash,
200 channel_idmap_eq)
201 HT_GENERATE2(channel_idmap, channel_idmap_entry_s, node, channel_idmap_hash,
202 channel_idmap_eq, 0.5, tor_reallocarray_, tor_free_)
204 static cell_queue_entry_t * cell_queue_entry_dup(cell_queue_entry_t *q);
205 #if 0
206 static int cell_queue_entry_is_padding(cell_queue_entry_t *q);
207 #endif
208 static cell_queue_entry_t *
209 cell_queue_entry_new_fixed(cell_t *cell);
210 static cell_queue_entry_t *
211 cell_queue_entry_new_var(var_cell_t *var_cell);
212 static int is_destroy_cell(channel_t *chan,
213 const cell_queue_entry_t *q, circid_t *circid_out);
215 static void channel_assert_counter_consistency(void);
217 /* Functions to maintain the digest map */
218 static void channel_add_to_digest_map(channel_t *chan);
219 static void channel_remove_from_digest_map(channel_t *chan);
222 * Flush cells from just the outgoing queue without trying to get them
223 * from circuits; used internall by channel_flush_some_cells().
225 static ssize_t
226 channel_flush_some_cells_from_outgoing_queue(channel_t *chan,
227 ssize_t num_cells);
228 static void channel_force_free(channel_t *chan);
229 static void
230 channel_free_list(smartlist_t *channels, int mark_for_close);
231 static void
232 channel_listener_free_list(smartlist_t *channels, int mark_for_close);
233 static void channel_listener_force_free(channel_listener_t *chan_l);
234 static size_t channel_get_cell_queue_entry_size(channel_t *chan,
235 cell_queue_entry_t *q);
236 static void
237 channel_write_cell_queue_entry(channel_t *chan, cell_queue_entry_t *q);
239 /***********************************
240 * Channel state utility functions *
241 **********************************/
244 * Indicate whether a given channel state is valid
248 channel_state_is_valid(channel_state_t state)
250 int is_valid;
252 switch (state) {
253 case CHANNEL_STATE_CLOSED:
254 case CHANNEL_STATE_CLOSING:
255 case CHANNEL_STATE_ERROR:
256 case CHANNEL_STATE_MAINT:
257 case CHANNEL_STATE_OPENING:
258 case CHANNEL_STATE_OPEN:
259 is_valid = 1;
260 break;
261 case CHANNEL_STATE_LAST:
262 default:
263 is_valid = 0;
266 return is_valid;
270 * Indicate whether a given channel listener state is valid
274 channel_listener_state_is_valid(channel_listener_state_t state)
276 int is_valid;
278 switch (state) {
279 case CHANNEL_LISTENER_STATE_CLOSED:
280 case CHANNEL_LISTENER_STATE_LISTENING:
281 case CHANNEL_LISTENER_STATE_CLOSING:
282 case CHANNEL_LISTENER_STATE_ERROR:
283 is_valid = 1;
284 break;
285 case CHANNEL_LISTENER_STATE_LAST:
286 default:
287 is_valid = 0;
290 return is_valid;
294 * Indicate whether a channel state transition is valid
296 * This function takes two channel states and indicates whether a
297 * transition between them is permitted (see the state definitions and
298 * transition table in or.h at the channel_state_t typedef).
302 channel_state_can_transition(channel_state_t from, channel_state_t to)
304 int is_valid;
306 switch (from) {
307 case CHANNEL_STATE_CLOSED:
308 is_valid = (to == CHANNEL_STATE_OPENING);
309 break;
310 case CHANNEL_STATE_CLOSING:
311 is_valid = (to == CHANNEL_STATE_CLOSED ||
312 to == CHANNEL_STATE_ERROR);
313 break;
314 case CHANNEL_STATE_ERROR:
315 is_valid = 0;
316 break;
317 case CHANNEL_STATE_MAINT:
318 is_valid = (to == CHANNEL_STATE_CLOSING ||
319 to == CHANNEL_STATE_ERROR ||
320 to == CHANNEL_STATE_OPEN);
321 break;
322 case CHANNEL_STATE_OPENING:
323 is_valid = (to == CHANNEL_STATE_CLOSING ||
324 to == CHANNEL_STATE_ERROR ||
325 to == CHANNEL_STATE_OPEN);
326 break;
327 case CHANNEL_STATE_OPEN:
328 is_valid = (to == CHANNEL_STATE_CLOSING ||
329 to == CHANNEL_STATE_ERROR ||
330 to == CHANNEL_STATE_MAINT);
331 break;
332 case CHANNEL_STATE_LAST:
333 default:
334 is_valid = 0;
337 return is_valid;
341 * Indicate whether a channel listener state transition is valid
343 * This function takes two channel listener states and indicates whether a
344 * transition between them is permitted (see the state definitions and
345 * transition table in or.h at the channel_listener_state_t typedef).
349 channel_listener_state_can_transition(channel_listener_state_t from,
350 channel_listener_state_t to)
352 int is_valid;
354 switch (from) {
355 case CHANNEL_LISTENER_STATE_CLOSED:
356 is_valid = (to == CHANNEL_LISTENER_STATE_LISTENING);
357 break;
358 case CHANNEL_LISTENER_STATE_CLOSING:
359 is_valid = (to == CHANNEL_LISTENER_STATE_CLOSED ||
360 to == CHANNEL_LISTENER_STATE_ERROR);
361 break;
362 case CHANNEL_LISTENER_STATE_ERROR:
363 is_valid = 0;
364 break;
365 case CHANNEL_LISTENER_STATE_LISTENING:
366 is_valid = (to == CHANNEL_LISTENER_STATE_CLOSING ||
367 to == CHANNEL_LISTENER_STATE_ERROR);
368 break;
369 case CHANNEL_LISTENER_STATE_LAST:
370 default:
371 is_valid = 0;
374 return is_valid;
378 * Return a human-readable description for a channel state
381 const char *
382 channel_state_to_string(channel_state_t state)
384 const char *descr;
386 switch (state) {
387 case CHANNEL_STATE_CLOSED:
388 descr = "closed";
389 break;
390 case CHANNEL_STATE_CLOSING:
391 descr = "closing";
392 break;
393 case CHANNEL_STATE_ERROR:
394 descr = "channel error";
395 break;
396 case CHANNEL_STATE_MAINT:
397 descr = "temporarily suspended for maintenance";
398 break;
399 case CHANNEL_STATE_OPENING:
400 descr = "opening";
401 break;
402 case CHANNEL_STATE_OPEN:
403 descr = "open";
404 break;
405 case CHANNEL_STATE_LAST:
406 default:
407 descr = "unknown or invalid channel state";
410 return descr;
414 * Return a human-readable description for a channel listenier state
417 const char *
418 channel_listener_state_to_string(channel_listener_state_t state)
420 const char *descr;
422 switch (state) {
423 case CHANNEL_LISTENER_STATE_CLOSED:
424 descr = "closed";
425 break;
426 case CHANNEL_LISTENER_STATE_CLOSING:
427 descr = "closing";
428 break;
429 case CHANNEL_LISTENER_STATE_ERROR:
430 descr = "channel listener error";
431 break;
432 case CHANNEL_LISTENER_STATE_LISTENING:
433 descr = "listening";
434 break;
435 case CHANNEL_LISTENER_STATE_LAST:
436 default:
437 descr = "unknown or invalid channel listener state";
440 return descr;
443 /***************************************
444 * Channel registration/unregistration *
445 ***************************************/
448 * Register a channel
450 * This function registers a newly created channel in the global lists/maps
451 * of active channels.
454 void
455 channel_register(channel_t *chan)
457 tor_assert(chan);
458 tor_assert(chan->global_identifier);
460 /* No-op if already registered */
461 if (chan->registered) return;
463 log_debug(LD_CHANNEL,
464 "Registering channel %p (ID " U64_FORMAT ") "
465 "in state %s (%d) with digest %s",
466 chan, U64_PRINTF_ARG(chan->global_identifier),
467 channel_state_to_string(chan->state), chan->state,
468 hex_str(chan->identity_digest, DIGEST_LEN));
470 /* Make sure we have all_channels, then add it */
471 if (!all_channels) all_channels = smartlist_new();
472 smartlist_add(all_channels, chan);
473 channel_t *oldval = HT_REPLACE(channel_gid_map, &channel_gid_map, chan);
474 tor_assert(! oldval);
476 /* Is it finished? */
477 if (CHANNEL_FINISHED(chan)) {
478 /* Put it in the finished list, creating it if necessary */
479 if (!finished_channels) finished_channels = smartlist_new();
480 smartlist_add(finished_channels, chan);
481 } else {
482 /* Put it in the active list, creating it if necessary */
483 if (!active_channels) active_channels = smartlist_new();
484 smartlist_add(active_channels, chan);
486 if (!CHANNEL_IS_CLOSING(chan)) {
487 /* It should have a digest set */
488 if (!tor_digest_is_zero(chan->identity_digest)) {
489 /* Yeah, we're good, add it to the map */
490 channel_add_to_digest_map(chan);
491 } else {
492 log_info(LD_CHANNEL,
493 "Channel %p (global ID " U64_FORMAT ") "
494 "in state %s (%d) registered with no identity digest",
495 chan, U64_PRINTF_ARG(chan->global_identifier),
496 channel_state_to_string(chan->state), chan->state);
501 /* Mark it as registered */
502 chan->registered = 1;
506 * Unregister a channel
508 * This function removes a channel from the global lists and maps and is used
509 * when freeing a closed/errored channel.
512 void
513 channel_unregister(channel_t *chan)
515 tor_assert(chan);
517 /* No-op if not registered */
518 if (!(chan->registered)) return;
520 /* Is it finished? */
521 if (CHANNEL_FINISHED(chan)) {
522 /* Get it out of the finished list */
523 if (finished_channels) smartlist_remove(finished_channels, chan);
524 } else {
525 /* Get it out of the active list */
526 if (active_channels) smartlist_remove(active_channels, chan);
529 /* Get it out of all_channels */
530 if (all_channels) smartlist_remove(all_channels, chan);
531 channel_t *oldval = HT_REMOVE(channel_gid_map, &channel_gid_map, chan);
532 tor_assert(oldval == NULL || oldval == chan);
534 /* Mark it as unregistered */
535 chan->registered = 0;
537 /* Should it be in the digest map? */
538 if (!tor_digest_is_zero(chan->identity_digest) &&
539 !(CHANNEL_CONDEMNED(chan))) {
540 /* Remove it */
541 channel_remove_from_digest_map(chan);
546 * Register a channel listener
548 * This function registers a newly created channel listner in the global
549 * lists/maps of active channel listeners.
552 void
553 channel_listener_register(channel_listener_t *chan_l)
555 tor_assert(chan_l);
557 /* No-op if already registered */
558 if (chan_l->registered) return;
560 log_debug(LD_CHANNEL,
561 "Registering channel listener %p (ID " U64_FORMAT ") "
562 "in state %s (%d)",
563 chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
564 channel_listener_state_to_string(chan_l->state),
565 chan_l->state);
567 /* Make sure we have all_listeners, then add it */
568 if (!all_listeners) all_listeners = smartlist_new();
569 smartlist_add(all_listeners, chan_l);
571 /* Is it finished? */
572 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
573 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
574 /* Put it in the finished list, creating it if necessary */
575 if (!finished_listeners) finished_listeners = smartlist_new();
576 smartlist_add(finished_listeners, chan_l);
577 } else {
578 /* Put it in the active list, creating it if necessary */
579 if (!active_listeners) active_listeners = smartlist_new();
580 smartlist_add(active_listeners, chan_l);
583 /* Mark it as registered */
584 chan_l->registered = 1;
588 * Unregister a channel listener
590 * This function removes a channel listener from the global lists and maps
591 * and is used when freeing a closed/errored channel listener.
594 void
595 channel_listener_unregister(channel_listener_t *chan_l)
597 tor_assert(chan_l);
599 /* No-op if not registered */
600 if (!(chan_l->registered)) return;
602 /* Is it finished? */
603 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
604 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
605 /* Get it out of the finished list */
606 if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
607 } else {
608 /* Get it out of the active list */
609 if (active_listeners) smartlist_remove(active_listeners, chan_l);
612 /* Get it out of all_listeners */
613 if (all_listeners) smartlist_remove(all_listeners, chan_l);
615 /* Mark it as unregistered */
616 chan_l->registered = 0;
619 /*********************************
620 * Channel digest map maintenance
621 *********************************/
624 * Add a channel to the digest map
626 * This function adds a channel to the digest map and inserts it into the
627 * correct linked list if channels with that remote endpoint identity digest
628 * already exist.
631 static void
632 channel_add_to_digest_map(channel_t *chan)
634 channel_idmap_entry_t *ent, search;
636 tor_assert(chan);
638 /* Assert that the state makes sense */
639 tor_assert(!CHANNEL_CONDEMNED(chan));
641 /* Assert that there is a digest */
642 tor_assert(!tor_digest_is_zero(chan->identity_digest));
644 memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
645 ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
646 if (! ent) {
647 ent = tor_malloc(sizeof(channel_idmap_entry_t));
648 memcpy(ent->digest, chan->identity_digest, DIGEST_LEN);
649 TOR_LIST_INIT(&ent->channel_list);
650 HT_INSERT(channel_idmap, &channel_identity_map, ent);
652 TOR_LIST_INSERT_HEAD(&ent->channel_list, chan, next_with_same_id);
654 log_debug(LD_CHANNEL,
655 "Added channel %p (global ID " U64_FORMAT ") "
656 "to identity map in state %s (%d) with digest %s",
657 chan, U64_PRINTF_ARG(chan->global_identifier),
658 channel_state_to_string(chan->state), chan->state,
659 hex_str(chan->identity_digest, DIGEST_LEN));
663 * Remove a channel from the digest map
665 * This function removes a channel from the digest map and the linked list of
666 * channels for that digest if more than one exists.
669 static void
670 channel_remove_from_digest_map(channel_t *chan)
672 channel_idmap_entry_t *ent, search;
674 tor_assert(chan);
676 /* Assert that there is a digest */
677 tor_assert(!tor_digest_is_zero(chan->identity_digest));
679 #if 0
680 /* Make sure we have a map */
681 if (!channel_identity_map) {
683 * No identity map, so we can't find it by definition. This
684 * case is similar to digestmap_get() failing below.
686 log_warn(LD_BUG,
687 "Trying to remove channel %p (global ID " U64_FORMAT ") "
688 "with digest %s from identity map, but didn't have any identity "
689 "map",
690 chan, U64_PRINTF_ARG(chan->global_identifier),
691 hex_str(chan->identity_digest, DIGEST_LEN));
692 /* Clear out its next/prev pointers */
693 if (chan->next_with_same_id) {
694 chan->next_with_same_id->prev_with_same_id = chan->prev_with_same_id;
696 if (chan->prev_with_same_id) {
697 chan->prev_with_same_id->next_with_same_id = chan->next_with_same_id;
699 chan->next_with_same_id = NULL;
700 chan->prev_with_same_id = NULL;
702 return;
704 #endif /* 0 */
706 /* Pull it out of its list, wherever that list is */
707 TOR_LIST_REMOVE(chan, next_with_same_id);
709 memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
710 ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
712 /* Look for it in the map */
713 if (ent) {
714 /* Okay, it's here */
716 if (TOR_LIST_EMPTY(&ent->channel_list)) {
717 HT_REMOVE(channel_idmap, &channel_identity_map, ent);
718 tor_free(ent);
721 log_debug(LD_CHANNEL,
722 "Removed channel %p (global ID " U64_FORMAT ") from "
723 "identity map in state %s (%d) with digest %s",
724 chan, U64_PRINTF_ARG(chan->global_identifier),
725 channel_state_to_string(chan->state), chan->state,
726 hex_str(chan->identity_digest, DIGEST_LEN));
727 } else {
728 /* Shouldn't happen */
729 log_warn(LD_BUG,
730 "Trying to remove channel %p (global ID " U64_FORMAT ") with "
731 "digest %s from identity map, but couldn't find any with "
732 "that digest",
733 chan, U64_PRINTF_ARG(chan->global_identifier),
734 hex_str(chan->identity_digest, DIGEST_LEN));
738 /****************************
739 * Channel lookup functions *
740 ***************************/
743 * Find channel by global ID
745 * This function searches for a channel by the global_identifier assigned
746 * at initialization time. This identifier is unique for the lifetime of the
747 * Tor process.
750 channel_t *
751 channel_find_by_global_id(uint64_t global_identifier)
753 channel_t lookup;
754 channel_t *rv = NULL;
756 lookup.global_identifier = global_identifier;
757 rv = HT_FIND(channel_gid_map, &channel_gid_map, &lookup);
758 if (rv) {
759 tor_assert(rv->global_identifier == global_identifier);
762 return rv;
765 /** Return true iff <b>chan</b> matches <b>rsa_id_digest</b> and <b>ed_id</b>.
766 * as its identity keys. If either is NULL, do not check for a match. */
767 static int
768 channel_remote_identity_matches(const channel_t *chan,
769 const char *rsa_id_digest,
770 const ed25519_public_key_t *ed_id)
772 if (BUG(!chan))
773 return 0;
774 if (rsa_id_digest) {
775 if (tor_memneq(rsa_id_digest, chan->identity_digest, DIGEST_LEN))
776 return 0;
778 if (ed_id) {
779 if (tor_memneq(ed_id->pubkey, chan->ed25519_identity.pubkey,
780 ED25519_PUBKEY_LEN))
781 return 0;
783 return 1;
787 * Find channel by RSA/Ed25519 identity of of the remote endpoint
789 * This function looks up a channel by the digest of its remote endpoint's RSA
790 * identity key. If <b>ed_id</b> is provided and nonzero, only a channel
791 * matching the <b>ed_id</b> will be returned.
793 * It's possible that more than one channel to a given endpoint exists. Use
794 * channel_next_with_rsa_identity() to walk the list of channels; make sure
795 * to test for Ed25519 identity match too (as appropriate)
797 channel_t *
798 channel_find_by_remote_identity(const char *rsa_id_digest,
799 const ed25519_public_key_t *ed_id)
801 channel_t *rv = NULL;
802 channel_idmap_entry_t *ent, search;
804 tor_assert(rsa_id_digest); /* For now, we require that every channel have
805 * an RSA identity, and that every lookup
806 * contain an RSA identity */
807 if (ed_id && ed25519_public_key_is_zero(ed_id)) {
808 /* Treat zero as meaning "We don't care about the presence or absence of
809 * an Ed key", not "There must be no Ed key". */
810 ed_id = NULL;
813 memcpy(search.digest, rsa_id_digest, DIGEST_LEN);
814 ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
815 if (ent) {
816 rv = TOR_LIST_FIRST(&ent->channel_list);
818 while (rv && ! channel_remote_identity_matches(rv, rsa_id_digest, ed_id)) {
819 rv = channel_next_with_rsa_identity(rv);
822 return rv;
826 * Get next channel with digest
828 * This function takes a channel and finds the next channel in the list
829 * with the same digest.
832 channel_t *
833 channel_next_with_rsa_identity(channel_t *chan)
835 tor_assert(chan);
837 return TOR_LIST_NEXT(chan, next_with_same_id);
841 * Relays run this once an hour to look over our list of channels to other
842 * relays. It prints out some statistics if there are multiple connections
843 * to many relays.
845 * This function is similar to connection_or_set_bad_connections(),
846 * and probably could be adapted to replace it, if it was modified to actually
847 * take action on any of these connections.
849 void
850 channel_check_for_duplicates(void)
852 channel_idmap_entry_t **iter;
853 channel_t *chan;
854 int total_relay_connections = 0, total_relays = 0, total_canonical = 0;
855 int total_half_canonical = 0;
856 int total_gt_one_connection = 0, total_gt_two_connections = 0;
857 int total_gt_four_connections = 0;
859 HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
860 int connections_to_relay = 0;
862 /* Only consider relay connections */
863 if (!connection_or_digest_is_known_relay((char*)(*iter)->digest))
864 continue;
866 total_relays++;
868 for (chan = TOR_LIST_FIRST(&(*iter)->channel_list); chan;
869 chan = channel_next_with_rsa_identity(chan)) {
871 if (CHANNEL_CONDEMNED(chan) || !CHANNEL_IS_OPEN(chan))
872 continue;
874 connections_to_relay++;
875 total_relay_connections++;
877 if (chan->is_canonical(chan, 0)) total_canonical++;
879 if (!chan->is_canonical_to_peer && chan->is_canonical(chan, 0)
880 && chan->is_canonical(chan, 1)) {
881 total_half_canonical++;
885 if (connections_to_relay > 1) total_gt_one_connection++;
886 if (connections_to_relay > 2) total_gt_two_connections++;
887 if (connections_to_relay > 4) total_gt_four_connections++;
890 #define MIN_RELAY_CONNECTIONS_TO_WARN 5
892 /* If we average 1.5 or more connections per relay, something is wrong */
893 if (total_relays > MIN_RELAY_CONNECTIONS_TO_WARN &&
894 total_relay_connections >= 1.5*total_relays) {
895 log_notice(LD_OR,
896 "Your relay has a very large number of connections to other relays. "
897 "Is your outbound address the same as your relay address? "
898 "Found %d connections to %d relays. Found %d current canonical "
899 "connections, in %d of which we were a non-canonical peer. "
900 "%d relays had more than 1 connection, %d had more than 2, and "
901 "%d had more than 4 connections.",
902 total_relay_connections, total_relays, total_canonical,
903 total_half_canonical, total_gt_one_connection,
904 total_gt_two_connections, total_gt_four_connections);
905 } else {
906 log_info(LD_OR, "Performed connection pruning. "
907 "Found %d connections to %d relays. Found %d current canonical "
908 "connections, in %d of which we were a non-canonical peer. "
909 "%d relays had more than 1 connection, %d had more than 2, and "
910 "%d had more than 4 connections.",
911 total_relay_connections, total_relays, total_canonical,
912 total_half_canonical, total_gt_one_connection,
913 total_gt_two_connections, total_gt_four_connections);
918 * Initialize a channel
920 * This function should be called by subclasses to set up some per-channel
921 * variables. I.e., this is the superclass constructor. Before this, the
922 * channel should be allocated with tor_malloc_zero().
925 void
926 channel_init(channel_t *chan)
928 tor_assert(chan);
930 /* Assign an ID and bump the counter */
931 chan->global_identifier = ++n_channels_allocated;
933 /* Init timestamp */
934 chan->timestamp_last_had_circuits = time(NULL);
936 /* Warn about exhausted circuit IDs no more than hourly. */
937 chan->last_warned_circ_ids_exhausted.rate = 3600;
939 /* Initialize queues. */
940 TOR_SIMPLEQ_INIT(&chan->incoming_queue);
941 TOR_SIMPLEQ_INIT(&chan->outgoing_queue);
943 /* Initialize list entries. */
944 memset(&chan->next_with_same_id, 0, sizeof(chan->next_with_same_id));
946 /* Timestamp it */
947 channel_timestamp_created(chan);
949 /* It hasn't been open yet. */
950 chan->has_been_open = 0;
952 /* Scheduler state is idle */
953 chan->scheduler_state = SCHED_CHAN_IDLE;
957 * Initialize a channel listener
959 * This function should be called by subclasses to set up some per-channel
960 * variables. I.e., this is the superclass constructor. Before this, the
961 * channel listener should be allocated with tor_malloc_zero().
964 void
965 channel_init_listener(channel_listener_t *chan_l)
967 tor_assert(chan_l);
969 /* Assign an ID and bump the counter */
970 chan_l->global_identifier = ++n_channels_allocated;
972 /* Timestamp it */
973 channel_listener_timestamp_created(chan_l);
977 * Free a channel; nothing outside of channel.c and subclasses should call
978 * this - it frees channels after they have closed and been unregistered.
981 void
982 channel_free(channel_t *chan)
984 if (!chan) return;
986 /* It must be closed or errored */
987 tor_assert(CHANNEL_FINISHED(chan));
989 /* It must be deregistered */
990 tor_assert(!(chan->registered));
992 log_debug(LD_CHANNEL,
993 "Freeing channel " U64_FORMAT " at %p",
994 U64_PRINTF_ARG(chan->global_identifier), chan);
996 /* Get this one out of the scheduler */
997 scheduler_release_channel(chan);
1000 * Get rid of cmux policy before we do anything, so cmux policies don't
1001 * see channels in weird half-freed states.
1003 if (chan->cmux) {
1004 circuitmux_set_policy(chan->cmux, NULL);
1007 /* Remove all timers and associated handle entries now */
1008 timer_free(chan->padding_timer);
1009 channel_handle_free(chan->timer_handle);
1010 channel_handles_clear(chan);
1012 /* Call a free method if there is one */
1013 if (chan->free_fn) chan->free_fn(chan);
1015 channel_clear_remote_end(chan);
1017 /* Get rid of cmux */
1018 if (chan->cmux) {
1019 circuitmux_detach_all_circuits(chan->cmux, NULL);
1020 circuitmux_mark_destroyed_circids_usable(chan->cmux, chan);
1021 circuitmux_free(chan->cmux);
1022 chan->cmux = NULL;
1025 /* We're in CLOSED or ERROR, so the cell queue is already empty */
1027 tor_free(chan);
1031 * Free a channel listener; nothing outside of channel.c and subclasses
1032 * should call this - it frees channel listeners after they have closed and
1033 * been unregistered.
1036 void
1037 channel_listener_free(channel_listener_t *chan_l)
1039 if (!chan_l) return;
1041 log_debug(LD_CHANNEL,
1042 "Freeing channel_listener_t " U64_FORMAT " at %p",
1043 U64_PRINTF_ARG(chan_l->global_identifier),
1044 chan_l);
1046 /* It must be closed or errored */
1047 tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1048 chan_l->state == CHANNEL_LISTENER_STATE_ERROR);
1049 /* It must be deregistered */
1050 tor_assert(!(chan_l->registered));
1052 /* Call a free method if there is one */
1053 if (chan_l->free_fn) chan_l->free_fn(chan_l);
1056 * We're in CLOSED or ERROR, so the incoming channel queue is already
1057 * empty.
1060 tor_free(chan_l);
1064 * Free a channel and skip the state/registration asserts; this internal-
1065 * use-only function should be called only from channel_free_all() when
1066 * shutting down the Tor process.
1069 static void
1070 channel_force_free(channel_t *chan)
1072 cell_queue_entry_t *cell, *cell_tmp;
1073 tor_assert(chan);
1075 log_debug(LD_CHANNEL,
1076 "Force-freeing channel " U64_FORMAT " at %p",
1077 U64_PRINTF_ARG(chan->global_identifier), chan);
1079 /* Get this one out of the scheduler */
1080 scheduler_release_channel(chan);
1083 * Get rid of cmux policy before we do anything, so cmux policies don't
1084 * see channels in weird half-freed states.
1086 if (chan->cmux) {
1087 circuitmux_set_policy(chan->cmux, NULL);
1090 /* Remove all timers and associated handle entries now */
1091 timer_free(chan->padding_timer);
1092 channel_handle_free(chan->timer_handle);
1093 channel_handles_clear(chan);
1095 /* Call a free method if there is one */
1096 if (chan->free_fn) chan->free_fn(chan);
1098 channel_clear_remote_end(chan);
1100 /* Get rid of cmux */
1101 if (chan->cmux) {
1102 circuitmux_free(chan->cmux);
1103 chan->cmux = NULL;
1106 /* We might still have a cell queue; kill it */
1107 TOR_SIMPLEQ_FOREACH_SAFE(cell, &chan->incoming_queue, next, cell_tmp) {
1108 cell_queue_entry_free(cell, 0);
1110 TOR_SIMPLEQ_INIT(&chan->incoming_queue);
1112 /* Outgoing cell queue is similar, but we can have to free packed cells */
1113 TOR_SIMPLEQ_FOREACH_SAFE(cell, &chan->outgoing_queue, next, cell_tmp) {
1114 cell_queue_entry_free(cell, 0);
1116 TOR_SIMPLEQ_INIT(&chan->outgoing_queue);
1118 tor_free(chan);
1122 * Free a channel listener and skip the state/reigstration asserts; this
1123 * internal-use-only function should be called only from channel_free_all()
1124 * when shutting down the Tor process.
1127 static void
1128 channel_listener_force_free(channel_listener_t *chan_l)
1130 tor_assert(chan_l);
1132 log_debug(LD_CHANNEL,
1133 "Force-freeing channel_listener_t " U64_FORMAT " at %p",
1134 U64_PRINTF_ARG(chan_l->global_identifier),
1135 chan_l);
1137 /* Call a free method if there is one */
1138 if (chan_l->free_fn) chan_l->free_fn(chan_l);
1141 * The incoming list just gets emptied and freed; we request close on
1142 * any channels we find there, but since we got called while shutting
1143 * down they will get deregistered and freed elsewhere anyway.
1145 if (chan_l->incoming_list) {
1146 SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
1147 channel_t *, qchan) {
1148 channel_mark_for_close(qchan);
1149 } SMARTLIST_FOREACH_END(qchan);
1151 smartlist_free(chan_l->incoming_list);
1152 chan_l->incoming_list = NULL;
1155 tor_free(chan_l);
1159 * Return the current registered listener for a channel listener
1161 * This function returns a function pointer to the current registered
1162 * handler for new incoming channels on a channel listener.
1165 channel_listener_fn_ptr
1166 channel_listener_get_listener_fn(channel_listener_t *chan_l)
1168 tor_assert(chan_l);
1170 if (chan_l->state == CHANNEL_LISTENER_STATE_LISTENING)
1171 return chan_l->listener;
1173 return NULL;
1177 * Set the listener for a channel listener
1179 * This function sets the handler for new incoming channels on a channel
1180 * listener.
1183 void
1184 channel_listener_set_listener_fn(channel_listener_t *chan_l,
1185 channel_listener_fn_ptr listener)
1187 tor_assert(chan_l);
1188 tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_LISTENING);
1190 log_debug(LD_CHANNEL,
1191 "Setting listener callback for channel listener %p "
1192 "(global ID " U64_FORMAT ") to %p",
1193 chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
1194 listener);
1196 chan_l->listener = listener;
1197 if (chan_l->listener) channel_listener_process_incoming(chan_l);
1201 * Return the fixed-length cell handler for a channel
1203 * This function gets the handler for incoming fixed-length cells installed
1204 * on a channel.
1207 channel_cell_handler_fn_ptr
1208 channel_get_cell_handler(channel_t *chan)
1210 tor_assert(chan);
1212 if (CHANNEL_CAN_HANDLE_CELLS(chan))
1213 return chan->cell_handler;
1215 return NULL;
1219 * Return the variable-length cell handler for a channel
1221 * This function gets the handler for incoming variable-length cells
1222 * installed on a channel.
1225 channel_var_cell_handler_fn_ptr
1226 channel_get_var_cell_handler(channel_t *chan)
1228 tor_assert(chan);
1230 if (CHANNEL_CAN_HANDLE_CELLS(chan))
1231 return chan->var_cell_handler;
1233 return NULL;
1237 * Set both cell handlers for a channel
1239 * This function sets both the fixed-length and variable length cell handlers
1240 * for a channel and processes any incoming cells that had been blocked in the
1241 * queue because none were available.
1244 void
1245 channel_set_cell_handlers(channel_t *chan,
1246 channel_cell_handler_fn_ptr cell_handler,
1247 channel_var_cell_handler_fn_ptr
1248 var_cell_handler)
1250 int try_again = 0;
1252 tor_assert(chan);
1253 tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
1255 log_debug(LD_CHANNEL,
1256 "Setting cell_handler callback for channel %p to %p",
1257 chan, cell_handler);
1258 log_debug(LD_CHANNEL,
1259 "Setting var_cell_handler callback for channel %p to %p",
1260 chan, var_cell_handler);
1262 /* Should we try the queue? */
1263 if (cell_handler &&
1264 cell_handler != chan->cell_handler) try_again = 1;
1265 if (var_cell_handler &&
1266 var_cell_handler != chan->var_cell_handler) try_again = 1;
1268 /* Change them */
1269 chan->cell_handler = cell_handler;
1270 chan->var_cell_handler = var_cell_handler;
1272 /* Re-run the queue if we have one and there's any reason to */
1273 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue) &&
1274 try_again &&
1275 (chan->cell_handler ||
1276 chan->var_cell_handler)) channel_process_cells(chan);
1280 * On closing channels
1282 * There are three functions that close channels, for use in
1283 * different circumstances:
1285 * - Use channel_mark_for_close() for most cases
1286 * - Use channel_close_from_lower_layer() if you are connection_or.c
1287 * and the other end closes the underlying connection.
1288 * - Use channel_close_for_error() if you are connection_or.c and
1289 * some sort of error has occurred.
1293 * Mark a channel for closure
1295 * This function tries to close a channel_t; it will go into the CLOSING
1296 * state, and eventually the lower layer should put it into the CLOSED or
1297 * ERROR state. Then, channel_run_cleanup() will eventually free it.
1300 void
1301 channel_mark_for_close(channel_t *chan)
1303 tor_assert(chan != NULL);
1304 tor_assert(chan->close != NULL);
1306 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1307 if (CHANNEL_CONDEMNED(chan))
1308 return;
1310 log_debug(LD_CHANNEL,
1311 "Closing channel %p (global ID " U64_FORMAT ") "
1312 "by request",
1313 chan, U64_PRINTF_ARG(chan->global_identifier));
1315 /* Note closing by request from above */
1316 chan->reason_for_closing = CHANNEL_CLOSE_REQUESTED;
1318 /* Change state to CLOSING */
1319 channel_change_state(chan, CHANNEL_STATE_CLOSING);
1321 /* Tell the lower layer */
1322 chan->close(chan);
1325 * It's up to the lower layer to change state to CLOSED or ERROR when we're
1326 * ready; we'll try to free channels that are in the finished list from
1327 * channel_run_cleanup(). The lower layer should do this by calling
1328 * channel_closed().
1333 * Mark a channel listener for closure
1335 * This function tries to close a channel_listener_t; it will go into the
1336 * CLOSING state, and eventually the lower layer should put it into the CLOSED
1337 * or ERROR state. Then, channel_run_cleanup() will eventually free it.
1340 void
1341 channel_listener_mark_for_close(channel_listener_t *chan_l)
1343 tor_assert(chan_l != NULL);
1344 tor_assert(chan_l->close != NULL);
1346 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1347 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
1348 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1349 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
1351 log_debug(LD_CHANNEL,
1352 "Closing channel listener %p (global ID " U64_FORMAT ") "
1353 "by request",
1354 chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
1356 /* Note closing by request from above */
1357 chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_REQUESTED;
1359 /* Change state to CLOSING */
1360 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
1362 /* Tell the lower layer */
1363 chan_l->close(chan_l);
1366 * It's up to the lower layer to change state to CLOSED or ERROR when we're
1367 * ready; we'll try to free channels that are in the finished list from
1368 * channel_run_cleanup(). The lower layer should do this by calling
1369 * channel_listener_closed().
1374 * Close a channel from the lower layer
1376 * Notify the channel code that the channel is being closed due to a non-error
1377 * condition in the lower layer. This does not call the close() method, since
1378 * the lower layer already knows.
1381 void
1382 channel_close_from_lower_layer(channel_t *chan)
1384 tor_assert(chan != NULL);
1386 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1387 if (CHANNEL_CONDEMNED(chan))
1388 return;
1390 log_debug(LD_CHANNEL,
1391 "Closing channel %p (global ID " U64_FORMAT ") "
1392 "due to lower-layer event",
1393 chan, U64_PRINTF_ARG(chan->global_identifier));
1395 /* Note closing by event from below */
1396 chan->reason_for_closing = CHANNEL_CLOSE_FROM_BELOW;
1398 /* Change state to CLOSING */
1399 channel_change_state(chan, CHANNEL_STATE_CLOSING);
1403 * Close a channel listener from the lower layer
1405 * Notify the channel code that the channel listener is being closed due to a
1406 * non-error condition in the lower layer. This does not call the close()
1407 * method, since the lower layer already knows.
1410 void
1411 channel_listener_close_from_lower_layer(channel_listener_t *chan_l)
1413 tor_assert(chan_l != NULL);
1415 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1416 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
1417 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1418 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
1420 log_debug(LD_CHANNEL,
1421 "Closing channel listener %p (global ID " U64_FORMAT ") "
1422 "due to lower-layer event",
1423 chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
1425 /* Note closing by event from below */
1426 chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_FROM_BELOW;
1428 /* Change state to CLOSING */
1429 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
1433 * Notify that the channel is being closed due to an error condition
1435 * This function is called by the lower layer implementing the transport
1436 * when a channel must be closed due to an error condition. This does not
1437 * call the channel's close method, since the lower layer already knows.
1440 void
1441 channel_close_for_error(channel_t *chan)
1443 tor_assert(chan != NULL);
1445 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1446 if (CHANNEL_CONDEMNED(chan))
1447 return;
1449 log_debug(LD_CHANNEL,
1450 "Closing channel %p due to lower-layer error",
1451 chan);
1453 /* Note closing by event from below */
1454 chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
1456 /* Change state to CLOSING */
1457 channel_change_state(chan, CHANNEL_STATE_CLOSING);
1461 * Notify that the channel listener is being closed due to an error condition
1463 * This function is called by the lower layer implementing the transport
1464 * when a channel listener must be closed due to an error condition. This
1465 * does not call the channel listener's close method, since the lower layer
1466 * already knows.
1469 void
1470 channel_listener_close_for_error(channel_listener_t *chan_l)
1472 tor_assert(chan_l != NULL);
1474 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1475 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
1476 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1477 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
1479 log_debug(LD_CHANNEL,
1480 "Closing channel listener %p (global ID " U64_FORMAT ") "
1481 "due to lower-layer error",
1482 chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
1484 /* Note closing by event from below */
1485 chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_FOR_ERROR;
1487 /* Change state to CLOSING */
1488 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
1492 * Notify that the lower layer is finished closing the channel
1494 * This function should be called by the lower layer when a channel
1495 * is finished closing and it should be regarded as inactive and
1496 * freed by the channel code.
1499 void
1500 channel_closed(channel_t *chan)
1502 tor_assert(chan);
1503 tor_assert(CHANNEL_CONDEMNED(chan));
1505 /* No-op if already inactive */
1506 if (CHANNEL_FINISHED(chan))
1507 return;
1509 /* Inform any pending (not attached) circs that they should
1510 * give up. */
1511 if (! chan->has_been_open)
1512 circuit_n_chan_done(chan, 0, 0);
1514 /* Now close all the attached circuits on it. */
1515 circuit_unlink_all_from_channel(chan, END_CIRC_REASON_CHANNEL_CLOSED);
1517 if (chan->reason_for_closing != CHANNEL_CLOSE_FOR_ERROR) {
1518 channel_change_state(chan, CHANNEL_STATE_CLOSED);
1519 } else {
1520 channel_change_state(chan, CHANNEL_STATE_ERROR);
1525 * Notify that the lower layer is finished closing the channel listener
1527 * This function should be called by the lower layer when a channel listener
1528 * is finished closing and it should be regarded as inactive and
1529 * freed by the channel code.
1532 void
1533 channel_listener_closed(channel_listener_t *chan_l)
1535 tor_assert(chan_l);
1536 tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
1537 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1538 chan_l->state == CHANNEL_LISTENER_STATE_ERROR);
1540 /* No-op if already inactive */
1541 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1542 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
1544 if (chan_l->reason_for_closing != CHANNEL_LISTENER_CLOSE_FOR_ERROR) {
1545 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSED);
1546 } else {
1547 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_ERROR);
1552 * Clear the identity_digest of a channel
1554 * This function clears the identity digest of the remote endpoint for a
1555 * channel; this is intended for use by the lower layer.
1558 void
1559 channel_clear_identity_digest(channel_t *chan)
1561 int state_not_in_map;
1563 tor_assert(chan);
1565 log_debug(LD_CHANNEL,
1566 "Clearing remote endpoint digest on channel %p with "
1567 "global ID " U64_FORMAT,
1568 chan, U64_PRINTF_ARG(chan->global_identifier));
1570 state_not_in_map = CHANNEL_CONDEMNED(chan);
1572 if (!state_not_in_map && chan->registered &&
1573 !tor_digest_is_zero(chan->identity_digest))
1574 /* if it's registered get it out of the digest map */
1575 channel_remove_from_digest_map(chan);
1577 memset(chan->identity_digest, 0,
1578 sizeof(chan->identity_digest));
1582 * Set the identity_digest of a channel
1584 * This function sets the identity digest of the remote endpoint for a
1585 * channel; this is intended for use by the lower layer.
1587 void
1588 channel_set_identity_digest(channel_t *chan,
1589 const char *identity_digest,
1590 const ed25519_public_key_t *ed_identity)
1592 int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
1594 tor_assert(chan);
1596 log_debug(LD_CHANNEL,
1597 "Setting remote endpoint digest on channel %p with "
1598 "global ID " U64_FORMAT " to digest %s",
1599 chan, U64_PRINTF_ARG(chan->global_identifier),
1600 identity_digest ?
1601 hex_str(identity_digest, DIGEST_LEN) : "(null)");
1603 state_not_in_map = CHANNEL_CONDEMNED(chan);
1605 was_in_digest_map =
1606 !state_not_in_map &&
1607 chan->registered &&
1608 !tor_digest_is_zero(chan->identity_digest);
1609 should_be_in_digest_map =
1610 !state_not_in_map &&
1611 chan->registered &&
1612 (identity_digest &&
1613 !tor_digest_is_zero(identity_digest));
1615 if (was_in_digest_map)
1616 /* We should always remove it; we'll add it back if we're writing
1617 * in a new digest.
1619 channel_remove_from_digest_map(chan);
1621 if (identity_digest) {
1622 memcpy(chan->identity_digest,
1623 identity_digest,
1624 sizeof(chan->identity_digest));
1625 } else {
1626 memset(chan->identity_digest, 0,
1627 sizeof(chan->identity_digest));
1629 if (ed_identity) {
1630 memcpy(&chan->ed25519_identity, ed_identity, sizeof(*ed_identity));
1631 } else {
1632 memset(&chan->ed25519_identity, 0, sizeof(*ed_identity));
1635 /* Put it in the digest map if we should */
1636 if (should_be_in_digest_map)
1637 channel_add_to_digest_map(chan);
1641 * Clear the remote end metadata (identity_digest/nickname) of a channel
1643 * This function clears all the remote end info from a channel; this is
1644 * intended for use by the lower layer.
1647 void
1648 channel_clear_remote_end(channel_t *chan)
1650 int state_not_in_map;
1652 tor_assert(chan);
1654 log_debug(LD_CHANNEL,
1655 "Clearing remote endpoint identity on channel %p with "
1656 "global ID " U64_FORMAT,
1657 chan, U64_PRINTF_ARG(chan->global_identifier));
1659 state_not_in_map = CHANNEL_CONDEMNED(chan);
1661 if (!state_not_in_map && chan->registered &&
1662 !tor_digest_is_zero(chan->identity_digest))
1663 /* if it's registered get it out of the digest map */
1664 channel_remove_from_digest_map(chan);
1666 memset(chan->identity_digest, 0,
1667 sizeof(chan->identity_digest));
1668 tor_free(chan->nickname);
1672 * Set the remote end metadata (identity_digest/nickname) of a channel
1674 * This function sets new remote end info on a channel; this is intended
1675 * for use by the lower layer.
1678 void
1679 channel_set_remote_end(channel_t *chan,
1680 const char *identity_digest,
1681 const char *nickname)
1683 int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
1685 tor_assert(chan);
1687 log_debug(LD_CHANNEL,
1688 "Setting remote endpoint identity on channel %p with "
1689 "global ID " U64_FORMAT " to nickname %s, digest %s",
1690 chan, U64_PRINTF_ARG(chan->global_identifier),
1691 nickname ? nickname : "(null)",
1692 identity_digest ?
1693 hex_str(identity_digest, DIGEST_LEN) : "(null)");
1695 state_not_in_map = CHANNEL_CONDEMNED(chan);
1697 was_in_digest_map =
1698 !state_not_in_map &&
1699 chan->registered &&
1700 !tor_digest_is_zero(chan->identity_digest);
1701 should_be_in_digest_map =
1702 !state_not_in_map &&
1703 chan->registered &&
1704 (identity_digest &&
1705 !tor_digest_is_zero(identity_digest));
1707 if (was_in_digest_map)
1708 /* We should always remove it; we'll add it back if we're writing
1709 * in a new digest.
1711 channel_remove_from_digest_map(chan);
1713 if (identity_digest) {
1714 memcpy(chan->identity_digest,
1715 identity_digest,
1716 sizeof(chan->identity_digest));
1718 } else {
1719 memset(chan->identity_digest, 0,
1720 sizeof(chan->identity_digest));
1723 tor_free(chan->nickname);
1724 if (nickname)
1725 chan->nickname = tor_strdup(nickname);
1727 /* Put it in the digest map if we should */
1728 if (should_be_in_digest_map)
1729 channel_add_to_digest_map(chan);
1733 * Duplicate a cell queue entry; this is a shallow copy intended for use
1734 * in channel_write_cell_queue_entry().
1737 static cell_queue_entry_t *
1738 cell_queue_entry_dup(cell_queue_entry_t *q)
1740 cell_queue_entry_t *rv = NULL;
1742 tor_assert(q);
1744 rv = tor_malloc(sizeof(*rv));
1745 memcpy(rv, q, sizeof(*rv));
1747 return rv;
1751 * Free a cell_queue_entry_t; the handed_off parameter indicates whether
1752 * the contents were passed to the lower layer (it is responsible for
1753 * them) or not (we should free).
1756 STATIC void
1757 cell_queue_entry_free(cell_queue_entry_t *q, int handed_off)
1759 if (!q) return;
1761 if (!handed_off) {
1763 * If we handed it off, the recipient becomes responsible (or
1764 * with packed cells the channel_t subclass calls packed_cell
1765 * free after writing out its contents; see, e.g.,
1766 * channel_tls_write_packed_cell_method(). Otherwise, we have
1767 * to take care of it here if possible.
1769 switch (q->type) {
1770 case CELL_QUEUE_FIXED:
1771 if (q->u.fixed.cell) {
1773 * There doesn't seem to be a cell_free() function anywhere in the
1774 * pre-channel code; just use tor_free()
1776 tor_free(q->u.fixed.cell);
1778 break;
1779 case CELL_QUEUE_PACKED:
1780 if (q->u.packed.packed_cell) {
1781 packed_cell_free(q->u.packed.packed_cell);
1783 break;
1784 case CELL_QUEUE_VAR:
1785 if (q->u.var.var_cell) {
1787 * This one's in connection_or.c; it'd be nice to figure out the
1788 * whole flow of cells from one end to the other and factor the
1789 * cell memory management functions like this out of the specific
1790 * TLS lower layer.
1792 var_cell_free(q->u.var.var_cell);
1794 break;
1795 default:
1797 * Nothing we can do if we don't know the type; this will
1798 * have been warned about elsewhere.
1800 break;
1803 tor_free(q);
1806 #if 0
1808 * Check whether a cell queue entry is padding; this is a helper function
1809 * for channel_write_cell_queue_entry()
1812 static int
1813 cell_queue_entry_is_padding(cell_queue_entry_t *q)
1815 tor_assert(q);
1817 if (q->type == CELL_QUEUE_FIXED) {
1818 if (q->u.fixed.cell) {
1819 if (q->u.fixed.cell->command == CELL_PADDING ||
1820 q->u.fixed.cell->command == CELL_VPADDING) {
1821 return 1;
1824 } else if (q->type == CELL_QUEUE_VAR) {
1825 if (q->u.var.var_cell) {
1826 if (q->u.var.var_cell->command == CELL_PADDING ||
1827 q->u.var.var_cell->command == CELL_VPADDING) {
1828 return 1;
1833 return 0;
1835 #endif /* 0 */
1838 * Allocate a new cell queue entry for a fixed-size cell
1841 static cell_queue_entry_t *
1842 cell_queue_entry_new_fixed(cell_t *cell)
1844 cell_queue_entry_t *q = NULL;
1846 tor_assert(cell);
1848 q = tor_malloc(sizeof(*q));
1849 q->type = CELL_QUEUE_FIXED;
1850 q->u.fixed.cell = cell;
1852 return q;
1856 * Allocate a new cell queue entry for a variable-size cell
1859 static cell_queue_entry_t *
1860 cell_queue_entry_new_var(var_cell_t *var_cell)
1862 cell_queue_entry_t *q = NULL;
1864 tor_assert(var_cell);
1866 q = tor_malloc(sizeof(*q));
1867 q->type = CELL_QUEUE_VAR;
1868 q->u.var.var_cell = var_cell;
1870 return q;
1874 * Ask how big the cell contained in a cell_queue_entry_t is
1877 static size_t
1878 channel_get_cell_queue_entry_size(channel_t *chan, cell_queue_entry_t *q)
1880 size_t rv = 0;
1882 tor_assert(chan);
1883 tor_assert(q);
1885 switch (q->type) {
1886 case CELL_QUEUE_FIXED:
1887 rv = get_cell_network_size(chan->wide_circ_ids);
1888 break;
1889 case CELL_QUEUE_VAR:
1890 rv = get_var_cell_header_size(chan->wide_circ_ids) +
1891 (q->u.var.var_cell ? q->u.var.var_cell->payload_len : 0);
1892 break;
1893 case CELL_QUEUE_PACKED:
1894 rv = get_cell_network_size(chan->wide_circ_ids);
1895 break;
1896 default:
1897 tor_assert_nonfatal_unreached_once();
1900 return rv;
1904 * Write to a channel based on a cell_queue_entry_t
1906 * Given a cell_queue_entry_t filled out by the caller, try to send the cell
1907 * and queue it if we can't.
1910 static void
1911 channel_write_cell_queue_entry(channel_t *chan, cell_queue_entry_t *q)
1913 int result = 0, sent = 0;
1914 cell_queue_entry_t *tmp = NULL;
1915 size_t cell_bytes;
1917 tor_assert(chan);
1918 tor_assert(q);
1920 /* Assert that the state makes sense for a cell write */
1921 tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
1924 circid_t circ_id;
1925 if (is_destroy_cell(chan, q, &circ_id)) {
1926 channel_note_destroy_not_pending(chan, circ_id);
1930 /* For statistical purposes, figure out how big this cell is */
1931 cell_bytes = channel_get_cell_queue_entry_size(chan, q);
1933 /* Can we send it right out? If so, try */
1934 if (TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue) &&
1935 CHANNEL_IS_OPEN(chan)) {
1936 /* Pick the right write function for this cell type and save the result */
1937 switch (q->type) {
1938 case CELL_QUEUE_FIXED:
1939 tor_assert(chan->write_cell);
1940 tor_assert(q->u.fixed.cell);
1941 result = chan->write_cell(chan, q->u.fixed.cell);
1942 break;
1943 case CELL_QUEUE_PACKED:
1944 tor_assert(chan->write_packed_cell);
1945 tor_assert(q->u.packed.packed_cell);
1946 result = chan->write_packed_cell(chan, q->u.packed.packed_cell);
1947 break;
1948 case CELL_QUEUE_VAR:
1949 tor_assert(chan->write_var_cell);
1950 tor_assert(q->u.var.var_cell);
1951 result = chan->write_var_cell(chan, q->u.var.var_cell);
1952 break;
1953 default:
1954 tor_assert(1);
1957 /* Check if we got it out */
1958 if (result > 0) {
1959 sent = 1;
1960 /* Timestamp for transmission */
1961 channel_timestamp_xmit(chan);
1962 /* If we're here the queue is empty, so it's drained too */
1963 channel_timestamp_drained(chan);
1964 /* Update the counter */
1965 ++(chan->n_cells_xmitted);
1966 chan->n_bytes_xmitted += cell_bytes;
1967 /* Update global counters */
1968 ++n_channel_cells_queued;
1969 ++n_channel_cells_passed_to_lower_layer;
1970 n_channel_bytes_queued += cell_bytes;
1971 n_channel_bytes_passed_to_lower_layer += cell_bytes;
1972 channel_assert_counter_consistency();
1976 if (!sent) {
1977 /* Not sent, queue it */
1979 * We have to copy the queue entry passed in, since the caller probably
1980 * used the stack.
1982 tmp = cell_queue_entry_dup(q);
1983 TOR_SIMPLEQ_INSERT_TAIL(&chan->outgoing_queue, tmp, next);
1984 /* Update global counters */
1985 ++n_channel_cells_queued;
1986 ++n_channel_cells_in_queues;
1987 n_channel_bytes_queued += cell_bytes;
1988 n_channel_bytes_in_queues += cell_bytes;
1989 channel_assert_counter_consistency();
1990 /* Update channel queue size */
1991 chan->bytes_in_queue += cell_bytes;
1992 /* Try to process the queue? */
1993 if (CHANNEL_IS_OPEN(chan)) channel_flush_cells(chan);
1997 /** Write a generic cell type to a channel
1999 * Write a generic cell to a channel. It is called by channel_write_cell(),
2000 * channel_write_var_cell() and channel_write_packed_cell() in order to reduce
2001 * code duplication. Notice that it takes cell as pointer of type void,
2002 * this can be dangerous because no type check is performed.
2005 void
2006 channel_write_cell_generic_(channel_t *chan, const char *cell_type,
2007 void *cell, cell_queue_entry_t *q)
2010 tor_assert(chan);
2011 tor_assert(cell);
2013 if (CHANNEL_IS_CLOSING(chan)) {
2014 log_debug(LD_CHANNEL, "Discarding %c %p on closing channel %p with "
2015 "global ID "U64_FORMAT, *cell_type, cell, chan,
2016 U64_PRINTF_ARG(chan->global_identifier));
2017 tor_free(cell);
2018 return;
2020 log_debug(LD_CHANNEL,
2021 "Writing %c %p to channel %p with global ID "
2022 U64_FORMAT, *cell_type,
2023 cell, chan, U64_PRINTF_ARG(chan->global_identifier));
2025 channel_write_cell_queue_entry(chan, q);
2026 /* Update the queue size estimate */
2027 channel_update_xmit_queue_size(chan);
2031 * Write a cell to a channel
2033 * Write a fixed-length cell to a channel using the write_cell() method.
2034 * This is equivalent to the pre-channels connection_or_write_cell_to_buf();
2035 * it is called by the transport-independent code to deliver a cell to a
2036 * channel for transmission.
2039 void
2040 channel_write_cell(channel_t *chan, cell_t *cell)
2042 cell_queue_entry_t q;
2043 q.type = CELL_QUEUE_FIXED;
2044 q.u.fixed.cell = cell;
2045 channel_write_cell_generic_(chan, "cell_t", cell, &q);
2049 * Write a packed cell to a channel
2051 * Write a packed cell to a channel using the write_cell() method. This is
2052 * called by the transport-independent code to deliver a packed cell to a
2053 * channel for transmission.
2056 void
2057 channel_write_packed_cell(channel_t *chan, packed_cell_t *packed_cell)
2059 cell_queue_entry_t q;
2060 q.type = CELL_QUEUE_PACKED;
2061 q.u.packed.packed_cell = packed_cell;
2062 channel_write_cell_generic_(chan, "packed_cell_t", packed_cell, &q);
2066 * Write a variable-length cell to a channel
2068 * Write a variable-length cell to a channel using the write_cell() method.
2069 * This is equivalent to the pre-channels
2070 * connection_or_write_var_cell_to_buf(); it's called by the transport-
2071 * independent code to deliver a var_cell to a channel for transmission.
2074 void
2075 channel_write_var_cell(channel_t *chan, var_cell_t *var_cell)
2077 cell_queue_entry_t q;
2078 q.type = CELL_QUEUE_VAR;
2079 q.u.var.var_cell = var_cell;
2080 channel_write_cell_generic_(chan, "var_cell_t", var_cell, &q);
2084 * Change channel state
2086 * This internal and subclass use only function is used to change channel
2087 * state, performing all transition validity checks and whatever actions
2088 * are appropriate to the state transition in question.
2091 static void
2092 channel_change_state_(channel_t *chan, channel_state_t to_state)
2094 channel_state_t from_state;
2095 unsigned char was_active, is_active;
2096 unsigned char was_in_id_map, is_in_id_map;
2098 tor_assert(chan);
2099 from_state = chan->state;
2101 tor_assert(channel_state_is_valid(from_state));
2102 tor_assert(channel_state_is_valid(to_state));
2103 tor_assert(channel_state_can_transition(chan->state, to_state));
2105 /* Check for no-op transitions */
2106 if (from_state == to_state) {
2107 log_debug(LD_CHANNEL,
2108 "Got no-op transition from \"%s\" to itself on channel %p"
2109 "(global ID " U64_FORMAT ")",
2110 channel_state_to_string(to_state),
2111 chan, U64_PRINTF_ARG(chan->global_identifier));
2112 return;
2115 /* If we're going to a closing or closed state, we must have a reason set */
2116 if (to_state == CHANNEL_STATE_CLOSING ||
2117 to_state == CHANNEL_STATE_CLOSED ||
2118 to_state == CHANNEL_STATE_ERROR) {
2119 tor_assert(chan->reason_for_closing != CHANNEL_NOT_CLOSING);
2123 * We need to maintain the queues here for some transitions:
2124 * when we enter CHANNEL_STATE_OPEN (especially from CHANNEL_STATE_MAINT)
2125 * we may have a backlog of cells to transmit, so drain the queues in
2126 * that case, and when going to CHANNEL_STATE_CLOSED the subclass
2127 * should have made sure to finish sending things (or gone to
2128 * CHANNEL_STATE_ERROR if not possible), so we assert for that here.
2131 log_debug(LD_CHANNEL,
2132 "Changing state of channel %p (global ID " U64_FORMAT
2133 ") from \"%s\" to \"%s\"",
2134 chan,
2135 U64_PRINTF_ARG(chan->global_identifier),
2136 channel_state_to_string(chan->state),
2137 channel_state_to_string(to_state));
2139 chan->state = to_state;
2141 /* Need to add to the right lists if the channel is registered */
2142 if (chan->registered) {
2143 was_active = !(from_state == CHANNEL_STATE_CLOSED ||
2144 from_state == CHANNEL_STATE_ERROR);
2145 is_active = !(to_state == CHANNEL_STATE_CLOSED ||
2146 to_state == CHANNEL_STATE_ERROR);
2148 /* Need to take off active list and put on finished list? */
2149 if (was_active && !is_active) {
2150 if (active_channels) smartlist_remove(active_channels, chan);
2151 if (!finished_channels) finished_channels = smartlist_new();
2152 smartlist_add(finished_channels, chan);
2154 /* Need to put on active list? */
2155 else if (!was_active && is_active) {
2156 if (finished_channels) smartlist_remove(finished_channels, chan);
2157 if (!active_channels) active_channels = smartlist_new();
2158 smartlist_add(active_channels, chan);
2161 if (!tor_digest_is_zero(chan->identity_digest)) {
2162 /* Now we need to handle the identity map */
2163 was_in_id_map = !(from_state == CHANNEL_STATE_CLOSING ||
2164 from_state == CHANNEL_STATE_CLOSED ||
2165 from_state == CHANNEL_STATE_ERROR);
2166 is_in_id_map = !(to_state == CHANNEL_STATE_CLOSING ||
2167 to_state == CHANNEL_STATE_CLOSED ||
2168 to_state == CHANNEL_STATE_ERROR);
2170 if (!was_in_id_map && is_in_id_map) channel_add_to_digest_map(chan);
2171 else if (was_in_id_map && !is_in_id_map)
2172 channel_remove_from_digest_map(chan);
2177 * If we're going to a closed/closing state, we don't need scheduling any
2178 * more; in CHANNEL_STATE_MAINT we can't accept writes.
2180 if (to_state == CHANNEL_STATE_CLOSING ||
2181 to_state == CHANNEL_STATE_CLOSED ||
2182 to_state == CHANNEL_STATE_ERROR) {
2183 scheduler_release_channel(chan);
2184 } else if (to_state == CHANNEL_STATE_MAINT) {
2185 scheduler_channel_doesnt_want_writes(chan);
2189 * If we're closing, this channel no longer counts toward the global
2190 * estimated queue size; if we're open, it now does.
2192 if ((to_state == CHANNEL_STATE_CLOSING ||
2193 to_state == CHANNEL_STATE_CLOSED ||
2194 to_state == CHANNEL_STATE_ERROR) &&
2195 (from_state == CHANNEL_STATE_OPEN ||
2196 from_state == CHANNEL_STATE_MAINT)) {
2197 estimated_total_queue_size -= chan->bytes_in_queue;
2201 * If we're opening, this channel now does count toward the global
2202 * estimated queue size.
2204 if ((to_state == CHANNEL_STATE_OPEN ||
2205 to_state == CHANNEL_STATE_MAINT) &&
2206 !(from_state == CHANNEL_STATE_OPEN ||
2207 from_state == CHANNEL_STATE_MAINT)) {
2208 estimated_total_queue_size += chan->bytes_in_queue;
2211 if (to_state == CHANNEL_STATE_CLOSED ||
2212 to_state == CHANNEL_STATE_ERROR) {
2213 /* Assert that all queues are empty */
2214 tor_assert(TOR_SIMPLEQ_EMPTY(&chan->incoming_queue));
2215 tor_assert(TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue));
2220 * As channel_change_state_, but change the state to any state but open.
2222 void
2223 channel_change_state(channel_t *chan, channel_state_t to_state)
2225 tor_assert(to_state != CHANNEL_STATE_OPEN);
2226 channel_change_state_(chan, to_state);
2230 * As channel_change_state, but change the state to open.
2232 void
2233 channel_change_state_open(channel_t *chan)
2235 channel_change_state_(chan, CHANNEL_STATE_OPEN);
2237 /* Tell circuits if we opened and stuff */
2238 channel_do_open_actions(chan);
2239 chan->has_been_open = 1;
2241 /* Check for queued cells to process */
2242 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
2243 channel_process_cells(chan);
2244 if (! TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue))
2245 channel_flush_cells(chan);
2249 * Change channel listener state
2251 * This internal and subclass use only function is used to change channel
2252 * listener state, performing all transition validity checks and whatever
2253 * actions are appropriate to the state transition in question.
2256 void
2257 channel_listener_change_state(channel_listener_t *chan_l,
2258 channel_listener_state_t to_state)
2260 channel_listener_state_t from_state;
2261 unsigned char was_active, is_active;
2263 tor_assert(chan_l);
2264 from_state = chan_l->state;
2266 tor_assert(channel_listener_state_is_valid(from_state));
2267 tor_assert(channel_listener_state_is_valid(to_state));
2268 tor_assert(channel_listener_state_can_transition(chan_l->state, to_state));
2270 /* Check for no-op transitions */
2271 if (from_state == to_state) {
2272 log_debug(LD_CHANNEL,
2273 "Got no-op transition from \"%s\" to itself on channel "
2274 "listener %p (global ID " U64_FORMAT ")",
2275 channel_listener_state_to_string(to_state),
2276 chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
2277 return;
2280 /* If we're going to a closing or closed state, we must have a reason set */
2281 if (to_state == CHANNEL_LISTENER_STATE_CLOSING ||
2282 to_state == CHANNEL_LISTENER_STATE_CLOSED ||
2283 to_state == CHANNEL_LISTENER_STATE_ERROR) {
2284 tor_assert(chan_l->reason_for_closing != CHANNEL_LISTENER_NOT_CLOSING);
2288 * We need to maintain the queues here for some transitions:
2289 * when we enter CHANNEL_STATE_OPEN (especially from CHANNEL_STATE_MAINT)
2290 * we may have a backlog of cells to transmit, so drain the queues in
2291 * that case, and when going to CHANNEL_STATE_CLOSED the subclass
2292 * should have made sure to finish sending things (or gone to
2293 * CHANNEL_STATE_ERROR if not possible), so we assert for that here.
2296 log_debug(LD_CHANNEL,
2297 "Changing state of channel listener %p (global ID " U64_FORMAT
2298 "from \"%s\" to \"%s\"",
2299 chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
2300 channel_listener_state_to_string(chan_l->state),
2301 channel_listener_state_to_string(to_state));
2303 chan_l->state = to_state;
2305 /* Need to add to the right lists if the channel listener is registered */
2306 if (chan_l->registered) {
2307 was_active = !(from_state == CHANNEL_LISTENER_STATE_CLOSED ||
2308 from_state == CHANNEL_LISTENER_STATE_ERROR);
2309 is_active = !(to_state == CHANNEL_LISTENER_STATE_CLOSED ||
2310 to_state == CHANNEL_LISTENER_STATE_ERROR);
2312 /* Need to take off active list and put on finished list? */
2313 if (was_active && !is_active) {
2314 if (active_listeners) smartlist_remove(active_listeners, chan_l);
2315 if (!finished_listeners) finished_listeners = smartlist_new();
2316 smartlist_add(finished_listeners, chan_l);
2318 /* Need to put on active list? */
2319 else if (!was_active && is_active) {
2320 if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
2321 if (!active_listeners) active_listeners = smartlist_new();
2322 smartlist_add(active_listeners, chan_l);
2326 if (to_state == CHANNEL_LISTENER_STATE_CLOSED ||
2327 to_state == CHANNEL_LISTENER_STATE_ERROR) {
2328 /* Assert that the queue is empty */
2329 tor_assert(!(chan_l->incoming_list) ||
2330 smartlist_len(chan_l->incoming_list) == 0);
2335 * Try to flush cells to the lower layer
2337 * this is called by the lower layer to indicate that it wants more cells;
2338 * it will try to write up to num_cells cells from the channel's cell queue or
2339 * from circuits active on that channel, or as many as it has available if
2340 * num_cells == -1.
2343 #define MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED 256
2345 MOCK_IMPL(ssize_t,
2346 channel_flush_some_cells, (channel_t *chan, ssize_t num_cells))
2348 unsigned int unlimited = 0;
2349 ssize_t flushed = 0;
2350 int num_cells_from_circs, clamped_num_cells;
2351 int q_len_before, q_len_after;
2353 tor_assert(chan);
2355 if (num_cells < 0) unlimited = 1;
2356 if (!unlimited && num_cells <= flushed) goto done;
2358 /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
2359 if (CHANNEL_IS_OPEN(chan)) {
2360 /* Try to flush as much as we can that's already queued */
2361 flushed += channel_flush_some_cells_from_outgoing_queue(chan,
2362 (unlimited ? -1 : num_cells - flushed));
2363 if (!unlimited && num_cells <= flushed) goto done;
2365 if (circuitmux_num_cells(chan->cmux) > 0) {
2366 /* Calculate number of cells, including clamp */
2367 if (unlimited) {
2368 clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
2369 } else {
2370 if (num_cells - flushed >
2371 MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED) {
2372 clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
2373 } else {
2374 clamped_num_cells = (int)(num_cells - flushed);
2379 * Keep track of the change in queue size; we have to count cells
2380 * channel_flush_from_first_active_circuit() writes out directly,
2381 * but not double-count ones we might get later in
2382 * channel_flush_some_cells_from_outgoing_queue()
2384 q_len_before = chan_cell_queue_len(&(chan->outgoing_queue));
2386 /* Try to get more cells from any active circuits */
2387 num_cells_from_circs = channel_flush_from_first_active_circuit(
2388 chan, clamped_num_cells);
2390 q_len_after = chan_cell_queue_len(&(chan->outgoing_queue));
2393 * If it claims we got some, adjust the flushed counter and consider
2394 * processing the queue again
2396 if (num_cells_from_circs > 0) {
2398 * Adjust flushed by the number of cells counted in
2399 * num_cells_from_circs that didn't go to the cell queue.
2402 if (q_len_after > q_len_before) {
2403 num_cells_from_circs -= (q_len_after - q_len_before);
2404 if (num_cells_from_circs < 0) num_cells_from_circs = 0;
2407 flushed += num_cells_from_circs;
2409 /* Now process the queue if necessary */
2411 if ((q_len_after > q_len_before) &&
2412 (unlimited || (flushed < num_cells))) {
2413 flushed += channel_flush_some_cells_from_outgoing_queue(chan,
2414 (unlimited ? -1 : num_cells - flushed));
2420 done:
2421 return flushed;
2425 * Flush cells from just the channel's outgoing cell queue
2427 * This gets called from channel_flush_some_cells() above to flush cells
2428 * just from the queue without trying for active_circuits.
2431 static ssize_t
2432 channel_flush_some_cells_from_outgoing_queue(channel_t *chan,
2433 ssize_t num_cells)
2435 unsigned int unlimited = 0;
2436 ssize_t flushed = 0;
2437 cell_queue_entry_t *q = NULL;
2438 size_t cell_size;
2439 int free_q = 0, handed_off = 0;
2441 tor_assert(chan);
2442 tor_assert(chan->write_cell);
2443 tor_assert(chan->write_packed_cell);
2444 tor_assert(chan->write_var_cell);
2446 if (num_cells < 0) unlimited = 1;
2447 if (!unlimited && num_cells <= flushed) return 0;
2449 /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
2450 if (CHANNEL_IS_OPEN(chan)) {
2451 while ((unlimited || num_cells > flushed) &&
2452 NULL != (q = TOR_SIMPLEQ_FIRST(&chan->outgoing_queue))) {
2453 free_q = 0;
2454 handed_off = 0;
2456 /* Figure out how big it is for statistical purposes */
2457 cell_size = channel_get_cell_queue_entry_size(chan, q);
2459 * Okay, we have a good queue entry, try to give it to the lower
2460 * layer.
2462 switch (q->type) {
2463 case CELL_QUEUE_FIXED:
2464 if (q->u.fixed.cell) {
2465 if (chan->write_cell(chan,
2466 q->u.fixed.cell)) {
2467 ++flushed;
2468 channel_timestamp_xmit(chan);
2469 ++(chan->n_cells_xmitted);
2470 chan->n_bytes_xmitted += cell_size;
2471 free_q = 1;
2472 handed_off = 1;
2474 /* Else couldn't write it; leave it on the queue */
2475 } else {
2476 /* This shouldn't happen */
2477 log_info(LD_CHANNEL,
2478 "Saw broken cell queue entry of type CELL_QUEUE_FIXED "
2479 "with no cell on channel %p "
2480 "(global ID " U64_FORMAT ").",
2481 chan, U64_PRINTF_ARG(chan->global_identifier));
2482 /* Throw it away */
2483 free_q = 1;
2484 handed_off = 0;
2486 break;
2487 case CELL_QUEUE_PACKED:
2488 if (q->u.packed.packed_cell) {
2489 if (chan->write_packed_cell(chan,
2490 q->u.packed.packed_cell)) {
2491 ++flushed;
2492 channel_timestamp_xmit(chan);
2493 ++(chan->n_cells_xmitted);
2494 chan->n_bytes_xmitted += cell_size;
2495 free_q = 1;
2496 handed_off = 1;
2498 /* Else couldn't write it; leave it on the queue */
2499 } else {
2500 /* This shouldn't happen */
2501 log_info(LD_CHANNEL,
2502 "Saw broken cell queue entry of type CELL_QUEUE_PACKED "
2503 "with no cell on channel %p "
2504 "(global ID " U64_FORMAT ").",
2505 chan, U64_PRINTF_ARG(chan->global_identifier));
2506 /* Throw it away */
2507 free_q = 1;
2508 handed_off = 0;
2510 break;
2511 case CELL_QUEUE_VAR:
2512 if (q->u.var.var_cell) {
2513 if (chan->write_var_cell(chan,
2514 q->u.var.var_cell)) {
2515 ++flushed;
2516 channel_timestamp_xmit(chan);
2517 ++(chan->n_cells_xmitted);
2518 chan->n_bytes_xmitted += cell_size;
2519 free_q = 1;
2520 handed_off = 1;
2522 /* Else couldn't write it; leave it on the queue */
2523 } else {
2524 /* This shouldn't happen */
2525 log_info(LD_CHANNEL,
2526 "Saw broken cell queue entry of type CELL_QUEUE_VAR "
2527 "with no cell on channel %p "
2528 "(global ID " U64_FORMAT ").",
2529 chan, U64_PRINTF_ARG(chan->global_identifier));
2530 /* Throw it away */
2531 free_q = 1;
2532 handed_off = 0;
2534 break;
2535 default:
2536 /* Unknown type, log and free it */
2537 log_info(LD_CHANNEL,
2538 "Saw an unknown cell queue entry type %d on channel %p "
2539 "(global ID " U64_FORMAT "; ignoring it."
2540 " Someone should fix this.",
2541 q->type, chan, U64_PRINTF_ARG(chan->global_identifier));
2542 free_q = 1;
2543 handed_off = 0;
2547 * if free_q is set, we used it and should remove the queue entry;
2548 * we have to do the free down here so TOR_SIMPLEQ_REMOVE_HEAD isn't
2549 * accessing freed memory
2551 if (free_q) {
2552 TOR_SIMPLEQ_REMOVE_HEAD(&chan->outgoing_queue, next);
2554 * ...and we handed a cell off to the lower layer, so we should
2555 * update the counters.
2557 ++n_channel_cells_passed_to_lower_layer;
2558 --n_channel_cells_in_queues;
2559 n_channel_bytes_passed_to_lower_layer += cell_size;
2560 n_channel_bytes_in_queues -= cell_size;
2561 channel_assert_counter_consistency();
2562 /* Update the channel's queue size too */
2563 chan->bytes_in_queue -= cell_size;
2564 /* Finally, free q */
2565 cell_queue_entry_free(q, handed_off);
2566 q = NULL;
2567 } else {
2568 /* No cell removed from list, so we can't go on any further */
2569 break;
2574 /* Did we drain the queue? */
2575 if (TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue)) {
2576 channel_timestamp_drained(chan);
2579 /* Update the estimate queue size */
2580 channel_update_xmit_queue_size(chan);
2582 return flushed;
2586 * Flush as many cells as we possibly can from the queue
2588 * This tries to flush as many cells from the queue as the lower layer
2589 * will take. It just calls channel_flush_some_cells_from_outgoing_queue()
2590 * in unlimited mode.
2593 void
2594 channel_flush_cells(channel_t *chan)
2596 channel_flush_some_cells_from_outgoing_queue(chan, -1);
2600 * Check if any cells are available
2602 * This gets used from the lower layer to check if any more cells are
2603 * available.
2606 MOCK_IMPL(int,
2607 channel_more_to_flush, (channel_t *chan))
2609 tor_assert(chan);
2611 /* Check if we have any queued */
2612 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
2613 return 1;
2615 /* Check if any circuits would like to queue some */
2616 if (circuitmux_num_cells(chan->cmux) > 0) return 1;
2618 /* Else no */
2619 return 0;
2623 * Notify the channel we're done flushing the output in the lower layer
2625 * Connection.c will call this when we've flushed the output; there's some
2626 * dirreq-related maintenance to do.
2629 void
2630 channel_notify_flushed(channel_t *chan)
2632 tor_assert(chan);
2634 if (chan->dirreq_id != 0)
2635 geoip_change_dirreq_state(chan->dirreq_id,
2636 DIRREQ_TUNNELED,
2637 DIRREQ_CHANNEL_BUFFER_FLUSHED);
2641 * Process the queue of incoming channels on a listener
2643 * Use a listener's registered callback to process as many entries in the
2644 * queue of incoming channels as possible.
2647 void
2648 channel_listener_process_incoming(channel_listener_t *listener)
2650 tor_assert(listener);
2653 * CHANNEL_LISTENER_STATE_CLOSING permitted because we drain the queue
2654 * while closing a listener.
2656 tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING ||
2657 listener->state == CHANNEL_LISTENER_STATE_CLOSING);
2658 tor_assert(listener->listener);
2660 log_debug(LD_CHANNEL,
2661 "Processing queue of incoming connections for channel "
2662 "listener %p (global ID " U64_FORMAT ")",
2663 listener, U64_PRINTF_ARG(listener->global_identifier));
2665 if (!(listener->incoming_list)) return;
2667 SMARTLIST_FOREACH_BEGIN(listener->incoming_list,
2668 channel_t *, chan) {
2669 tor_assert(chan);
2671 log_debug(LD_CHANNEL,
2672 "Handling incoming channel %p (" U64_FORMAT ") "
2673 "for listener %p (" U64_FORMAT ")",
2674 chan,
2675 U64_PRINTF_ARG(chan->global_identifier),
2676 listener,
2677 U64_PRINTF_ARG(listener->global_identifier));
2678 /* Make sure this is set correctly */
2679 channel_mark_incoming(chan);
2680 listener->listener(listener, chan);
2681 } SMARTLIST_FOREACH_END(chan);
2683 smartlist_free(listener->incoming_list);
2684 listener->incoming_list = NULL;
2688 * Take actions required when a channel becomes open
2690 * Handle actions we should do when we know a channel is open; a lot of
2691 * this comes from the old connection_or_set_state_open() of connection_or.c.
2693 * Because of this mechanism, future channel_t subclasses should take care
2694 * not to change a channel to from CHANNEL_STATE_OPENING to CHANNEL_STATE_OPEN
2695 * until there is positive confirmation that the network is operational.
2696 * In particular, anything UDP-based should not make this transition until a
2697 * packet is received from the other side.
2700 void
2701 channel_do_open_actions(channel_t *chan)
2703 tor_addr_t remote_addr;
2704 int started_here;
2705 time_t now = time(NULL);
2706 int close_origin_circuits = 0;
2708 tor_assert(chan);
2710 started_here = channel_is_outgoing(chan);
2712 if (started_here) {
2713 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
2714 rep_hist_note_connect_succeeded(chan->identity_digest, now);
2715 router_set_status(chan->identity_digest, 1);
2716 } else {
2717 /* only report it to the geoip module if it's not a known router */
2718 if (!connection_or_digest_is_known_relay(chan->identity_digest)) {
2719 if (channel_get_addr_if_possible(chan, &remote_addr)) {
2720 char *transport_name = NULL;
2721 if (chan->get_transport_name(chan, &transport_name) < 0)
2722 transport_name = NULL;
2724 geoip_note_client_seen(GEOIP_CLIENT_CONNECT,
2725 &remote_addr, transport_name,
2726 now);
2727 tor_free(transport_name);
2729 /* Otherwise the underlying transport can't tell us this, so skip it */
2733 /* Disable or reduce padding according to user prefs. */
2734 if (chan->padding_enabled || get_options()->ConnectionPadding == 1) {
2735 if (!get_options()->ConnectionPadding) {
2736 /* Disable if torrc disabled */
2737 channelpadding_disable_padding_on_channel(chan);
2738 } else if (get_options()->Tor2webMode &&
2739 !networkstatus_get_param(NULL,
2740 CHANNELPADDING_TOR2WEB_PARAM,
2741 CHANNELPADDING_TOR2WEB_DEFAULT, 0, 1)) {
2742 /* Disable if we're using tor2web and the consensus disabled padding
2743 * for tor2web */
2744 channelpadding_disable_padding_on_channel(chan);
2745 } else if (rend_service_allow_non_anonymous_connection(get_options()) &&
2746 !networkstatus_get_param(NULL,
2747 CHANNELPADDING_SOS_PARAM,
2748 CHANNELPADDING_SOS_DEFAULT, 0, 1)) {
2749 /* Disable if we're using RSOS and the consensus disabled padding
2750 * for RSOS*/
2751 channelpadding_disable_padding_on_channel(chan);
2752 } else if (get_options()->ReducedConnectionPadding) {
2753 /* Padding can be forced and/or reduced by clients, regardless of if
2754 * the channel supports it */
2755 channelpadding_reduce_padding_on_channel(chan);
2759 circuit_n_chan_done(chan, 1, close_origin_circuits);
2763 * Queue an incoming channel on a listener
2765 * Internal and subclass use only function to queue an incoming channel from
2766 * a listener. A subclass of channel_listener_t should call this when a new
2767 * incoming channel is created.
2770 void
2771 channel_listener_queue_incoming(channel_listener_t *listener,
2772 channel_t *incoming)
2774 int need_to_queue = 0;
2776 tor_assert(listener);
2777 tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING);
2778 tor_assert(incoming);
2780 log_debug(LD_CHANNEL,
2781 "Queueing incoming channel %p (global ID " U64_FORMAT ") on "
2782 "channel listener %p (global ID " U64_FORMAT ")",
2783 incoming, U64_PRINTF_ARG(incoming->global_identifier),
2784 listener, U64_PRINTF_ARG(listener->global_identifier));
2786 /* Do we need to queue it, or can we just call the listener right away? */
2787 if (!(listener->listener)) need_to_queue = 1;
2788 if (listener->incoming_list &&
2789 (smartlist_len(listener->incoming_list) > 0))
2790 need_to_queue = 1;
2792 /* If we need to queue and have no queue, create one */
2793 if (need_to_queue && !(listener->incoming_list)) {
2794 listener->incoming_list = smartlist_new();
2797 /* Bump the counter and timestamp it */
2798 channel_listener_timestamp_active(listener);
2799 channel_listener_timestamp_accepted(listener);
2800 ++(listener->n_accepted);
2802 /* If we don't need to queue, process it right away */
2803 if (!need_to_queue) {
2804 tor_assert(listener->listener);
2805 listener->listener(listener, incoming);
2808 * Otherwise, we need to queue; queue and then process the queue if
2809 * we can.
2811 else {
2812 tor_assert(listener->incoming_list);
2813 smartlist_add(listener->incoming_list, incoming);
2814 if (listener->listener) channel_listener_process_incoming(listener);
2819 * Process queued incoming cells
2821 * Process as many queued cells as we can from the incoming
2822 * cell queue.
2825 void
2826 channel_process_cells(channel_t *chan)
2828 cell_queue_entry_t *q;
2829 tor_assert(chan);
2830 tor_assert(CHANNEL_IS_CLOSING(chan) || CHANNEL_IS_MAINT(chan) ||
2831 CHANNEL_IS_OPEN(chan));
2833 log_debug(LD_CHANNEL,
2834 "Processing as many incoming cells as we can for channel %p",
2835 chan);
2837 /* Nothing we can do if we have no registered cell handlers */
2838 if (!(chan->cell_handler ||
2839 chan->var_cell_handler)) return;
2840 /* Nothing we can do if we have no cells */
2841 if (TOR_SIMPLEQ_EMPTY(&chan->incoming_queue)) return;
2844 * Process cells until we're done or find one we have no current handler
2845 * for.
2847 * We must free the cells here after calling the handler, since custody
2848 * of the buffer was given to the channel layer when they were queued;
2849 * see comments on memory management in channel_queue_cell() and in
2850 * channel_queue_var_cell() below.
2852 while (NULL != (q = TOR_SIMPLEQ_FIRST(&chan->incoming_queue))) {
2853 tor_assert(q);
2854 tor_assert(q->type == CELL_QUEUE_FIXED ||
2855 q->type == CELL_QUEUE_VAR);
2857 if (q->type == CELL_QUEUE_FIXED &&
2858 chan->cell_handler) {
2859 /* Handle a fixed-length cell */
2860 TOR_SIMPLEQ_REMOVE_HEAD(&chan->incoming_queue, next);
2861 tor_assert(q->u.fixed.cell);
2862 log_debug(LD_CHANNEL,
2863 "Processing incoming cell_t %p for channel %p (global ID "
2864 U64_FORMAT ")",
2865 q->u.fixed.cell, chan,
2866 U64_PRINTF_ARG(chan->global_identifier));
2867 chan->cell_handler(chan, q->u.fixed.cell);
2868 tor_free(q->u.fixed.cell);
2869 tor_free(q);
2870 } else if (q->type == CELL_QUEUE_VAR &&
2871 chan->var_cell_handler) {
2872 /* Handle a variable-length cell */
2873 TOR_SIMPLEQ_REMOVE_HEAD(&chan->incoming_queue, next);
2874 tor_assert(q->u.var.var_cell);
2875 log_debug(LD_CHANNEL,
2876 "Processing incoming var_cell_t %p for channel %p (global ID "
2877 U64_FORMAT ")",
2878 q->u.var.var_cell, chan,
2879 U64_PRINTF_ARG(chan->global_identifier));
2880 chan->var_cell_handler(chan, q->u.var.var_cell);
2881 tor_free(q->u.var.var_cell);
2882 tor_free(q);
2883 } else {
2884 /* Can't handle this one */
2885 break;
2891 * Queue incoming cell
2893 * This should be called by a channel_t subclass to queue an incoming fixed-
2894 * length cell for processing, and process it if possible.
2897 void
2898 channel_queue_cell(channel_t *chan, cell_t *cell)
2900 int need_to_queue = 0;
2901 cell_queue_entry_t *q;
2902 cell_t *cell_copy = NULL;
2904 tor_assert(chan);
2905 tor_assert(cell);
2906 tor_assert(CHANNEL_IS_OPEN(chan));
2908 /* Do we need to queue it, or can we just call the handler right away? */
2909 if (!(chan->cell_handler)) need_to_queue = 1;
2910 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
2911 need_to_queue = 1;
2913 /* Timestamp for receiving */
2914 channel_timestamp_recv(chan);
2916 /* Update the counters */
2917 ++(chan->n_cells_recved);
2918 chan->n_bytes_recved += get_cell_network_size(chan->wide_circ_ids);
2920 /* If we don't need to queue we can just call cell_handler */
2921 if (!need_to_queue) {
2922 tor_assert(chan->cell_handler);
2923 log_debug(LD_CHANNEL,
2924 "Directly handling incoming cell_t %p for channel %p "
2925 "(global ID " U64_FORMAT ")",
2926 cell, chan,
2927 U64_PRINTF_ARG(chan->global_identifier));
2928 chan->cell_handler(chan, cell);
2929 } else {
2931 * Otherwise queue it and then process the queue if possible.
2933 * We queue a copy, not the original pointer - it might have been on the
2934 * stack in connection_or_process_cells_from_inbuf() (or another caller
2935 * if we ever have a subclass other than channel_tls_t), or be freed
2936 * there after we return. This is the uncommon case; the non-copying
2937 * fast path occurs in the if (!need_to_queue) case above when the
2938 * upper layer has installed cell handlers.
2940 cell_copy = tor_malloc_zero(sizeof(cell_t));
2941 memcpy(cell_copy, cell, sizeof(cell_t));
2942 q = cell_queue_entry_new_fixed(cell_copy);
2943 log_debug(LD_CHANNEL,
2944 "Queueing incoming cell_t %p for channel %p "
2945 "(global ID " U64_FORMAT ")",
2946 cell, chan,
2947 U64_PRINTF_ARG(chan->global_identifier));
2948 TOR_SIMPLEQ_INSERT_TAIL(&chan->incoming_queue, q, next);
2949 if (chan->cell_handler ||
2950 chan->var_cell_handler) {
2951 channel_process_cells(chan);
2957 * Queue incoming variable-length cell
2959 * This should be called by a channel_t subclass to queue an incoming
2960 * variable-length cell for processing, and process it if possible.
2963 void
2964 channel_queue_var_cell(channel_t *chan, var_cell_t *var_cell)
2966 int need_to_queue = 0;
2967 cell_queue_entry_t *q;
2968 var_cell_t *cell_copy = NULL;
2970 tor_assert(chan);
2971 tor_assert(var_cell);
2972 tor_assert(CHANNEL_IS_OPEN(chan));
2974 /* Do we need to queue it, or can we just call the handler right away? */
2975 if (!(chan->var_cell_handler)) need_to_queue = 1;
2976 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
2977 need_to_queue = 1;
2979 /* Timestamp for receiving */
2980 channel_timestamp_recv(chan);
2982 /* Update the counter */
2983 ++(chan->n_cells_recved);
2984 chan->n_bytes_recved += get_var_cell_header_size(chan->wide_circ_ids) +
2985 var_cell->payload_len;
2987 /* If we don't need to queue we can just call cell_handler */
2988 if (!need_to_queue) {
2989 tor_assert(chan->var_cell_handler);
2990 log_debug(LD_CHANNEL,
2991 "Directly handling incoming var_cell_t %p for channel %p "
2992 "(global ID " U64_FORMAT ")",
2993 var_cell, chan,
2994 U64_PRINTF_ARG(chan->global_identifier));
2995 chan->var_cell_handler(chan, var_cell);
2996 } else {
2998 * Otherwise queue it and then process the queue if possible.
3000 * We queue a copy, not the original pointer - it might have been on the
3001 * stack in connection_or_process_cells_from_inbuf() (or another caller
3002 * if we ever have a subclass other than channel_tls_t), or be freed
3003 * there after we return. This is the uncommon case; the non-copying
3004 * fast path occurs in the if (!need_to_queue) case above when the
3005 * upper layer has installed cell handlers.
3007 cell_copy = var_cell_copy(var_cell);
3008 q = cell_queue_entry_new_var(cell_copy);
3009 log_debug(LD_CHANNEL,
3010 "Queueing incoming var_cell_t %p for channel %p "
3011 "(global ID " U64_FORMAT ")",
3012 var_cell, chan,
3013 U64_PRINTF_ARG(chan->global_identifier));
3014 TOR_SIMPLEQ_INSERT_TAIL(&chan->incoming_queue, q, next);
3015 if (chan->cell_handler ||
3016 chan->var_cell_handler) {
3017 channel_process_cells(chan);
3022 /** If <b>packed_cell</b> on <b>chan</b> is a destroy cell, then set
3023 * *<b>circid_out</b> to its circuit ID, and return true. Otherwise, return
3024 * false. */
3025 /* XXXX Move this function. */
3027 packed_cell_is_destroy(channel_t *chan,
3028 const packed_cell_t *packed_cell,
3029 circid_t *circid_out)
3031 if (chan->wide_circ_ids) {
3032 if (packed_cell->body[4] == CELL_DESTROY) {
3033 *circid_out = ntohl(get_uint32(packed_cell->body));
3034 return 1;
3036 } else {
3037 if (packed_cell->body[2] == CELL_DESTROY) {
3038 *circid_out = ntohs(get_uint16(packed_cell->body));
3039 return 1;
3042 return 0;
3046 * Assert that the global channel stats counters are internally consistent
3049 static void
3050 channel_assert_counter_consistency(void)
3052 tor_assert(n_channel_cells_queued ==
3053 (n_channel_cells_in_queues + n_channel_cells_passed_to_lower_layer));
3054 tor_assert(n_channel_bytes_queued ==
3055 (n_channel_bytes_in_queues + n_channel_bytes_passed_to_lower_layer));
3058 /* DOCDOC */
3059 static int
3060 is_destroy_cell(channel_t *chan,
3061 const cell_queue_entry_t *q, circid_t *circid_out)
3063 *circid_out = 0;
3064 switch (q->type) {
3065 case CELL_QUEUE_FIXED:
3066 if (q->u.fixed.cell->command == CELL_DESTROY) {
3067 *circid_out = q->u.fixed.cell->circ_id;
3068 return 1;
3070 break;
3071 case CELL_QUEUE_VAR:
3072 if (q->u.var.var_cell->command == CELL_DESTROY) {
3073 *circid_out = q->u.var.var_cell->circ_id;
3074 return 1;
3076 break;
3077 case CELL_QUEUE_PACKED:
3078 return packed_cell_is_destroy(chan, q->u.packed.packed_cell, circid_out);
3080 return 0;
3084 * Send destroy cell on a channel
3086 * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
3087 * onto channel <b>chan</b>. Don't perform range-checking on reason:
3088 * we may want to propagate reasons from other cells.
3092 channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
3094 tor_assert(chan);
3095 if (circ_id == 0) {
3096 log_warn(LD_BUG, "Attempted to send a destroy cell for circID 0 "
3097 "on a channel " U64_FORMAT " at %p in state %s (%d)",
3098 U64_PRINTF_ARG(chan->global_identifier),
3099 chan, channel_state_to_string(chan->state),
3100 chan->state);
3101 return 0;
3104 /* Check to make sure we can send on this channel first */
3105 if (!CHANNEL_CONDEMNED(chan) && chan->cmux) {
3106 channel_note_destroy_pending(chan, circ_id);
3107 circuitmux_append_destroy_cell(chan, chan->cmux, circ_id, reason);
3108 log_debug(LD_OR,
3109 "Sending destroy (circID %u) on channel %p "
3110 "(global ID " U64_FORMAT ")",
3111 (unsigned)circ_id, chan,
3112 U64_PRINTF_ARG(chan->global_identifier));
3113 } else {
3114 log_warn(LD_BUG,
3115 "Someone called channel_send_destroy() for circID %u "
3116 "on a channel " U64_FORMAT " at %p in state %s (%d)",
3117 (unsigned)circ_id, U64_PRINTF_ARG(chan->global_identifier),
3118 chan, channel_state_to_string(chan->state),
3119 chan->state);
3122 return 0;
3126 * Dump channel statistics to the log
3128 * This is called from dumpstats() in main.c and spams the log with
3129 * statistics on channels.
3132 void
3133 channel_dumpstats(int severity)
3135 if (all_channels && smartlist_len(all_channels) > 0) {
3136 tor_log(severity, LD_GENERAL,
3137 "Channels have queued " U64_FORMAT " bytes in " U64_FORMAT " cells, "
3138 "and handed " U64_FORMAT " bytes in " U64_FORMAT " cells to the lower"
3139 " layer.",
3140 U64_PRINTF_ARG(n_channel_bytes_queued),
3141 U64_PRINTF_ARG(n_channel_cells_queued),
3142 U64_PRINTF_ARG(n_channel_bytes_passed_to_lower_layer),
3143 U64_PRINTF_ARG(n_channel_cells_passed_to_lower_layer));
3144 tor_log(severity, LD_GENERAL,
3145 "There are currently " U64_FORMAT " bytes in " U64_FORMAT " cells "
3146 "in channel queues.",
3147 U64_PRINTF_ARG(n_channel_bytes_in_queues),
3148 U64_PRINTF_ARG(n_channel_cells_in_queues));
3149 tor_log(severity, LD_GENERAL,
3150 "Dumping statistics about %d channels:",
3151 smartlist_len(all_channels));
3152 tor_log(severity, LD_GENERAL,
3153 "%d are active, and %d are done and waiting for cleanup",
3154 (active_channels != NULL) ?
3155 smartlist_len(active_channels) : 0,
3156 (finished_channels != NULL) ?
3157 smartlist_len(finished_channels) : 0);
3159 SMARTLIST_FOREACH(all_channels, channel_t *, chan,
3160 channel_dump_statistics(chan, severity));
3162 tor_log(severity, LD_GENERAL,
3163 "Done spamming about channels now");
3164 } else {
3165 tor_log(severity, LD_GENERAL,
3166 "No channels to dump");
3171 * Dump channel listener statistics to the log
3173 * This is called from dumpstats() in main.c and spams the log with
3174 * statistics on channel listeners.
3177 void
3178 channel_listener_dumpstats(int severity)
3180 if (all_listeners && smartlist_len(all_listeners) > 0) {
3181 tor_log(severity, LD_GENERAL,
3182 "Dumping statistics about %d channel listeners:",
3183 smartlist_len(all_listeners));
3184 tor_log(severity, LD_GENERAL,
3185 "%d are active and %d are done and waiting for cleanup",
3186 (active_listeners != NULL) ?
3187 smartlist_len(active_listeners) : 0,
3188 (finished_listeners != NULL) ?
3189 smartlist_len(finished_listeners) : 0);
3191 SMARTLIST_FOREACH(all_listeners, channel_listener_t *, chan_l,
3192 channel_listener_dump_statistics(chan_l, severity));
3194 tor_log(severity, LD_GENERAL,
3195 "Done spamming about channel listeners now");
3196 } else {
3197 tor_log(severity, LD_GENERAL,
3198 "No channel listeners to dump");
3203 * Set the cmux policy on all active channels
3206 void
3207 channel_set_cmux_policy_everywhere(circuitmux_policy_t *pol)
3209 if (!active_channels) return;
3211 SMARTLIST_FOREACH_BEGIN(active_channels, channel_t *, curr) {
3212 if (curr->cmux) {
3213 circuitmux_set_policy(curr->cmux, pol);
3215 } SMARTLIST_FOREACH_END(curr);
3219 * Clean up channels
3221 * This gets called periodically from run_scheduled_events() in main.c;
3222 * it cleans up after closed channels.
3225 void
3226 channel_run_cleanup(void)
3228 channel_t *tmp = NULL;
3230 /* Check if we need to do anything */
3231 if (!finished_channels || smartlist_len(finished_channels) == 0) return;
3233 /* Iterate through finished_channels and get rid of them */
3234 SMARTLIST_FOREACH_BEGIN(finished_channels, channel_t *, curr) {
3235 tmp = curr;
3236 /* Remove it from the list */
3237 SMARTLIST_DEL_CURRENT(finished_channels, curr);
3238 /* Also unregister it */
3239 channel_unregister(tmp);
3240 /* ... and free it */
3241 channel_free(tmp);
3242 } SMARTLIST_FOREACH_END(curr);
3246 * Clean up channel listeners
3248 * This gets called periodically from run_scheduled_events() in main.c;
3249 * it cleans up after closed channel listeners.
3252 void
3253 channel_listener_run_cleanup(void)
3255 channel_listener_t *tmp = NULL;
3257 /* Check if we need to do anything */
3258 if (!finished_listeners || smartlist_len(finished_listeners) == 0) return;
3260 /* Iterate through finished_channels and get rid of them */
3261 SMARTLIST_FOREACH_BEGIN(finished_listeners, channel_listener_t *, curr) {
3262 tmp = curr;
3263 /* Remove it from the list */
3264 SMARTLIST_DEL_CURRENT(finished_listeners, curr);
3265 /* Also unregister it */
3266 channel_listener_unregister(tmp);
3267 /* ... and free it */
3268 channel_listener_free(tmp);
3269 } SMARTLIST_FOREACH_END(curr);
3273 * Free a list of channels for channel_free_all()
3276 static void
3277 channel_free_list(smartlist_t *channels, int mark_for_close)
3279 if (!channels) return;
3281 SMARTLIST_FOREACH_BEGIN(channels, channel_t *, curr) {
3282 /* Deregister and free it */
3283 tor_assert(curr);
3284 log_debug(LD_CHANNEL,
3285 "Cleaning up channel %p (global ID " U64_FORMAT ") "
3286 "in state %s (%d)",
3287 curr, U64_PRINTF_ARG(curr->global_identifier),
3288 channel_state_to_string(curr->state), curr->state);
3289 /* Detach circuits early so they can find the channel */
3290 if (curr->cmux) {
3291 circuitmux_detach_all_circuits(curr->cmux, NULL);
3293 SMARTLIST_DEL_CURRENT(channels, curr);
3294 channel_unregister(curr);
3295 if (mark_for_close) {
3296 if (!CHANNEL_CONDEMNED(curr)) {
3297 channel_mark_for_close(curr);
3299 channel_force_free(curr);
3300 } else channel_free(curr);
3301 } SMARTLIST_FOREACH_END(curr);
3305 * Free a list of channel listeners for channel_free_all()
3308 static void
3309 channel_listener_free_list(smartlist_t *listeners, int mark_for_close)
3311 if (!listeners) return;
3313 SMARTLIST_FOREACH_BEGIN(listeners, channel_listener_t *, curr) {
3314 /* Deregister and free it */
3315 tor_assert(curr);
3316 log_debug(LD_CHANNEL,
3317 "Cleaning up channel listener %p (global ID " U64_FORMAT ") "
3318 "in state %s (%d)",
3319 curr, U64_PRINTF_ARG(curr->global_identifier),
3320 channel_listener_state_to_string(curr->state), curr->state);
3321 channel_listener_unregister(curr);
3322 if (mark_for_close) {
3323 if (!(curr->state == CHANNEL_LISTENER_STATE_CLOSING ||
3324 curr->state == CHANNEL_LISTENER_STATE_CLOSED ||
3325 curr->state == CHANNEL_LISTENER_STATE_ERROR)) {
3326 channel_listener_mark_for_close(curr);
3328 channel_listener_force_free(curr);
3329 } else channel_listener_free(curr);
3330 } SMARTLIST_FOREACH_END(curr);
3334 * Close all channels and free everything
3336 * This gets called from tor_free_all() in main.c to clean up on exit.
3337 * It will close all registered channels and free associated storage,
3338 * then free the all_channels, active_channels, listening_channels and
3339 * finished_channels lists and also channel_identity_map.
3342 void
3343 channel_free_all(void)
3345 log_debug(LD_CHANNEL,
3346 "Shutting down channels...");
3348 /* First, let's go for finished channels */
3349 if (finished_channels) {
3350 channel_free_list(finished_channels, 0);
3351 smartlist_free(finished_channels);
3352 finished_channels = NULL;
3355 /* Now the finished listeners */
3356 if (finished_listeners) {
3357 channel_listener_free_list(finished_listeners, 0);
3358 smartlist_free(finished_listeners);
3359 finished_listeners = NULL;
3362 /* Now all active channels */
3363 if (active_channels) {
3364 channel_free_list(active_channels, 1);
3365 smartlist_free(active_channels);
3366 active_channels = NULL;
3369 /* Now all active listeners */
3370 if (active_listeners) {
3371 channel_listener_free_list(active_listeners, 1);
3372 smartlist_free(active_listeners);
3373 active_listeners = NULL;
3376 /* Now all channels, in case any are left over */
3377 if (all_channels) {
3378 channel_free_list(all_channels, 1);
3379 smartlist_free(all_channels);
3380 all_channels = NULL;
3383 /* Now all listeners, in case any are left over */
3384 if (all_listeners) {
3385 channel_listener_free_list(all_listeners, 1);
3386 smartlist_free(all_listeners);
3387 all_listeners = NULL;
3390 /* Now free channel_identity_map */
3391 log_debug(LD_CHANNEL,
3392 "Freeing channel_identity_map");
3393 /* Geez, anything still left over just won't die ... let it leak then */
3394 HT_CLEAR(channel_idmap, &channel_identity_map);
3396 /* Same with channel_gid_map */
3397 log_debug(LD_CHANNEL,
3398 "Freeing channel_gid_map");
3399 HT_CLEAR(channel_gid_map, &channel_gid_map);
3401 log_debug(LD_CHANNEL,
3402 "Done cleaning up after channels");
3406 * Connect to a given addr/port/digest
3408 * This sets up a new outgoing channel; in the future if multiple
3409 * channel_t subclasses are available, this is where the selection policy
3410 * should go. It may also be desirable to fold port into tor_addr_t
3411 * or make a new type including a tor_addr_t and port, so we have a
3412 * single abstract object encapsulating all the protocol details of
3413 * how to contact an OR.
3416 channel_t *
3417 channel_connect(const tor_addr_t *addr, uint16_t port,
3418 const char *id_digest,
3419 const ed25519_public_key_t *ed_id)
3421 return channel_tls_connect(addr, port, id_digest, ed_id);
3425 * Decide which of two channels to prefer for extending a circuit
3427 * This function is called while extending a circuit and returns true iff
3428 * a is 'better' than b. The most important criterion here is that a
3429 * canonical channel is always better than a non-canonical one, but the
3430 * number of circuits and the age are used as tie-breakers.
3432 * This is based on the former connection_or_is_better() of connection_or.c
3436 channel_is_better(channel_t *a, channel_t *b)
3438 int a_is_canonical, b_is_canonical;
3440 tor_assert(a);
3441 tor_assert(b);
3443 /* If one channel is bad for new circuits, and the other isn't,
3444 * use the one that is still good. */
3445 if (!channel_is_bad_for_new_circs(a) && channel_is_bad_for_new_circs(b))
3446 return 1;
3447 if (channel_is_bad_for_new_circs(a) && !channel_is_bad_for_new_circs(b))
3448 return 0;
3450 /* Check if one is canonical and the other isn't first */
3451 a_is_canonical = channel_is_canonical(a);
3452 b_is_canonical = channel_is_canonical(b);
3454 if (a_is_canonical && !b_is_canonical) return 1;
3455 if (!a_is_canonical && b_is_canonical) return 0;
3457 /* Check if we suspect that one of the channels will be preferred
3458 * by the peer */
3459 if (a->is_canonical_to_peer && !b->is_canonical_to_peer) return 1;
3460 if (!a->is_canonical_to_peer && b->is_canonical_to_peer) return 0;
3463 * Okay, if we're here they tied on canonicity, the prefer the older
3464 * connection, so that the adversary can't create a new connection
3465 * and try to switch us over to it (which will leak information
3466 * about long-lived circuits). Additionally, switching connections
3467 * too often makes us more vulnerable to attacks like Torscan and
3468 * passive netflow-based equivalents.
3470 * Connections will still only live for at most a week, due to
3471 * the check in connection_or_group_set_badness() against
3472 * TIME_BEFORE_OR_CONN_IS_TOO_OLD, which marks old connections as
3473 * unusable for new circuits after 1 week. That check sets
3474 * is_bad_for_new_circs, which is checked in channel_get_for_extend().
3476 * We check channel_is_bad_for_new_circs() above here anyway, for safety.
3478 if (channel_when_created(a) < channel_when_created(b)) return 1;
3479 else if (channel_when_created(a) > channel_when_created(b)) return 0;
3481 if (channel_num_circuits(a) > channel_num_circuits(b)) return 1;
3482 else return 0;
3486 * Get a channel to extend a circuit
3488 * Pick a suitable channel to extend a circuit to given the desired digest
3489 * the address we believe is correct for that digest; this tries to see
3490 * if we already have one for the requested endpoint, but if there is no good
3491 * channel, set *msg_out to a message describing the channel's state
3492 * and our next action, and set *launch_out to a boolean indicated whether
3493 * the caller should try to launch a new channel with channel_connect().
3496 channel_t *
3497 channel_get_for_extend(const char *rsa_id_digest,
3498 const ed25519_public_key_t *ed_id,
3499 const tor_addr_t *target_addr,
3500 const char **msg_out,
3501 int *launch_out)
3503 channel_t *chan, *best = NULL;
3504 int n_inprogress_goodaddr = 0, n_old = 0;
3505 int n_noncanonical = 0, n_possible = 0;
3507 tor_assert(msg_out);
3508 tor_assert(launch_out);
3510 chan = channel_find_by_remote_identity(rsa_id_digest, ed_id);
3512 /* Walk the list, unrefing the old one and refing the new at each
3513 * iteration.
3515 for (; chan; chan = channel_next_with_rsa_identity(chan)) {
3516 tor_assert(tor_memeq(chan->identity_digest,
3517 rsa_id_digest, DIGEST_LEN));
3519 if (CHANNEL_CONDEMNED(chan))
3520 continue;
3522 /* Never return a channel on which the other end appears to be
3523 * a client. */
3524 if (channel_is_client(chan)) {
3525 continue;
3528 /* The Ed25519 key has to match too */
3529 if (!channel_remote_identity_matches(chan, rsa_id_digest, ed_id)) {
3530 continue;
3533 /* Never return a non-open connection. */
3534 if (!CHANNEL_IS_OPEN(chan)) {
3535 /* If the address matches, don't launch a new connection for this
3536 * circuit. */
3537 if (channel_matches_target_addr_for_extend(chan, target_addr))
3538 ++n_inprogress_goodaddr;
3539 continue;
3542 /* Never return a connection that shouldn't be used for circs. */
3543 if (channel_is_bad_for_new_circs(chan)) {
3544 ++n_old;
3545 continue;
3548 /* Never return a non-canonical connection using a recent link protocol
3549 * if the address is not what we wanted.
3551 * The channel_is_canonical_is_reliable() function asks the lower layer
3552 * if we should trust channel_is_canonical(). The below is from the
3553 * comments of the old circuit_or_get_for_extend() and applies when
3554 * the lower-layer transport is channel_tls_t.
3556 * (For old link protocols, we can't rely on is_canonical getting
3557 * set properly if we're talking to the right address, since we might
3558 * have an out-of-date descriptor, and we will get no NETINFO cell to
3559 * tell us about the right address.)
3561 if (!channel_is_canonical(chan) &&
3562 channel_is_canonical_is_reliable(chan) &&
3563 !channel_matches_target_addr_for_extend(chan, target_addr)) {
3564 ++n_noncanonical;
3565 continue;
3568 ++n_possible;
3570 if (!best) {
3571 best = chan; /* If we have no 'best' so far, this one is good enough. */
3572 continue;
3575 if (channel_is_better(chan, best))
3576 best = chan;
3579 if (best) {
3580 *msg_out = "Connection is fine; using it.";
3581 *launch_out = 0;
3582 return best;
3583 } else if (n_inprogress_goodaddr) {
3584 *msg_out = "Connection in progress; waiting.";
3585 *launch_out = 0;
3586 return NULL;
3587 } else if (n_old || n_noncanonical) {
3588 *msg_out = "Connections all too old, or too non-canonical. "
3589 " Launching a new one.";
3590 *launch_out = 1;
3591 return NULL;
3592 } else {
3593 *msg_out = "Not connected. Connecting.";
3594 *launch_out = 1;
3595 return NULL;
3600 * Describe the transport subclass for a channel
3602 * Invoke a method to get a string description of the lower-layer
3603 * transport for this channel.
3606 const char *
3607 channel_describe_transport(channel_t *chan)
3609 tor_assert(chan);
3610 tor_assert(chan->describe_transport);
3612 return chan->describe_transport(chan);
3616 * Describe the transport subclass for a channel listener
3618 * Invoke a method to get a string description of the lower-layer
3619 * transport for this channel listener.
3622 const char *
3623 channel_listener_describe_transport(channel_listener_t *chan_l)
3625 tor_assert(chan_l);
3626 tor_assert(chan_l->describe_transport);
3628 return chan_l->describe_transport(chan_l);
3632 * Return the number of entries in <b>queue</b>
3634 STATIC int
3635 chan_cell_queue_len(const chan_cell_queue_t *queue)
3637 int r = 0;
3638 cell_queue_entry_t *cell;
3639 TOR_SIMPLEQ_FOREACH(cell, queue, next)
3640 ++r;
3641 return r;
3645 * Dump channel statistics
3647 * Dump statistics for one channel to the log
3650 MOCK_IMPL(void,
3651 channel_dump_statistics, (channel_t *chan, int severity))
3653 double avg, interval, age;
3654 time_t now = time(NULL);
3655 tor_addr_t remote_addr;
3656 int have_remote_addr;
3657 char *remote_addr_str;
3659 tor_assert(chan);
3661 age = (double)(now - chan->timestamp_created);
3663 tor_log(severity, LD_GENERAL,
3664 "Channel " U64_FORMAT " (at %p) with transport %s is in state "
3665 "%s (%d)",
3666 U64_PRINTF_ARG(chan->global_identifier), chan,
3667 channel_describe_transport(chan),
3668 channel_state_to_string(chan->state), chan->state);
3669 tor_log(severity, LD_GENERAL,
3670 " * Channel " U64_FORMAT " was created at " U64_FORMAT
3671 " (" U64_FORMAT " seconds ago) "
3672 "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3673 U64_PRINTF_ARG(chan->global_identifier),
3674 U64_PRINTF_ARG(chan->timestamp_created),
3675 U64_PRINTF_ARG(now - chan->timestamp_created),
3676 U64_PRINTF_ARG(chan->timestamp_active),
3677 U64_PRINTF_ARG(now - chan->timestamp_active));
3679 /* Handle digest and nickname */
3680 if (!tor_digest_is_zero(chan->identity_digest)) {
3681 if (chan->nickname) {
3682 tor_log(severity, LD_GENERAL,
3683 " * Channel " U64_FORMAT " says it is connected "
3684 "to an OR with digest %s and nickname %s",
3685 U64_PRINTF_ARG(chan->global_identifier),
3686 hex_str(chan->identity_digest, DIGEST_LEN),
3687 chan->nickname);
3688 } else {
3689 tor_log(severity, LD_GENERAL,
3690 " * Channel " U64_FORMAT " says it is connected "
3691 "to an OR with digest %s and no known nickname",
3692 U64_PRINTF_ARG(chan->global_identifier),
3693 hex_str(chan->identity_digest, DIGEST_LEN));
3695 } else {
3696 if (chan->nickname) {
3697 tor_log(severity, LD_GENERAL,
3698 " * Channel " U64_FORMAT " does not know the digest"
3699 " of the OR it is connected to, but reports its nickname is %s",
3700 U64_PRINTF_ARG(chan->global_identifier),
3701 chan->nickname);
3702 } else {
3703 tor_log(severity, LD_GENERAL,
3704 " * Channel " U64_FORMAT " does not know the digest"
3705 " or the nickname of the OR it is connected to",
3706 U64_PRINTF_ARG(chan->global_identifier));
3710 /* Handle remote address and descriptions */
3711 have_remote_addr = channel_get_addr_if_possible(chan, &remote_addr);
3712 if (have_remote_addr) {
3713 char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
3714 remote_addr_str = tor_addr_to_str_dup(&remote_addr);
3715 tor_log(severity, LD_GENERAL,
3716 " * Channel " U64_FORMAT " says its remote address"
3717 " is %s, and gives a canonical description of \"%s\" and an "
3718 "actual description of \"%s\"",
3719 U64_PRINTF_ARG(chan->global_identifier),
3720 safe_str(remote_addr_str),
3721 safe_str(channel_get_canonical_remote_descr(chan)),
3722 safe_str(actual));
3723 tor_free(remote_addr_str);
3724 tor_free(actual);
3725 } else {
3726 char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
3727 tor_log(severity, LD_GENERAL,
3728 " * Channel " U64_FORMAT " does not know its remote "
3729 "address, but gives a canonical description of \"%s\" and an "
3730 "actual description of \"%s\"",
3731 U64_PRINTF_ARG(chan->global_identifier),
3732 channel_get_canonical_remote_descr(chan),
3733 actual);
3734 tor_free(actual);
3737 /* Handle marks */
3738 tor_log(severity, LD_GENERAL,
3739 " * Channel " U64_FORMAT " has these marks: %s %s %s "
3740 "%s %s %s",
3741 U64_PRINTF_ARG(chan->global_identifier),
3742 channel_is_bad_for_new_circs(chan) ?
3743 "bad_for_new_circs" : "!bad_for_new_circs",
3744 channel_is_canonical(chan) ?
3745 "canonical" : "!canonical",
3746 channel_is_canonical_is_reliable(chan) ?
3747 "is_canonical_is_reliable" :
3748 "!is_canonical_is_reliable",
3749 channel_is_client(chan) ?
3750 "client" : "!client",
3751 channel_is_local(chan) ?
3752 "local" : "!local",
3753 channel_is_incoming(chan) ?
3754 "incoming" : "outgoing");
3756 /* Describe queues */
3757 tor_log(severity, LD_GENERAL,
3758 " * Channel " U64_FORMAT " has %d queued incoming cells"
3759 " and %d queued outgoing cells",
3760 U64_PRINTF_ARG(chan->global_identifier),
3761 chan_cell_queue_len(&chan->incoming_queue),
3762 chan_cell_queue_len(&chan->outgoing_queue));
3764 /* Describe circuits */
3765 tor_log(severity, LD_GENERAL,
3766 " * Channel " U64_FORMAT " has %d active circuits out of"
3767 " %d in total",
3768 U64_PRINTF_ARG(chan->global_identifier),
3769 (chan->cmux != NULL) ?
3770 circuitmux_num_active_circuits(chan->cmux) : 0,
3771 (chan->cmux != NULL) ?
3772 circuitmux_num_circuits(chan->cmux) : 0);
3774 /* Describe timestamps */
3775 tor_log(severity, LD_GENERAL,
3776 " * Channel " U64_FORMAT " was last used by a "
3777 "client at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3778 U64_PRINTF_ARG(chan->global_identifier),
3779 U64_PRINTF_ARG(chan->timestamp_client),
3780 U64_PRINTF_ARG(now - chan->timestamp_client));
3781 tor_log(severity, LD_GENERAL,
3782 " * Channel " U64_FORMAT " was last drained at "
3783 U64_FORMAT " (" U64_FORMAT " seconds ago)",
3784 U64_PRINTF_ARG(chan->global_identifier),
3785 U64_PRINTF_ARG(chan->timestamp_drained),
3786 U64_PRINTF_ARG(now - chan->timestamp_drained));
3787 tor_log(severity, LD_GENERAL,
3788 " * Channel " U64_FORMAT " last received a cell "
3789 "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3790 U64_PRINTF_ARG(chan->global_identifier),
3791 U64_PRINTF_ARG(chan->timestamp_recv),
3792 U64_PRINTF_ARG(now - chan->timestamp_recv));
3793 tor_log(severity, LD_GENERAL,
3794 " * Channel " U64_FORMAT " last transmitted a cell "
3795 "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3796 U64_PRINTF_ARG(chan->global_identifier),
3797 U64_PRINTF_ARG(chan->timestamp_xmit),
3798 U64_PRINTF_ARG(now - chan->timestamp_xmit));
3800 /* Describe counters and rates */
3801 tor_log(severity, LD_GENERAL,
3802 " * Channel " U64_FORMAT " has received "
3803 U64_FORMAT " bytes in " U64_FORMAT " cells and transmitted "
3804 U64_FORMAT " bytes in " U64_FORMAT " cells",
3805 U64_PRINTF_ARG(chan->global_identifier),
3806 U64_PRINTF_ARG(chan->n_bytes_recved),
3807 U64_PRINTF_ARG(chan->n_cells_recved),
3808 U64_PRINTF_ARG(chan->n_bytes_xmitted),
3809 U64_PRINTF_ARG(chan->n_cells_xmitted));
3810 if (now > chan->timestamp_created &&
3811 chan->timestamp_created > 0) {
3812 if (chan->n_bytes_recved > 0) {
3813 avg = (double)(chan->n_bytes_recved) / age;
3814 tor_log(severity, LD_GENERAL,
3815 " * Channel " U64_FORMAT " has averaged %f "
3816 "bytes received per second",
3817 U64_PRINTF_ARG(chan->global_identifier), avg);
3819 if (chan->n_cells_recved > 0) {
3820 avg = (double)(chan->n_cells_recved) / age;
3821 if (avg >= 1.0) {
3822 tor_log(severity, LD_GENERAL,
3823 " * Channel " U64_FORMAT " has averaged %f "
3824 "cells received per second",
3825 U64_PRINTF_ARG(chan->global_identifier), avg);
3826 } else if (avg >= 0.0) {
3827 interval = 1.0 / avg;
3828 tor_log(severity, LD_GENERAL,
3829 " * Channel " U64_FORMAT " has averaged %f "
3830 "seconds between received cells",
3831 U64_PRINTF_ARG(chan->global_identifier), interval);
3834 if (chan->n_bytes_xmitted > 0) {
3835 avg = (double)(chan->n_bytes_xmitted) / age;
3836 tor_log(severity, LD_GENERAL,
3837 " * Channel " U64_FORMAT " has averaged %f "
3838 "bytes transmitted per second",
3839 U64_PRINTF_ARG(chan->global_identifier), avg);
3841 if (chan->n_cells_xmitted > 0) {
3842 avg = (double)(chan->n_cells_xmitted) / age;
3843 if (avg >= 1.0) {
3844 tor_log(severity, LD_GENERAL,
3845 " * Channel " U64_FORMAT " has averaged %f "
3846 "cells transmitted per second",
3847 U64_PRINTF_ARG(chan->global_identifier), avg);
3848 } else if (avg >= 0.0) {
3849 interval = 1.0 / avg;
3850 tor_log(severity, LD_GENERAL,
3851 " * Channel " U64_FORMAT " has averaged %f "
3852 "seconds between transmitted cells",
3853 U64_PRINTF_ARG(chan->global_identifier), interval);
3858 /* Dump anything the lower layer has to say */
3859 channel_dump_transport_statistics(chan, severity);
3863 * Dump channel listener statistics
3865 * Dump statistics for one channel listener to the log
3868 void
3869 channel_listener_dump_statistics(channel_listener_t *chan_l, int severity)
3871 double avg, interval, age;
3872 time_t now = time(NULL);
3874 tor_assert(chan_l);
3876 age = (double)(now - chan_l->timestamp_created);
3878 tor_log(severity, LD_GENERAL,
3879 "Channel listener " U64_FORMAT " (at %p) with transport %s is in "
3880 "state %s (%d)",
3881 U64_PRINTF_ARG(chan_l->global_identifier), chan_l,
3882 channel_listener_describe_transport(chan_l),
3883 channel_listener_state_to_string(chan_l->state), chan_l->state);
3884 tor_log(severity, LD_GENERAL,
3885 " * Channel listener " U64_FORMAT " was created at " U64_FORMAT
3886 " (" U64_FORMAT " seconds ago) "
3887 "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3888 U64_PRINTF_ARG(chan_l->global_identifier),
3889 U64_PRINTF_ARG(chan_l->timestamp_created),
3890 U64_PRINTF_ARG(now - chan_l->timestamp_created),
3891 U64_PRINTF_ARG(chan_l->timestamp_active),
3892 U64_PRINTF_ARG(now - chan_l->timestamp_active));
3894 tor_log(severity, LD_GENERAL,
3895 " * Channel listener " U64_FORMAT " last accepted an incoming "
3896 "channel at " U64_FORMAT " (" U64_FORMAT " seconds ago) "
3897 "and has accepted " U64_FORMAT " channels in total",
3898 U64_PRINTF_ARG(chan_l->global_identifier),
3899 U64_PRINTF_ARG(chan_l->timestamp_accepted),
3900 U64_PRINTF_ARG(now - chan_l->timestamp_accepted),
3901 U64_PRINTF_ARG(chan_l->n_accepted));
3904 * If it's sensible to do so, get the rate of incoming channels on this
3905 * listener
3907 if (now > chan_l->timestamp_created &&
3908 chan_l->timestamp_created > 0 &&
3909 chan_l->n_accepted > 0) {
3910 avg = (double)(chan_l->n_accepted) / age;
3911 if (avg >= 1.0) {
3912 tor_log(severity, LD_GENERAL,
3913 " * Channel listener " U64_FORMAT " has averaged %f incoming "
3914 "channels per second",
3915 U64_PRINTF_ARG(chan_l->global_identifier), avg);
3916 } else if (avg >= 0.0) {
3917 interval = 1.0 / avg;
3918 tor_log(severity, LD_GENERAL,
3919 " * Channel listener " U64_FORMAT " has averaged %f seconds "
3920 "between incoming channels",
3921 U64_PRINTF_ARG(chan_l->global_identifier), interval);
3925 /* Dump anything the lower layer has to say */
3926 channel_listener_dump_transport_statistics(chan_l, severity);
3930 * Invoke transport-specific stats dump for channel
3932 * If there is a lower-layer statistics dump method, invoke it
3935 void
3936 channel_dump_transport_statistics(channel_t *chan, int severity)
3938 tor_assert(chan);
3940 if (chan->dumpstats) chan->dumpstats(chan, severity);
3944 * Invoke transport-specific stats dump for channel listener
3946 * If there is a lower-layer statistics dump method, invoke it
3949 void
3950 channel_listener_dump_transport_statistics(channel_listener_t *chan_l,
3951 int severity)
3953 tor_assert(chan_l);
3955 if (chan_l->dumpstats) chan_l->dumpstats(chan_l, severity);
3959 * Return text description of the remote endpoint
3961 * This function return a test provided by the lower layer of the remote
3962 * endpoint for this channel; it should specify the actual address connected
3963 * to/from.
3965 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
3966 * may invalidate the return value from this function.
3968 const char *
3969 channel_get_actual_remote_descr(channel_t *chan)
3971 tor_assert(chan);
3972 tor_assert(chan->get_remote_descr);
3974 /* Param 1 indicates the actual description */
3975 return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL);
3979 * Return the text address of the remote endpoint.
3981 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
3982 * may invalidate the return value from this function.
3984 const char *
3985 channel_get_actual_remote_address(channel_t *chan)
3987 /* Param 1 indicates the actual description */
3988 return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY);
3992 * Return text description of the remote endpoint canonical address
3994 * This function return a test provided by the lower layer of the remote
3995 * endpoint for this channel; it should use the known canonical address for
3996 * this OR's identity digest if possible.
3998 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
3999 * may invalidate the return value from this function.
4001 const char *
4002 channel_get_canonical_remote_descr(channel_t *chan)
4004 tor_assert(chan);
4005 tor_assert(chan->get_remote_descr);
4007 /* Param 0 indicates the canonicalized description */
4008 return chan->get_remote_descr(chan, 0);
4012 * Get remote address if possible.
4014 * Write the remote address out to a tor_addr_t if the underlying transport
4015 * supports this operation, and return 1. Return 0 if the underlying transport
4016 * doesn't let us do this.
4019 channel_get_addr_if_possible(channel_t *chan, tor_addr_t *addr_out)
4021 tor_assert(chan);
4022 tor_assert(addr_out);
4024 if (chan->get_remote_addr)
4025 return chan->get_remote_addr(chan, addr_out);
4026 /* Else no support, method not implemented */
4027 else return 0;
4031 * Check if there are outgoing queue writes on this channel
4033 * Indicate if either we have queued cells, or if not, whether the underlying
4034 * lower-layer transport thinks it has an output queue.
4038 channel_has_queued_writes(channel_t *chan)
4040 int has_writes = 0;
4042 tor_assert(chan);
4043 tor_assert(chan->has_queued_writes);
4045 if (! TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue)) {
4046 has_writes = 1;
4047 } else {
4048 /* Check with the lower layer */
4049 has_writes = chan->has_queued_writes(chan);
4052 return has_writes;
4056 * Check the is_bad_for_new_circs flag
4058 * This function returns the is_bad_for_new_circs flag of the specified
4059 * channel.
4063 channel_is_bad_for_new_circs(channel_t *chan)
4065 tor_assert(chan);
4067 return chan->is_bad_for_new_circs;
4071 * Mark a channel as bad for new circuits
4073 * Set the is_bad_for_new_circs_flag on chan.
4076 void
4077 channel_mark_bad_for_new_circs(channel_t *chan)
4079 tor_assert(chan);
4081 chan->is_bad_for_new_circs = 1;
4085 * Get the client flag
4087 * This returns the client flag of a channel, which will be set if
4088 * command_process_create_cell() in command.c thinks this is a connection
4089 * from a client.
4093 channel_is_client(const channel_t *chan)
4095 tor_assert(chan);
4097 return chan->is_client;
4101 * Set the client flag
4103 * Mark a channel as being from a client
4106 void
4107 channel_mark_client(channel_t *chan)
4109 tor_assert(chan);
4111 chan->is_client = 1;
4115 * Clear the client flag
4117 * Mark a channel as being _not_ from a client
4120 void
4121 channel_clear_client(channel_t *chan)
4123 tor_assert(chan);
4125 chan->is_client = 0;
4129 * Get the canonical flag for a channel
4131 * This returns the is_canonical for a channel; this flag is determined by
4132 * the lower layer and can't be set in a transport-independent way.
4136 channel_is_canonical(channel_t *chan)
4138 tor_assert(chan);
4139 tor_assert(chan->is_canonical);
4141 return chan->is_canonical(chan, 0);
4145 * Test if the canonical flag is reliable
4147 * This function asks if the lower layer thinks it's safe to trust the
4148 * result of channel_is_canonical()
4152 channel_is_canonical_is_reliable(channel_t *chan)
4154 tor_assert(chan);
4155 tor_assert(chan->is_canonical);
4157 return chan->is_canonical(chan, 1);
4161 * Test incoming flag
4163 * This function gets the incoming flag; this is set when a listener spawns
4164 * a channel. If this returns true the channel was remotely initiated.
4168 channel_is_incoming(channel_t *chan)
4170 tor_assert(chan);
4172 return chan->is_incoming;
4176 * Set the incoming flag
4178 * This function is called when a channel arrives on a listening channel
4179 * to mark it as incoming.
4182 void
4183 channel_mark_incoming(channel_t *chan)
4185 tor_assert(chan);
4187 chan->is_incoming = 1;
4191 * Test local flag
4193 * This function gets the local flag; the lower layer should set this when
4194 * setting up the channel if is_local_addr() is true for all of the
4195 * destinations it will communicate with on behalf of this channel. It's
4196 * used to decide whether to declare the network reachable when seeing incoming
4197 * traffic on the channel.
4201 channel_is_local(channel_t *chan)
4203 tor_assert(chan);
4205 return chan->is_local;
4209 * Set the local flag
4211 * This internal-only function should be called by the lower layer if the
4212 * channel is to a local address. See channel_is_local() above or the
4213 * description of the is_local bit in channel.h
4216 void
4217 channel_mark_local(channel_t *chan)
4219 tor_assert(chan);
4221 chan->is_local = 1;
4225 * Mark a channel as remote
4227 * This internal-only function should be called by the lower layer if the
4228 * channel is not to a local address but has previously been marked local.
4229 * See channel_is_local() above or the description of the is_local bit in
4230 * channel.h
4233 void
4234 channel_mark_remote(channel_t *chan)
4236 tor_assert(chan);
4238 chan->is_local = 0;
4242 * Test outgoing flag
4244 * This function gets the outgoing flag; this is the inverse of the incoming
4245 * bit set when a listener spawns a channel. If this returns true the channel
4246 * was locally initiated.
4250 channel_is_outgoing(channel_t *chan)
4252 tor_assert(chan);
4254 return !(chan->is_incoming);
4258 * Mark a channel as outgoing
4260 * This function clears the incoming flag and thus marks a channel as
4261 * outgoing.
4264 void
4265 channel_mark_outgoing(channel_t *chan)
4267 tor_assert(chan);
4269 chan->is_incoming = 0;
4272 /************************
4273 * Flow control queries *
4274 ***********************/
4277 * Get the latest estimate for the total queue size of all open channels
4280 uint64_t
4281 channel_get_global_queue_estimate(void)
4283 return estimated_total_queue_size;
4287 * Estimate the number of writeable cells
4289 * Ask the lower layer for an estimate of how many cells it can accept, and
4290 * then subtract the length of our outgoing_queue, if any, to produce an
4291 * estimate of the number of cells this channel can accept for writes.
4295 channel_num_cells_writeable(channel_t *chan)
4297 int result;
4299 tor_assert(chan);
4300 tor_assert(chan->num_cells_writeable);
4302 if (chan->state == CHANNEL_STATE_OPEN) {
4303 /* Query lower layer */
4304 result = chan->num_cells_writeable(chan);
4305 /* Subtract cell queue length, if any */
4306 result -= chan_cell_queue_len(&chan->outgoing_queue);
4307 if (result < 0) result = 0;
4308 } else {
4309 /* No cells are writeable in any other state */
4310 result = 0;
4313 return result;
4316 /*********************
4317 * Timestamp updates *
4318 ********************/
4321 * Update the created timestamp for a channel
4323 * This updates the channel's created timestamp and should only be called
4324 * from channel_init().
4327 void
4328 channel_timestamp_created(channel_t *chan)
4330 time_t now = time(NULL);
4332 tor_assert(chan);
4334 chan->timestamp_created = now;
4338 * Update the created timestamp for a channel listener
4340 * This updates the channel listener's created timestamp and should only be
4341 * called from channel_init_listener().
4344 void
4345 channel_listener_timestamp_created(channel_listener_t *chan_l)
4347 time_t now = time(NULL);
4349 tor_assert(chan_l);
4351 chan_l->timestamp_created = now;
4355 * Update the last active timestamp for a channel
4357 * This function updates the channel's last active timestamp; it should be
4358 * called by the lower layer whenever there is activity on the channel which
4359 * does not lead to a cell being transmitted or received; the active timestamp
4360 * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
4361 * but it should be updated for things like the v3 handshake and stuff that
4362 * produce activity only visible to the lower layer.
4365 void
4366 channel_timestamp_active(channel_t *chan)
4368 time_t now = time(NULL);
4370 tor_assert(chan);
4371 chan->timestamp_xfer_ms = monotime_coarse_absolute_msec();
4373 chan->timestamp_active = now;
4375 /* Clear any potential netflow padding timer. We're active */
4376 chan->next_padding_time_ms = 0;
4380 * Update the last active timestamp for a channel listener
4383 void
4384 channel_listener_timestamp_active(channel_listener_t *chan_l)
4386 time_t now = time(NULL);
4388 tor_assert(chan_l);
4390 chan_l->timestamp_active = now;
4394 * Update the last accepted timestamp.
4396 * This function updates the channel listener's last accepted timestamp; it
4397 * should be called whenever a new incoming channel is accepted on a
4398 * listener.
4401 void
4402 channel_listener_timestamp_accepted(channel_listener_t *chan_l)
4404 time_t now = time(NULL);
4406 tor_assert(chan_l);
4408 chan_l->timestamp_active = now;
4409 chan_l->timestamp_accepted = now;
4413 * Update client timestamp
4415 * This function is called by relay.c to timestamp a channel that appears to
4416 * be used as a client.
4419 void
4420 channel_timestamp_client(channel_t *chan)
4422 time_t now = time(NULL);
4424 tor_assert(chan);
4426 chan->timestamp_client = now;
4430 * Update the last drained timestamp
4432 * This is called whenever we transmit a cell which leaves the outgoing cell
4433 * queue completely empty. It also updates the xmit time and the active time.
4436 void
4437 channel_timestamp_drained(channel_t *chan)
4439 time_t now = time(NULL);
4441 tor_assert(chan);
4443 chan->timestamp_active = now;
4444 chan->timestamp_drained = now;
4445 chan->timestamp_xmit = now;
4449 * Update the recv timestamp
4451 * This is called whenever we get an incoming cell from the lower layer.
4452 * This also updates the active timestamp.
4455 void
4456 channel_timestamp_recv(channel_t *chan)
4458 time_t now = time(NULL);
4459 tor_assert(chan);
4460 chan->timestamp_xfer_ms = monotime_coarse_absolute_msec();
4462 chan->timestamp_active = now;
4463 chan->timestamp_recv = now;
4465 /* Clear any potential netflow padding timer. We're active */
4466 chan->next_padding_time_ms = 0;
4470 * Update the xmit timestamp
4471 * This is called whenever we pass an outgoing cell to the lower layer. This
4472 * also updates the active timestamp.
4475 void
4476 channel_timestamp_xmit(channel_t *chan)
4478 time_t now = time(NULL);
4479 tor_assert(chan);
4481 chan->timestamp_xfer_ms = monotime_coarse_absolute_msec();
4483 chan->timestamp_active = now;
4484 chan->timestamp_xmit = now;
4486 /* Clear any potential netflow padding timer. We're active */
4487 chan->next_padding_time_ms = 0;
4490 /***************************************************************
4491 * Timestamp queries - see above for definitions of timestamps *
4492 **************************************************************/
4495 * Query created timestamp for a channel
4498 time_t
4499 channel_when_created(channel_t *chan)
4501 tor_assert(chan);
4503 return chan->timestamp_created;
4507 * Query created timestamp for a channel listener
4510 time_t
4511 channel_listener_when_created(channel_listener_t *chan_l)
4513 tor_assert(chan_l);
4515 return chan_l->timestamp_created;
4519 * Query last active timestamp for a channel
4522 time_t
4523 channel_when_last_active(channel_t *chan)
4525 tor_assert(chan);
4527 return chan->timestamp_active;
4531 * Query last active timestamp for a channel listener
4534 time_t
4535 channel_listener_when_last_active(channel_listener_t *chan_l)
4537 tor_assert(chan_l);
4539 return chan_l->timestamp_active;
4543 * Query last accepted timestamp for a channel listener
4546 time_t
4547 channel_listener_when_last_accepted(channel_listener_t *chan_l)
4549 tor_assert(chan_l);
4551 return chan_l->timestamp_accepted;
4555 * Query client timestamp
4558 time_t
4559 channel_when_last_client(channel_t *chan)
4561 tor_assert(chan);
4563 return chan->timestamp_client;
4567 * Query drained timestamp
4570 time_t
4571 channel_when_last_drained(channel_t *chan)
4573 tor_assert(chan);
4575 return chan->timestamp_drained;
4579 * Query recv timestamp
4582 time_t
4583 channel_when_last_recv(channel_t *chan)
4585 tor_assert(chan);
4587 return chan->timestamp_recv;
4591 * Query xmit timestamp
4594 time_t
4595 channel_when_last_xmit(channel_t *chan)
4597 tor_assert(chan);
4599 return chan->timestamp_xmit;
4603 * Query accepted counter
4606 uint64_t
4607 channel_listener_count_accepted(channel_listener_t *chan_l)
4609 tor_assert(chan_l);
4611 return chan_l->n_accepted;
4615 * Query received cell counter
4618 uint64_t
4619 channel_count_recved(channel_t *chan)
4621 tor_assert(chan);
4623 return chan->n_cells_recved;
4627 * Query transmitted cell counter
4630 uint64_t
4631 channel_count_xmitted(channel_t *chan)
4633 tor_assert(chan);
4635 return chan->n_cells_xmitted;
4639 * Check if a channel matches an extend_info_t
4641 * This function calls the lower layer and asks if this channel matches a
4642 * given extend_info_t.
4646 channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
4648 tor_assert(chan);
4649 tor_assert(chan->matches_extend_info);
4650 tor_assert(extend_info);
4652 return chan->matches_extend_info(chan, extend_info);
4656 * Check if a channel matches a given target address; return true iff we do.
4658 * This function calls into the lower layer and asks if this channel thinks
4659 * it matches a given target address for circuit extension purposes.
4663 channel_matches_target_addr_for_extend(channel_t *chan,
4664 const tor_addr_t *target)
4666 tor_assert(chan);
4667 tor_assert(chan->matches_target);
4668 tor_assert(target);
4670 return chan->matches_target(chan, target);
4674 * Return the total number of circuits used by a channel
4676 * @param chan Channel to query
4677 * @return Number of circuits using this as n_chan or p_chan
4680 unsigned int
4681 channel_num_circuits(channel_t *chan)
4683 tor_assert(chan);
4685 return chan->num_n_circuits +
4686 chan->num_p_circuits;
4690 * Set up circuit ID generation
4692 * This is called when setting up a channel and replaces the old
4693 * connection_or_set_circid_type()
4695 MOCK_IMPL(void,
4696 channel_set_circid_type,(channel_t *chan,
4697 crypto_pk_t *identity_rcvd,
4698 int consider_identity))
4700 int started_here;
4701 crypto_pk_t *our_identity;
4703 tor_assert(chan);
4705 started_here = channel_is_outgoing(chan);
4707 if (! consider_identity) {
4708 if (started_here)
4709 chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
4710 else
4711 chan->circ_id_type = CIRC_ID_TYPE_LOWER;
4712 return;
4715 our_identity = started_here ?
4716 get_tlsclient_identity_key() : get_server_identity_key();
4718 if (identity_rcvd) {
4719 if (crypto_pk_cmp_keys(our_identity, identity_rcvd) < 0) {
4720 chan->circ_id_type = CIRC_ID_TYPE_LOWER;
4721 } else {
4722 chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
4724 } else {
4725 chan->circ_id_type = CIRC_ID_TYPE_NEITHER;
4729 /** Helper for channel_update_bad_for_new_circs(): Perform the
4730 * channel_update_bad_for_new_circs operation on all channels in <b>lst</b>,
4731 * all of which MUST have the same RSA ID. (They MAY have different
4732 * Ed25519 IDs.) */
4733 static void
4734 channel_rsa_id_group_set_badness(struct channel_list_s *lst, int force)
4736 /*XXXX This function should really be about channels. 15056 */
4737 channel_t *chan;
4739 /* First, get a minimal list of the ed25519 identites */
4740 smartlist_t *ed_identities = smartlist_new();
4741 TOR_LIST_FOREACH(chan, lst, next_with_same_id) {
4742 uint8_t *id_copy =
4743 tor_memdup(&chan->ed25519_identity.pubkey, DIGEST256_LEN);
4744 smartlist_add(ed_identities, id_copy);
4746 smartlist_sort_digests256(ed_identities);
4747 smartlist_uniq_digests256(ed_identities);
4749 /* Now, for each Ed identity, build a smartlist and find the best entry on
4750 * it. */
4751 smartlist_t *or_conns = smartlist_new();
4752 SMARTLIST_FOREACH_BEGIN(ed_identities, const uint8_t *, ed_id) {
4753 TOR_LIST_FOREACH(chan, lst, next_with_same_id) {
4754 channel_tls_t *chantls = BASE_CHAN_TO_TLS(chan);
4755 if (tor_memneq(ed_id, &chan->ed25519_identity.pubkey, DIGEST256_LEN))
4756 continue;
4757 or_connection_t *orconn = chantls->conn;
4758 if (orconn) {
4759 tor_assert(orconn->chan == chantls);
4760 smartlist_add(or_conns, orconn);
4764 connection_or_group_set_badness_(or_conns, force);
4765 smartlist_clear(or_conns);
4766 } SMARTLIST_FOREACH_END(ed_id);
4768 /* XXXX 15056 we may want to do something special with connections that have
4769 * no set Ed25519 identity! */
4771 smartlist_free(or_conns);
4773 SMARTLIST_FOREACH(ed_identities, uint8_t *, ed_id, tor_free(ed_id));
4774 smartlist_free(ed_identities);
4777 /** Go through all the channels (or if <b>digest</b> is non-NULL, just
4778 * the OR connections with that digest), and set the is_bad_for_new_circs
4779 * flag based on the rules in connection_or_group_set_badness() (or just
4780 * always set it if <b>force</b> is true).
4782 void
4783 channel_update_bad_for_new_circs(const char *digest, int force)
4785 if (digest) {
4786 channel_idmap_entry_t *ent;
4787 channel_idmap_entry_t search;
4788 memset(&search, 0, sizeof(search));
4789 memcpy(search.digest, digest, DIGEST_LEN);
4790 ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
4791 if (ent) {
4792 channel_rsa_id_group_set_badness(&ent->channel_list, force);
4794 return;
4797 /* no digest; just look at everything. */
4798 channel_idmap_entry_t **iter;
4799 HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
4800 channel_rsa_id_group_set_badness(&(*iter)->channel_list, force);
4805 * Update the estimated number of bytes queued to transmit for this channel,
4806 * and notify the scheduler. The estimate includes both the channel queue and
4807 * the queue size reported by the lower layer, and an overhead estimate
4808 * optionally provided by the lower layer.
4811 void
4812 channel_update_xmit_queue_size(channel_t *chan)
4814 uint64_t queued, adj;
4815 double overhead;
4817 tor_assert(chan);
4818 tor_assert(chan->num_bytes_queued);
4821 * First, get the number of bytes we have queued without factoring in
4822 * lower-layer overhead.
4824 queued = chan->num_bytes_queued(chan) + chan->bytes_in_queue;
4825 /* Next, adjust by the overhead factor, if any is available */
4826 if (chan->get_overhead_estimate) {
4827 overhead = chan->get_overhead_estimate(chan);
4828 if (overhead >= 1.0) {
4829 queued = (uint64_t)(queued * overhead);
4830 } else {
4831 /* Ignore silly overhead factors */
4832 log_notice(LD_CHANNEL, "Ignoring silly overhead factor %f", overhead);
4836 /* Now, compare to the previous estimate */
4837 if (queued > chan->bytes_queued_for_xmit) {
4838 adj = queued - chan->bytes_queued_for_xmit;
4839 log_debug(LD_CHANNEL,
4840 "Increasing queue size for channel " U64_FORMAT " by " U64_FORMAT
4841 " from " U64_FORMAT " to " U64_FORMAT,
4842 U64_PRINTF_ARG(chan->global_identifier),
4843 U64_PRINTF_ARG(adj),
4844 U64_PRINTF_ARG(chan->bytes_queued_for_xmit),
4845 U64_PRINTF_ARG(queued));
4846 /* Update the channel's estimate */
4847 chan->bytes_queued_for_xmit = queued;
4849 /* Update the global queue size estimate if appropriate */
4850 if (chan->state == CHANNEL_STATE_OPEN ||
4851 chan->state == CHANNEL_STATE_MAINT) {
4852 estimated_total_queue_size += adj;
4853 log_debug(LD_CHANNEL,
4854 "Increasing global queue size by " U64_FORMAT " for channel "
4855 U64_FORMAT ", new size is " U64_FORMAT,
4856 U64_PRINTF_ARG(adj), U64_PRINTF_ARG(chan->global_identifier),
4857 U64_PRINTF_ARG(estimated_total_queue_size));
4859 } else if (queued < chan->bytes_queued_for_xmit) {
4860 adj = chan->bytes_queued_for_xmit - queued;
4861 log_debug(LD_CHANNEL,
4862 "Decreasing queue size for channel " U64_FORMAT " by " U64_FORMAT
4863 " from " U64_FORMAT " to " U64_FORMAT,
4864 U64_PRINTF_ARG(chan->global_identifier),
4865 U64_PRINTF_ARG(adj),
4866 U64_PRINTF_ARG(chan->bytes_queued_for_xmit),
4867 U64_PRINTF_ARG(queued));
4868 /* Update the channel's estimate */
4869 chan->bytes_queued_for_xmit = queued;
4871 /* Update the global queue size estimate if appropriate */
4872 if (chan->state == CHANNEL_STATE_OPEN ||
4873 chan->state == CHANNEL_STATE_MAINT) {
4874 estimated_total_queue_size -= adj;
4875 log_debug(LD_CHANNEL,
4876 "Decreasing global queue size by " U64_FORMAT " for channel "
4877 U64_FORMAT ", new size is " U64_FORMAT,
4878 U64_PRINTF_ARG(adj), U64_PRINTF_ARG(chan->global_identifier),
4879 U64_PRINTF_ARG(estimated_total_queue_size));