Merge branch 'maint-0.2.7' into maint-0.2.8
[tor.git] / src / or / channel.c
blob5f69a0864b728fdf3753563639489ba40cdcee9c
1 /* * Copyright (c) 2012-2016, 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.
11 **/
14 * Define this so channel.h gives us things only channel_t subclasses
15 * should touch.
18 #define TOR_CHANNEL_INTERNAL_
20 /* This one's for stuff only channel.c and the test suite should see */
21 #define CHANNEL_PRIVATE_
23 #include "or.h"
24 #include "channel.h"
25 #include "channeltls.h"
26 #include "circuitbuild.h"
27 #include "circuitlist.h"
28 #include "circuitstats.h"
29 #include "config.h"
30 #include "connection_or.h" /* For var_cell_free() */
31 #include "circuitmux.h"
32 #include "entrynodes.h"
33 #include "geoip.h"
34 #include "nodelist.h"
35 #include "relay.h"
36 #include "rephist.h"
37 #include "router.h"
38 #include "routerlist.h"
39 #include "scheduler.h"
41 /* Global lists of channels */
43 /* All channel_t instances */
44 static smartlist_t *all_channels = NULL;
46 /* All channel_t instances not in ERROR or CLOSED states */
47 static smartlist_t *active_channels = NULL;
49 /* All channel_t instances in ERROR or CLOSED states */
50 static smartlist_t *finished_channels = NULL;
52 /* All channel_listener_t instances */
53 static smartlist_t *all_listeners = NULL;
55 /* All channel_listener_t instances in LISTENING state */
56 static smartlist_t *active_listeners = NULL;
58 /* All channel_listener_t instances in LISTENING state */
59 static smartlist_t *finished_listeners = NULL;
61 /* Counter for ID numbers */
62 static uint64_t n_channels_allocated = 0;
64 * Channel global byte/cell counters, for statistics and for scheduler high
65 * /low-water marks.
69 * Total number of cells ever given to any channel with the
70 * channel_write_*_cell() functions.
73 static uint64_t n_channel_cells_queued = 0;
76 * Total number of cells ever passed to a channel lower layer with the
77 * write_*_cell() methods.
80 static uint64_t n_channel_cells_passed_to_lower_layer = 0;
83 * Current number of cells in all channel queues; should be
84 * n_channel_cells_queued - n_channel_cells_passed_to_lower_layer.
87 static uint64_t n_channel_cells_in_queues = 0;
90 * Total number of bytes for all cells ever queued to a channel and
91 * counted in n_channel_cells_queued.
94 static uint64_t n_channel_bytes_queued = 0;
97 * Total number of bytes for all cells ever passed to a channel lower layer
98 * and counted in n_channel_cells_passed_to_lower_layer.
101 static uint64_t n_channel_bytes_passed_to_lower_layer = 0;
104 * Current number of bytes in all channel queues; should be
105 * n_channel_bytes_queued - n_channel_bytes_passed_to_lower_layer.
108 static uint64_t n_channel_bytes_in_queues = 0;
111 * Current total estimated queue size *including lower layer queues and
112 * transmit overhead*
115 STATIC uint64_t estimated_total_queue_size = 0;
117 /* Digest->channel map
119 * Similar to the one used in connection_or.c, this maps from the identity
120 * digest of a remote endpoint to a channel_t to that endpoint. Channels
121 * should be placed here when registered and removed when they close or error.
122 * If more than one channel exists, follow the next_with_same_id pointer
123 * as a linked list.
125 HT_HEAD(channel_idmap, channel_idmap_entry_s) channel_identity_map =
126 HT_INITIALIZER();
128 typedef struct channel_idmap_entry_s {
129 HT_ENTRY(channel_idmap_entry_s) node;
130 uint8_t digest[DIGEST_LEN];
131 TOR_LIST_HEAD(channel_list_s, channel_s) channel_list;
132 } channel_idmap_entry_t;
134 static inline unsigned
135 channel_idmap_hash(const channel_idmap_entry_t *ent)
137 return (unsigned) siphash24g(ent->digest, DIGEST_LEN);
140 static inline int
141 channel_idmap_eq(const channel_idmap_entry_t *a,
142 const channel_idmap_entry_t *b)
144 return tor_memeq(a->digest, b->digest, DIGEST_LEN);
147 HT_PROTOTYPE(channel_idmap, channel_idmap_entry_s, node, channel_idmap_hash,
148 channel_idmap_eq);
149 HT_GENERATE2(channel_idmap, channel_idmap_entry_s, node, channel_idmap_hash,
150 channel_idmap_eq, 0.5, tor_reallocarray_, tor_free_);
152 static cell_queue_entry_t * cell_queue_entry_dup(cell_queue_entry_t *q);
153 #if 0
154 static int cell_queue_entry_is_padding(cell_queue_entry_t *q);
155 #endif
156 static cell_queue_entry_t *
157 cell_queue_entry_new_fixed(cell_t *cell);
158 static cell_queue_entry_t *
159 cell_queue_entry_new_var(var_cell_t *var_cell);
160 static int is_destroy_cell(channel_t *chan,
161 const cell_queue_entry_t *q, circid_t *circid_out);
163 static void channel_assert_counter_consistency(void);
165 /* Functions to maintain the digest map */
166 static void channel_add_to_digest_map(channel_t *chan);
167 static void channel_remove_from_digest_map(channel_t *chan);
170 * Flush cells from just the outgoing queue without trying to get them
171 * from circuits; used internall by channel_flush_some_cells().
173 static ssize_t
174 channel_flush_some_cells_from_outgoing_queue(channel_t *chan,
175 ssize_t num_cells);
176 static void channel_force_free(channel_t *chan);
177 static void
178 channel_free_list(smartlist_t *channels, int mark_for_close);
179 static void
180 channel_listener_free_list(smartlist_t *channels, int mark_for_close);
181 static void channel_listener_force_free(channel_listener_t *chan_l);
182 static size_t channel_get_cell_queue_entry_size(channel_t *chan,
183 cell_queue_entry_t *q);
184 static void
185 channel_write_cell_queue_entry(channel_t *chan, cell_queue_entry_t *q);
187 /***********************************
188 * Channel state utility functions *
189 **********************************/
192 * Indicate whether a given channel state is valid
196 channel_state_is_valid(channel_state_t state)
198 int is_valid;
200 switch (state) {
201 case CHANNEL_STATE_CLOSED:
202 case CHANNEL_STATE_CLOSING:
203 case CHANNEL_STATE_ERROR:
204 case CHANNEL_STATE_MAINT:
205 case CHANNEL_STATE_OPENING:
206 case CHANNEL_STATE_OPEN:
207 is_valid = 1;
208 break;
209 case CHANNEL_STATE_LAST:
210 default:
211 is_valid = 0;
214 return is_valid;
218 * Indicate whether a given channel listener state is valid
222 channel_listener_state_is_valid(channel_listener_state_t state)
224 int is_valid;
226 switch (state) {
227 case CHANNEL_LISTENER_STATE_CLOSED:
228 case CHANNEL_LISTENER_STATE_LISTENING:
229 case CHANNEL_LISTENER_STATE_CLOSING:
230 case CHANNEL_LISTENER_STATE_ERROR:
231 is_valid = 1;
232 break;
233 case CHANNEL_LISTENER_STATE_LAST:
234 default:
235 is_valid = 0;
238 return is_valid;
242 * Indicate whether a channel state transition is valid
244 * This function takes two channel states and indicates whether a
245 * transition between them is permitted (see the state definitions and
246 * transition table in or.h at the channel_state_t typedef).
250 channel_state_can_transition(channel_state_t from, channel_state_t to)
252 int is_valid;
254 switch (from) {
255 case CHANNEL_STATE_CLOSED:
256 is_valid = (to == CHANNEL_STATE_OPENING);
257 break;
258 case CHANNEL_STATE_CLOSING:
259 is_valid = (to == CHANNEL_STATE_CLOSED ||
260 to == CHANNEL_STATE_ERROR);
261 break;
262 case CHANNEL_STATE_ERROR:
263 is_valid = 0;
264 break;
265 case CHANNEL_STATE_MAINT:
266 is_valid = (to == CHANNEL_STATE_CLOSING ||
267 to == CHANNEL_STATE_ERROR ||
268 to == CHANNEL_STATE_OPEN);
269 break;
270 case CHANNEL_STATE_OPENING:
271 is_valid = (to == CHANNEL_STATE_CLOSING ||
272 to == CHANNEL_STATE_ERROR ||
273 to == CHANNEL_STATE_OPEN);
274 break;
275 case CHANNEL_STATE_OPEN:
276 is_valid = (to == CHANNEL_STATE_CLOSING ||
277 to == CHANNEL_STATE_ERROR ||
278 to == CHANNEL_STATE_MAINT);
279 break;
280 case CHANNEL_STATE_LAST:
281 default:
282 is_valid = 0;
285 return is_valid;
289 * Indicate whether a channel listener state transition is valid
291 * This function takes two channel listener states and indicates whether a
292 * transition between them is permitted (see the state definitions and
293 * transition table in or.h at the channel_listener_state_t typedef).
297 channel_listener_state_can_transition(channel_listener_state_t from,
298 channel_listener_state_t to)
300 int is_valid;
302 switch (from) {
303 case CHANNEL_LISTENER_STATE_CLOSED:
304 is_valid = (to == CHANNEL_LISTENER_STATE_LISTENING);
305 break;
306 case CHANNEL_LISTENER_STATE_CLOSING:
307 is_valid = (to == CHANNEL_LISTENER_STATE_CLOSED ||
308 to == CHANNEL_LISTENER_STATE_ERROR);
309 break;
310 case CHANNEL_LISTENER_STATE_ERROR:
311 is_valid = 0;
312 break;
313 case CHANNEL_LISTENER_STATE_LISTENING:
314 is_valid = (to == CHANNEL_LISTENER_STATE_CLOSING ||
315 to == CHANNEL_LISTENER_STATE_ERROR);
316 break;
317 case CHANNEL_LISTENER_STATE_LAST:
318 default:
319 is_valid = 0;
322 return is_valid;
326 * Return a human-readable description for a channel state
329 const char *
330 channel_state_to_string(channel_state_t state)
332 const char *descr;
334 switch (state) {
335 case CHANNEL_STATE_CLOSED:
336 descr = "closed";
337 break;
338 case CHANNEL_STATE_CLOSING:
339 descr = "closing";
340 break;
341 case CHANNEL_STATE_ERROR:
342 descr = "channel error";
343 break;
344 case CHANNEL_STATE_MAINT:
345 descr = "temporarily suspended for maintenance";
346 break;
347 case CHANNEL_STATE_OPENING:
348 descr = "opening";
349 break;
350 case CHANNEL_STATE_OPEN:
351 descr = "open";
352 break;
353 case CHANNEL_STATE_LAST:
354 default:
355 descr = "unknown or invalid channel state";
358 return descr;
362 * Return a human-readable description for a channel listenier state
365 const char *
366 channel_listener_state_to_string(channel_listener_state_t state)
368 const char *descr;
370 switch (state) {
371 case CHANNEL_LISTENER_STATE_CLOSED:
372 descr = "closed";
373 break;
374 case CHANNEL_LISTENER_STATE_CLOSING:
375 descr = "closing";
376 break;
377 case CHANNEL_LISTENER_STATE_ERROR:
378 descr = "channel listener error";
379 break;
380 case CHANNEL_LISTENER_STATE_LISTENING:
381 descr = "listening";
382 break;
383 case CHANNEL_LISTENER_STATE_LAST:
384 default:
385 descr = "unknown or invalid channel listener state";
388 return descr;
391 /***************************************
392 * Channel registration/unregistration *
393 ***************************************/
396 * Register a channel
398 * This function registers a newly created channel in the global lists/maps
399 * of active channels.
402 void
403 channel_register(channel_t *chan)
405 tor_assert(chan);
407 /* No-op if already registered */
408 if (chan->registered) return;
410 log_debug(LD_CHANNEL,
411 "Registering channel %p (ID " U64_FORMAT ") "
412 "in state %s (%d) with digest %s",
413 chan, U64_PRINTF_ARG(chan->global_identifier),
414 channel_state_to_string(chan->state), chan->state,
415 hex_str(chan->identity_digest, DIGEST_LEN));
417 /* Make sure we have all_channels, then add it */
418 if (!all_channels) all_channels = smartlist_new();
419 smartlist_add(all_channels, chan);
421 /* Is it finished? */
422 if (CHANNEL_FINISHED(chan)) {
423 /* Put it in the finished list, creating it if necessary */
424 if (!finished_channels) finished_channels = smartlist_new();
425 smartlist_add(finished_channels, chan);
426 } else {
427 /* Put it in the active list, creating it if necessary */
428 if (!active_channels) active_channels = smartlist_new();
429 smartlist_add(active_channels, chan);
431 if (!CHANNEL_IS_CLOSING(chan)) {
432 /* It should have a digest set */
433 if (!tor_digest_is_zero(chan->identity_digest)) {
434 /* Yeah, we're good, add it to the map */
435 channel_add_to_digest_map(chan);
436 } else {
437 log_info(LD_CHANNEL,
438 "Channel %p (global ID " U64_FORMAT ") "
439 "in state %s (%d) registered with no identity digest",
440 chan, U64_PRINTF_ARG(chan->global_identifier),
441 channel_state_to_string(chan->state), chan->state);
446 /* Mark it as registered */
447 chan->registered = 1;
451 * Unregister a channel
453 * This function removes a channel from the global lists and maps and is used
454 * when freeing a closed/errored channel.
457 void
458 channel_unregister(channel_t *chan)
460 tor_assert(chan);
462 /* No-op if not registered */
463 if (!(chan->registered)) return;
465 /* Is it finished? */
466 if (CHANNEL_FINISHED(chan)) {
467 /* Get it out of the finished list */
468 if (finished_channels) smartlist_remove(finished_channels, chan);
469 } else {
470 /* Get it out of the active list */
471 if (active_channels) smartlist_remove(active_channels, chan);
474 /* Get it out of all_channels */
475 if (all_channels) smartlist_remove(all_channels, chan);
477 /* Mark it as unregistered */
478 chan->registered = 0;
480 /* Should it be in the digest map? */
481 if (!tor_digest_is_zero(chan->identity_digest) &&
482 !(CHANNEL_CONDEMNED(chan))) {
483 /* Remove it */
484 channel_remove_from_digest_map(chan);
489 * Register a channel listener
491 * This function registers a newly created channel listner in the global
492 * lists/maps of active channel listeners.
495 void
496 channel_listener_register(channel_listener_t *chan_l)
498 tor_assert(chan_l);
500 /* No-op if already registered */
501 if (chan_l->registered) return;
503 log_debug(LD_CHANNEL,
504 "Registering channel listener %p (ID " U64_FORMAT ") "
505 "in state %s (%d)",
506 chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
507 channel_listener_state_to_string(chan_l->state),
508 chan_l->state);
510 /* Make sure we have all_channels, then add it */
511 if (!all_listeners) all_listeners = smartlist_new();
512 smartlist_add(all_listeners, chan_l);
514 /* Is it finished? */
515 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
516 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
517 /* Put it in the finished list, creating it if necessary */
518 if (!finished_listeners) finished_listeners = smartlist_new();
519 smartlist_add(finished_listeners, chan_l);
520 } else {
521 /* Put it in the active list, creating it if necessary */
522 if (!active_listeners) active_listeners = smartlist_new();
523 smartlist_add(active_listeners, chan_l);
526 /* Mark it as registered */
527 chan_l->registered = 1;
531 * Unregister a channel listener
533 * This function removes a channel listener from the global lists and maps
534 * and is used when freeing a closed/errored channel listener.
537 void
538 channel_listener_unregister(channel_listener_t *chan_l)
540 tor_assert(chan_l);
542 /* No-op if not registered */
543 if (!(chan_l->registered)) return;
545 /* Is it finished? */
546 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
547 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
548 /* Get it out of the finished list */
549 if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
550 } else {
551 /* Get it out of the active list */
552 if (active_listeners) smartlist_remove(active_listeners, chan_l);
555 /* Get it out of all_channels */
556 if (all_listeners) smartlist_remove(all_listeners, chan_l);
558 /* Mark it as unregistered */
559 chan_l->registered = 0;
562 /*********************************
563 * Channel digest map maintenance
564 *********************************/
567 * Add a channel to the digest map
569 * This function adds a channel to the digest map and inserts it into the
570 * correct linked list if channels with that remote endpoint identity digest
571 * already exist.
574 static void
575 channel_add_to_digest_map(channel_t *chan)
577 channel_idmap_entry_t *ent, search;
579 tor_assert(chan);
581 /* Assert that the state makes sense */
582 tor_assert(!CHANNEL_CONDEMNED(chan));
584 /* Assert that there is a digest */
585 tor_assert(!tor_digest_is_zero(chan->identity_digest));
587 memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
588 ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
589 if (! ent) {
590 ent = tor_malloc(sizeof(channel_idmap_entry_t));
591 memcpy(ent->digest, chan->identity_digest, DIGEST_LEN);
592 TOR_LIST_INIT(&ent->channel_list);
593 HT_INSERT(channel_idmap, &channel_identity_map, ent);
595 TOR_LIST_INSERT_HEAD(&ent->channel_list, chan, next_with_same_id);
597 log_debug(LD_CHANNEL,
598 "Added channel %p (global ID " U64_FORMAT ") "
599 "to identity map in state %s (%d) with digest %s",
600 chan, U64_PRINTF_ARG(chan->global_identifier),
601 channel_state_to_string(chan->state), chan->state,
602 hex_str(chan->identity_digest, DIGEST_LEN));
606 * Remove a channel from the digest map
608 * This function removes a channel from the digest map and the linked list of
609 * channels for that digest if more than one exists.
612 static void
613 channel_remove_from_digest_map(channel_t *chan)
615 channel_idmap_entry_t *ent, search;
617 tor_assert(chan);
619 /* Assert that there is a digest */
620 tor_assert(!tor_digest_is_zero(chan->identity_digest));
622 #if 0
623 /* Make sure we have a map */
624 if (!channel_identity_map) {
626 * No identity map, so we can't find it by definition. This
627 * case is similar to digestmap_get() failing below.
629 log_warn(LD_BUG,
630 "Trying to remove channel %p (global ID " U64_FORMAT ") "
631 "with digest %s from identity map, but didn't have any identity "
632 "map",
633 chan, U64_PRINTF_ARG(chan->global_identifier),
634 hex_str(chan->identity_digest, DIGEST_LEN));
635 /* Clear out its next/prev pointers */
636 if (chan->next_with_same_id) {
637 chan->next_with_same_id->prev_with_same_id = chan->prev_with_same_id;
639 if (chan->prev_with_same_id) {
640 chan->prev_with_same_id->next_with_same_id = chan->next_with_same_id;
642 chan->next_with_same_id = NULL;
643 chan->prev_with_same_id = NULL;
645 return;
647 #endif
649 /* Pull it out of its list, wherever that list is */
650 TOR_LIST_REMOVE(chan, next_with_same_id);
652 memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
653 ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
655 /* Look for it in the map */
656 if (ent) {
657 /* Okay, it's here */
659 if (TOR_LIST_EMPTY(&ent->channel_list)) {
660 HT_REMOVE(channel_idmap, &channel_identity_map, ent);
661 tor_free(ent);
664 log_debug(LD_CHANNEL,
665 "Removed channel %p (global ID " U64_FORMAT ") from "
666 "identity map in state %s (%d) with digest %s",
667 chan, U64_PRINTF_ARG(chan->global_identifier),
668 channel_state_to_string(chan->state), chan->state,
669 hex_str(chan->identity_digest, DIGEST_LEN));
670 } else {
671 /* Shouldn't happen */
672 log_warn(LD_BUG,
673 "Trying to remove channel %p (global ID " U64_FORMAT ") with "
674 "digest %s from identity map, but couldn't find any with "
675 "that digest",
676 chan, U64_PRINTF_ARG(chan->global_identifier),
677 hex_str(chan->identity_digest, DIGEST_LEN));
681 /****************************
682 * Channel lookup functions *
683 ***************************/
686 * Find channel by global ID
688 * This function searches for a channel by the global_identifier assigned
689 * at initialization time. This identifier is unique for the lifetime of the
690 * Tor process.
693 channel_t *
694 channel_find_by_global_id(uint64_t global_identifier)
696 channel_t *rv = NULL;
698 if (all_channels && smartlist_len(all_channels) > 0) {
699 SMARTLIST_FOREACH_BEGIN(all_channels, channel_t *, curr) {
700 if (curr->global_identifier == global_identifier) {
701 rv = curr;
702 break;
704 } SMARTLIST_FOREACH_END(curr);
707 return rv;
711 * Find channel by digest of the remote endpoint
713 * This function looks up a channel by the digest of its remote endpoint in
714 * the channel digest map. It's possible that more than one channel to a
715 * given endpoint exists. Use channel_next_with_digest() to walk the list.
718 channel_t *
719 channel_find_by_remote_digest(const char *identity_digest)
721 channel_t *rv = NULL;
722 channel_idmap_entry_t *ent, search;
724 tor_assert(identity_digest);
726 memcpy(search.digest, identity_digest, DIGEST_LEN);
727 ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
728 if (ent) {
729 rv = TOR_LIST_FIRST(&ent->channel_list);
732 return rv;
736 * Get next channel with digest
738 * This function takes a channel and finds the next channel in the list
739 * with the same digest.
742 channel_t *
743 channel_next_with_digest(channel_t *chan)
745 tor_assert(chan);
747 return TOR_LIST_NEXT(chan, next_with_same_id);
751 * Initialize a channel
753 * This function should be called by subclasses to set up some per-channel
754 * variables. I.e., this is the superclass constructor. Before this, the
755 * channel should be allocated with tor_malloc_zero().
758 void
759 channel_init(channel_t *chan)
761 tor_assert(chan);
763 /* Assign an ID and bump the counter */
764 chan->global_identifier = n_channels_allocated++;
766 /* Init timestamp */
767 chan->timestamp_last_had_circuits = time(NULL);
769 /* Warn about exhausted circuit IDs no more than hourly. */
770 chan->last_warned_circ_ids_exhausted.rate = 3600;
772 /* Initialize queues. */
773 TOR_SIMPLEQ_INIT(&chan->incoming_queue);
774 TOR_SIMPLEQ_INIT(&chan->outgoing_queue);
776 /* Initialize list entries. */
777 memset(&chan->next_with_same_id, 0, sizeof(chan->next_with_same_id));
779 /* Timestamp it */
780 channel_timestamp_created(chan);
782 /* It hasn't been open yet. */
783 chan->has_been_open = 0;
785 /* Scheduler state is idle */
786 chan->scheduler_state = SCHED_CHAN_IDLE;
790 * Initialize a channel listener
792 * This function should be called by subclasses to set up some per-channel
793 * variables. I.e., this is the superclass constructor. Before this, the
794 * channel listener should be allocated with tor_malloc_zero().
797 void
798 channel_init_listener(channel_listener_t *chan_l)
800 tor_assert(chan_l);
802 /* Assign an ID and bump the counter */
803 chan_l->global_identifier = n_channels_allocated++;
805 /* Timestamp it */
806 channel_listener_timestamp_created(chan_l);
810 * Free a channel; nothing outside of channel.c and subclasses should call
811 * this - it frees channels after they have closed and been unregistered.
814 void
815 channel_free(channel_t *chan)
817 if (!chan) return;
819 /* It must be closed or errored */
820 tor_assert(CHANNEL_FINISHED(chan));
822 /* It must be deregistered */
823 tor_assert(!(chan->registered));
825 log_debug(LD_CHANNEL,
826 "Freeing channel " U64_FORMAT " at %p",
827 U64_PRINTF_ARG(chan->global_identifier), chan);
829 /* Get this one out of the scheduler */
830 scheduler_release_channel(chan);
833 * Get rid of cmux policy before we do anything, so cmux policies don't
834 * see channels in weird half-freed states.
836 if (chan->cmux) {
837 circuitmux_set_policy(chan->cmux, NULL);
840 /* Call a free method if there is one */
841 if (chan->free) chan->free(chan);
843 channel_clear_remote_end(chan);
845 /* Get rid of cmux */
846 if (chan->cmux) {
847 circuitmux_detach_all_circuits(chan->cmux, NULL);
848 circuitmux_mark_destroyed_circids_usable(chan->cmux, chan);
849 circuitmux_free(chan->cmux);
850 chan->cmux = NULL;
853 /* We're in CLOSED or ERROR, so the cell queue is already empty */
855 tor_free(chan);
859 * Free a channel listener; nothing outside of channel.c and subclasses
860 * should call this - it frees channel listeners after they have closed and
861 * been unregistered.
864 void
865 channel_listener_free(channel_listener_t *chan_l)
867 if (!chan_l) return;
869 log_debug(LD_CHANNEL,
870 "Freeing channel_listener_t " U64_FORMAT " at %p",
871 U64_PRINTF_ARG(chan_l->global_identifier),
872 chan_l);
874 /* It must be closed or errored */
875 tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
876 chan_l->state == CHANNEL_LISTENER_STATE_ERROR);
877 /* It must be deregistered */
878 tor_assert(!(chan_l->registered));
880 /* Call a free method if there is one */
881 if (chan_l->free) chan_l->free(chan_l);
884 * We're in CLOSED or ERROR, so the incoming channel queue is already
885 * empty.
888 tor_free(chan_l);
892 * Free a channel and skip the state/registration asserts; this internal-
893 * use-only function should be called only from channel_free_all() when
894 * shutting down the Tor process.
897 static void
898 channel_force_free(channel_t *chan)
900 cell_queue_entry_t *cell, *cell_tmp;
901 tor_assert(chan);
903 log_debug(LD_CHANNEL,
904 "Force-freeing channel " U64_FORMAT " at %p",
905 U64_PRINTF_ARG(chan->global_identifier), chan);
907 /* Get this one out of the scheduler */
908 scheduler_release_channel(chan);
911 * Get rid of cmux policy before we do anything, so cmux policies don't
912 * see channels in weird half-freed states.
914 if (chan->cmux) {
915 circuitmux_set_policy(chan->cmux, NULL);
918 /* Call a free method if there is one */
919 if (chan->free) chan->free(chan);
921 channel_clear_remote_end(chan);
923 /* Get rid of cmux */
924 if (chan->cmux) {
925 circuitmux_free(chan->cmux);
926 chan->cmux = NULL;
929 /* We might still have a cell queue; kill it */
930 TOR_SIMPLEQ_FOREACH_SAFE(cell, &chan->incoming_queue, next, cell_tmp) {
931 cell_queue_entry_free(cell, 0);
933 TOR_SIMPLEQ_INIT(&chan->incoming_queue);
935 /* Outgoing cell queue is similar, but we can have to free packed cells */
936 TOR_SIMPLEQ_FOREACH_SAFE(cell, &chan->outgoing_queue, next, cell_tmp) {
937 cell_queue_entry_free(cell, 0);
939 TOR_SIMPLEQ_INIT(&chan->outgoing_queue);
941 tor_free(chan);
945 * Free a channel listener and skip the state/reigstration asserts; this
946 * internal-use-only function should be called only from channel_free_all()
947 * when shutting down the Tor process.
950 static void
951 channel_listener_force_free(channel_listener_t *chan_l)
953 tor_assert(chan_l);
955 log_debug(LD_CHANNEL,
956 "Force-freeing channel_listener_t " U64_FORMAT " at %p",
957 U64_PRINTF_ARG(chan_l->global_identifier),
958 chan_l);
960 /* Call a free method if there is one */
961 if (chan_l->free) chan_l->free(chan_l);
964 * The incoming list just gets emptied and freed; we request close on
965 * any channels we find there, but since we got called while shutting
966 * down they will get deregistered and freed elsewhere anyway.
968 if (chan_l->incoming_list) {
969 SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
970 channel_t *, qchan) {
971 channel_mark_for_close(qchan);
972 } SMARTLIST_FOREACH_END(qchan);
974 smartlist_free(chan_l->incoming_list);
975 chan_l->incoming_list = NULL;
978 tor_free(chan_l);
982 * Return the current registered listener for a channel listener
984 * This function returns a function pointer to the current registered
985 * handler for new incoming channels on a channel listener.
988 channel_listener_fn_ptr
989 channel_listener_get_listener_fn(channel_listener_t *chan_l)
991 tor_assert(chan_l);
993 if (chan_l->state == CHANNEL_LISTENER_STATE_LISTENING)
994 return chan_l->listener;
996 return NULL;
1000 * Set the listener for a channel listener
1002 * This function sets the handler for new incoming channels on a channel
1003 * listener.
1006 void
1007 channel_listener_set_listener_fn(channel_listener_t *chan_l,
1008 channel_listener_fn_ptr listener)
1010 tor_assert(chan_l);
1011 tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_LISTENING);
1013 log_debug(LD_CHANNEL,
1014 "Setting listener callback for channel listener %p "
1015 "(global ID " U64_FORMAT ") to %p",
1016 chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
1017 listener);
1019 chan_l->listener = listener;
1020 if (chan_l->listener) channel_listener_process_incoming(chan_l);
1024 * Return the fixed-length cell handler for a channel
1026 * This function gets the handler for incoming fixed-length cells installed
1027 * on a channel.
1030 channel_cell_handler_fn_ptr
1031 channel_get_cell_handler(channel_t *chan)
1033 tor_assert(chan);
1035 if (CHANNEL_CAN_HANDLE_CELLS(chan))
1036 return chan->cell_handler;
1038 return NULL;
1042 * Return the variable-length cell handler for a channel
1044 * This function gets the handler for incoming variable-length cells
1045 * installed on a channel.
1048 channel_var_cell_handler_fn_ptr
1049 channel_get_var_cell_handler(channel_t *chan)
1051 tor_assert(chan);
1053 if (CHANNEL_CAN_HANDLE_CELLS(chan))
1054 return chan->var_cell_handler;
1056 return NULL;
1060 * Set both cell handlers for a channel
1062 * This function sets both the fixed-length and variable length cell handlers
1063 * for a channel and processes any incoming cells that had been blocked in the
1064 * queue because none were available.
1067 void
1068 channel_set_cell_handlers(channel_t *chan,
1069 channel_cell_handler_fn_ptr cell_handler,
1070 channel_var_cell_handler_fn_ptr
1071 var_cell_handler)
1073 int try_again = 0;
1075 tor_assert(chan);
1076 tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
1078 log_debug(LD_CHANNEL,
1079 "Setting cell_handler callback for channel %p to %p",
1080 chan, cell_handler);
1081 log_debug(LD_CHANNEL,
1082 "Setting var_cell_handler callback for channel %p to %p",
1083 chan, var_cell_handler);
1085 /* Should we try the queue? */
1086 if (cell_handler &&
1087 cell_handler != chan->cell_handler) try_again = 1;
1088 if (var_cell_handler &&
1089 var_cell_handler != chan->var_cell_handler) try_again = 1;
1091 /* Change them */
1092 chan->cell_handler = cell_handler;
1093 chan->var_cell_handler = var_cell_handler;
1095 /* Re-run the queue if we have one and there's any reason to */
1096 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue) &&
1097 try_again &&
1098 (chan->cell_handler ||
1099 chan->var_cell_handler)) channel_process_cells(chan);
1103 * On closing channels
1105 * There are three functions that close channels, for use in
1106 * different circumstances:
1108 * - Use channel_mark_for_close() for most cases
1109 * - Use channel_close_from_lower_layer() if you are connection_or.c
1110 * and the other end closes the underlying connection.
1111 * - Use channel_close_for_error() if you are connection_or.c and
1112 * some sort of error has occurred.
1116 * Mark a channel for closure
1118 * This function tries to close a channel_t; it will go into the CLOSING
1119 * state, and eventually the lower layer should put it into the CLOSED or
1120 * ERROR state. Then, channel_run_cleanup() will eventually free it.
1123 void
1124 channel_mark_for_close(channel_t *chan)
1126 tor_assert(chan != NULL);
1127 tor_assert(chan->close != NULL);
1129 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1130 if (CHANNEL_CONDEMNED(chan))
1131 return;
1133 log_debug(LD_CHANNEL,
1134 "Closing channel %p (global ID " U64_FORMAT ") "
1135 "by request",
1136 chan, U64_PRINTF_ARG(chan->global_identifier));
1138 /* Note closing by request from above */
1139 chan->reason_for_closing = CHANNEL_CLOSE_REQUESTED;
1141 /* Change state to CLOSING */
1142 channel_change_state(chan, CHANNEL_STATE_CLOSING);
1144 /* Tell the lower layer */
1145 chan->close(chan);
1148 * It's up to the lower layer to change state to CLOSED or ERROR when we're
1149 * ready; we'll try to free channels that are in the finished list from
1150 * channel_run_cleanup(). The lower layer should do this by calling
1151 * channel_closed().
1156 * Mark a channel listener for closure
1158 * This function tries to close a channel_listener_t; it will go into the
1159 * CLOSING state, and eventually the lower layer should put it into the CLOSED
1160 * or ERROR state. Then, channel_run_cleanup() will eventually free it.
1163 void
1164 channel_listener_mark_for_close(channel_listener_t *chan_l)
1166 tor_assert(chan_l != NULL);
1167 tor_assert(chan_l->close != NULL);
1169 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1170 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
1171 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1172 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
1174 log_debug(LD_CHANNEL,
1175 "Closing channel listener %p (global ID " U64_FORMAT ") "
1176 "by request",
1177 chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
1179 /* Note closing by request from above */
1180 chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_REQUESTED;
1182 /* Change state to CLOSING */
1183 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
1185 /* Tell the lower layer */
1186 chan_l->close(chan_l);
1189 * It's up to the lower layer to change state to CLOSED or ERROR when we're
1190 * ready; we'll try to free channels that are in the finished list from
1191 * channel_run_cleanup(). The lower layer should do this by calling
1192 * channel_listener_closed().
1197 * Close a channel from the lower layer
1199 * Notify the channel code that the channel is being closed due to a non-error
1200 * condition in the lower layer. This does not call the close() method, since
1201 * the lower layer already knows.
1204 void
1205 channel_close_from_lower_layer(channel_t *chan)
1207 tor_assert(chan != NULL);
1209 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1210 if (CHANNEL_CONDEMNED(chan))
1211 return;
1213 log_debug(LD_CHANNEL,
1214 "Closing channel %p (global ID " U64_FORMAT ") "
1215 "due to lower-layer event",
1216 chan, U64_PRINTF_ARG(chan->global_identifier));
1218 /* Note closing by event from below */
1219 chan->reason_for_closing = CHANNEL_CLOSE_FROM_BELOW;
1221 /* Change state to CLOSING */
1222 channel_change_state(chan, CHANNEL_STATE_CLOSING);
1226 * Close a channel listener from the lower layer
1228 * Notify the channel code that the channel listener is being closed due to a
1229 * non-error condition in the lower layer. This does not call the close()
1230 * method, since the lower layer already knows.
1233 void
1234 channel_listener_close_from_lower_layer(channel_listener_t *chan_l)
1236 tor_assert(chan_l != NULL);
1238 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1239 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
1240 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1241 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
1243 log_debug(LD_CHANNEL,
1244 "Closing channel listener %p (global ID " U64_FORMAT ") "
1245 "due to lower-layer event",
1246 chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
1248 /* Note closing by event from below */
1249 chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_FROM_BELOW;
1251 /* Change state to CLOSING */
1252 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
1256 * Notify that the channel is being closed due to an error condition
1258 * This function is called by the lower layer implementing the transport
1259 * when a channel must be closed due to an error condition. This does not
1260 * call the channel's close method, since the lower layer already knows.
1263 void
1264 channel_close_for_error(channel_t *chan)
1266 tor_assert(chan != NULL);
1268 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1269 if (CHANNEL_CONDEMNED(chan))
1270 return;
1272 log_debug(LD_CHANNEL,
1273 "Closing channel %p due to lower-layer error",
1274 chan);
1276 /* Note closing by event from below */
1277 chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
1279 /* Change state to CLOSING */
1280 channel_change_state(chan, CHANNEL_STATE_CLOSING);
1284 * Notify that the channel listener is being closed due to an error condition
1286 * This function is called by the lower layer implementing the transport
1287 * when a channel listener must be closed due to an error condition. This
1288 * does not call the channel listener's close method, since the lower layer
1289 * already knows.
1292 void
1293 channel_listener_close_for_error(channel_listener_t *chan_l)
1295 tor_assert(chan_l != NULL);
1297 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1298 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
1299 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1300 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
1302 log_debug(LD_CHANNEL,
1303 "Closing channel listener %p (global ID " U64_FORMAT ") "
1304 "due to lower-layer error",
1305 chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
1307 /* Note closing by event from below */
1308 chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_FOR_ERROR;
1310 /* Change state to CLOSING */
1311 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
1315 * Notify that the lower layer is finished closing the channel
1317 * This function should be called by the lower layer when a channel
1318 * is finished closing and it should be regarded as inactive and
1319 * freed by the channel code.
1322 void
1323 channel_closed(channel_t *chan)
1325 tor_assert(chan);
1326 tor_assert(CHANNEL_CONDEMNED(chan));
1328 /* No-op if already inactive */
1329 if (CHANNEL_FINISHED(chan))
1330 return;
1332 /* Inform any pending (not attached) circs that they should
1333 * give up. */
1334 if (! chan->has_been_open)
1335 circuit_n_chan_done(chan, 0, 0);
1337 /* Now close all the attached circuits on it. */
1338 circuit_unlink_all_from_channel(chan, END_CIRC_REASON_CHANNEL_CLOSED);
1340 if (chan->reason_for_closing != CHANNEL_CLOSE_FOR_ERROR) {
1341 channel_change_state(chan, CHANNEL_STATE_CLOSED);
1342 } else {
1343 channel_change_state(chan, CHANNEL_STATE_ERROR);
1348 * Notify that the lower layer is finished closing the channel listener
1350 * This function should be called by the lower layer when a channel listener
1351 * is finished closing and it should be regarded as inactive and
1352 * freed by the channel code.
1355 void
1356 channel_listener_closed(channel_listener_t *chan_l)
1358 tor_assert(chan_l);
1359 tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
1360 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1361 chan_l->state == CHANNEL_LISTENER_STATE_ERROR);
1363 /* No-op if already inactive */
1364 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1365 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
1367 if (chan_l->reason_for_closing != CHANNEL_LISTENER_CLOSE_FOR_ERROR) {
1368 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSED);
1369 } else {
1370 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_ERROR);
1375 * Clear the identity_digest of a channel
1377 * This function clears the identity digest of the remote endpoint for a
1378 * channel; this is intended for use by the lower layer.
1381 void
1382 channel_clear_identity_digest(channel_t *chan)
1384 int state_not_in_map;
1386 tor_assert(chan);
1388 log_debug(LD_CHANNEL,
1389 "Clearing remote endpoint digest on channel %p with "
1390 "global ID " U64_FORMAT,
1391 chan, U64_PRINTF_ARG(chan->global_identifier));
1393 state_not_in_map = CHANNEL_CONDEMNED(chan);
1395 if (!state_not_in_map && chan->registered &&
1396 !tor_digest_is_zero(chan->identity_digest))
1397 /* if it's registered get it out of the digest map */
1398 channel_remove_from_digest_map(chan);
1400 memset(chan->identity_digest, 0,
1401 sizeof(chan->identity_digest));
1405 * Set the identity_digest of a channel
1407 * This function sets the identity digest of the remote endpoint for a
1408 * channel; this is intended for use by the lower layer.
1411 void
1412 channel_set_identity_digest(channel_t *chan,
1413 const char *identity_digest)
1415 int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
1417 tor_assert(chan);
1419 log_debug(LD_CHANNEL,
1420 "Setting remote endpoint digest on channel %p with "
1421 "global ID " U64_FORMAT " to digest %s",
1422 chan, U64_PRINTF_ARG(chan->global_identifier),
1423 identity_digest ?
1424 hex_str(identity_digest, DIGEST_LEN) : "(null)");
1426 state_not_in_map = CHANNEL_CONDEMNED(chan);
1428 was_in_digest_map =
1429 !state_not_in_map &&
1430 chan->registered &&
1431 !tor_digest_is_zero(chan->identity_digest);
1432 should_be_in_digest_map =
1433 !state_not_in_map &&
1434 chan->registered &&
1435 (identity_digest &&
1436 !tor_digest_is_zero(identity_digest));
1438 if (was_in_digest_map)
1439 /* We should always remove it; we'll add it back if we're writing
1440 * in a new digest.
1442 channel_remove_from_digest_map(chan);
1444 if (identity_digest) {
1445 memcpy(chan->identity_digest,
1446 identity_digest,
1447 sizeof(chan->identity_digest));
1448 } else {
1449 memset(chan->identity_digest, 0,
1450 sizeof(chan->identity_digest));
1453 /* Put it in the digest map if we should */
1454 if (should_be_in_digest_map)
1455 channel_add_to_digest_map(chan);
1459 * Clear the remote end metadata (identity_digest/nickname) of a channel
1461 * This function clears all the remote end info from a channel; this is
1462 * intended for use by the lower layer.
1465 void
1466 channel_clear_remote_end(channel_t *chan)
1468 int state_not_in_map;
1470 tor_assert(chan);
1472 log_debug(LD_CHANNEL,
1473 "Clearing remote endpoint identity on channel %p with "
1474 "global ID " U64_FORMAT,
1475 chan, U64_PRINTF_ARG(chan->global_identifier));
1477 state_not_in_map = CHANNEL_CONDEMNED(chan);
1479 if (!state_not_in_map && chan->registered &&
1480 !tor_digest_is_zero(chan->identity_digest))
1481 /* if it's registered get it out of the digest map */
1482 channel_remove_from_digest_map(chan);
1484 memset(chan->identity_digest, 0,
1485 sizeof(chan->identity_digest));
1486 tor_free(chan->nickname);
1490 * Set the remote end metadata (identity_digest/nickname) of a channel
1492 * This function sets new remote end info on a channel; this is intended
1493 * for use by the lower layer.
1496 void
1497 channel_set_remote_end(channel_t *chan,
1498 const char *identity_digest,
1499 const char *nickname)
1501 int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
1503 tor_assert(chan);
1505 log_debug(LD_CHANNEL,
1506 "Setting remote endpoint identity on channel %p with "
1507 "global ID " U64_FORMAT " to nickname %s, digest %s",
1508 chan, U64_PRINTF_ARG(chan->global_identifier),
1509 nickname ? nickname : "(null)",
1510 identity_digest ?
1511 hex_str(identity_digest, DIGEST_LEN) : "(null)");
1513 state_not_in_map = CHANNEL_CONDEMNED(chan);
1515 was_in_digest_map =
1516 !state_not_in_map &&
1517 chan->registered &&
1518 !tor_digest_is_zero(chan->identity_digest);
1519 should_be_in_digest_map =
1520 !state_not_in_map &&
1521 chan->registered &&
1522 (identity_digest &&
1523 !tor_digest_is_zero(identity_digest));
1525 if (was_in_digest_map)
1526 /* We should always remove it; we'll add it back if we're writing
1527 * in a new digest.
1529 channel_remove_from_digest_map(chan);
1531 if (identity_digest) {
1532 memcpy(chan->identity_digest,
1533 identity_digest,
1534 sizeof(chan->identity_digest));
1536 } else {
1537 memset(chan->identity_digest, 0,
1538 sizeof(chan->identity_digest));
1541 tor_free(chan->nickname);
1542 if (nickname)
1543 chan->nickname = tor_strdup(nickname);
1545 /* Put it in the digest map if we should */
1546 if (should_be_in_digest_map)
1547 channel_add_to_digest_map(chan);
1551 * Duplicate a cell queue entry; this is a shallow copy intended for use
1552 * in channel_write_cell_queue_entry().
1555 static cell_queue_entry_t *
1556 cell_queue_entry_dup(cell_queue_entry_t *q)
1558 cell_queue_entry_t *rv = NULL;
1560 tor_assert(q);
1562 rv = tor_malloc(sizeof(*rv));
1563 memcpy(rv, q, sizeof(*rv));
1565 return rv;
1569 * Free a cell_queue_entry_t; the handed_off parameter indicates whether
1570 * the contents were passed to the lower layer (it is responsible for
1571 * them) or not (we should free).
1574 STATIC void
1575 cell_queue_entry_free(cell_queue_entry_t *q, int handed_off)
1577 if (!q) return;
1579 if (!handed_off) {
1581 * If we handed it off, the recipient becomes responsible (or
1582 * with packed cells the channel_t subclass calls packed_cell
1583 * free after writing out its contents; see, e.g.,
1584 * channel_tls_write_packed_cell_method(). Otherwise, we have
1585 * to take care of it here if possible.
1587 switch (q->type) {
1588 case CELL_QUEUE_FIXED:
1589 if (q->u.fixed.cell) {
1591 * There doesn't seem to be a cell_free() function anywhere in the
1592 * pre-channel code; just use tor_free()
1594 tor_free(q->u.fixed.cell);
1596 break;
1597 case CELL_QUEUE_PACKED:
1598 if (q->u.packed.packed_cell) {
1599 packed_cell_free(q->u.packed.packed_cell);
1601 break;
1602 case CELL_QUEUE_VAR:
1603 if (q->u.var.var_cell) {
1605 * This one's in connection_or.c; it'd be nice to figure out the
1606 * whole flow of cells from one end to the other and factor the
1607 * cell memory management functions like this out of the specific
1608 * TLS lower layer.
1610 var_cell_free(q->u.var.var_cell);
1612 break;
1613 default:
1615 * Nothing we can do if we don't know the type; this will
1616 * have been warned about elsewhere.
1618 break;
1621 tor_free(q);
1624 #if 0
1626 * Check whether a cell queue entry is padding; this is a helper function
1627 * for channel_write_cell_queue_entry()
1630 static int
1631 cell_queue_entry_is_padding(cell_queue_entry_t *q)
1633 tor_assert(q);
1635 if (q->type == CELL_QUEUE_FIXED) {
1636 if (q->u.fixed.cell) {
1637 if (q->u.fixed.cell->command == CELL_PADDING ||
1638 q->u.fixed.cell->command == CELL_VPADDING) {
1639 return 1;
1642 } else if (q->type == CELL_QUEUE_VAR) {
1643 if (q->u.var.var_cell) {
1644 if (q->u.var.var_cell->command == CELL_PADDING ||
1645 q->u.var.var_cell->command == CELL_VPADDING) {
1646 return 1;
1651 return 0;
1653 #endif
1656 * Allocate a new cell queue entry for a fixed-size cell
1659 static cell_queue_entry_t *
1660 cell_queue_entry_new_fixed(cell_t *cell)
1662 cell_queue_entry_t *q = NULL;
1664 tor_assert(cell);
1666 q = tor_malloc(sizeof(*q));
1667 q->type = CELL_QUEUE_FIXED;
1668 q->u.fixed.cell = cell;
1670 return q;
1674 * Allocate a new cell queue entry for a variable-size cell
1677 static cell_queue_entry_t *
1678 cell_queue_entry_new_var(var_cell_t *var_cell)
1680 cell_queue_entry_t *q = NULL;
1682 tor_assert(var_cell);
1684 q = tor_malloc(sizeof(*q));
1685 q->type = CELL_QUEUE_VAR;
1686 q->u.var.var_cell = var_cell;
1688 return q;
1692 * Ask how big the cell contained in a cell_queue_entry_t is
1695 static size_t
1696 channel_get_cell_queue_entry_size(channel_t *chan, cell_queue_entry_t *q)
1698 size_t rv = 0;
1700 tor_assert(chan);
1701 tor_assert(q);
1703 switch (q->type) {
1704 case CELL_QUEUE_FIXED:
1705 rv = get_cell_network_size(chan->wide_circ_ids);
1706 break;
1707 case CELL_QUEUE_VAR:
1708 rv = get_var_cell_header_size(chan->wide_circ_ids) +
1709 (q->u.var.var_cell ? q->u.var.var_cell->payload_len : 0);
1710 break;
1711 case CELL_QUEUE_PACKED:
1712 rv = get_cell_network_size(chan->wide_circ_ids);
1713 break;
1714 default:
1715 tor_assert(1);
1718 return rv;
1722 * Write to a channel based on a cell_queue_entry_t
1724 * Given a cell_queue_entry_t filled out by the caller, try to send the cell
1725 * and queue it if we can't.
1728 static void
1729 channel_write_cell_queue_entry(channel_t *chan, cell_queue_entry_t *q)
1731 int result = 0, sent = 0;
1732 cell_queue_entry_t *tmp = NULL;
1733 size_t cell_bytes;
1735 tor_assert(chan);
1736 tor_assert(q);
1738 /* Assert that the state makes sense for a cell write */
1739 tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
1742 circid_t circ_id;
1743 if (is_destroy_cell(chan, q, &circ_id)) {
1744 channel_note_destroy_not_pending(chan, circ_id);
1748 /* For statistical purposes, figure out how big this cell is */
1749 cell_bytes = channel_get_cell_queue_entry_size(chan, q);
1751 /* Can we send it right out? If so, try */
1752 if (TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue) &&
1753 CHANNEL_IS_OPEN(chan)) {
1754 /* Pick the right write function for this cell type and save the result */
1755 switch (q->type) {
1756 case CELL_QUEUE_FIXED:
1757 tor_assert(chan->write_cell);
1758 tor_assert(q->u.fixed.cell);
1759 result = chan->write_cell(chan, q->u.fixed.cell);
1760 break;
1761 case CELL_QUEUE_PACKED:
1762 tor_assert(chan->write_packed_cell);
1763 tor_assert(q->u.packed.packed_cell);
1764 result = chan->write_packed_cell(chan, q->u.packed.packed_cell);
1765 break;
1766 case CELL_QUEUE_VAR:
1767 tor_assert(chan->write_var_cell);
1768 tor_assert(q->u.var.var_cell);
1769 result = chan->write_var_cell(chan, q->u.var.var_cell);
1770 break;
1771 default:
1772 tor_assert(1);
1775 /* Check if we got it out */
1776 if (result > 0) {
1777 sent = 1;
1778 /* Timestamp for transmission */
1779 channel_timestamp_xmit(chan);
1780 /* If we're here the queue is empty, so it's drained too */
1781 channel_timestamp_drained(chan);
1782 /* Update the counter */
1783 ++(chan->n_cells_xmitted);
1784 chan->n_bytes_xmitted += cell_bytes;
1785 /* Update global counters */
1786 ++n_channel_cells_queued;
1787 ++n_channel_cells_passed_to_lower_layer;
1788 n_channel_bytes_queued += cell_bytes;
1789 n_channel_bytes_passed_to_lower_layer += cell_bytes;
1790 channel_assert_counter_consistency();
1794 if (!sent) {
1795 /* Not sent, queue it */
1797 * We have to copy the queue entry passed in, since the caller probably
1798 * used the stack.
1800 tmp = cell_queue_entry_dup(q);
1801 TOR_SIMPLEQ_INSERT_TAIL(&chan->outgoing_queue, tmp, next);
1802 /* Update global counters */
1803 ++n_channel_cells_queued;
1804 ++n_channel_cells_in_queues;
1805 n_channel_bytes_queued += cell_bytes;
1806 n_channel_bytes_in_queues += cell_bytes;
1807 channel_assert_counter_consistency();
1808 /* Update channel queue size */
1809 chan->bytes_in_queue += cell_bytes;
1810 /* Try to process the queue? */
1811 if (CHANNEL_IS_OPEN(chan)) channel_flush_cells(chan);
1816 * Write a cell to a channel
1818 * Write a fixed-length cell to a channel using the write_cell() method.
1819 * This is equivalent to the pre-channels connection_or_write_cell_to_buf();
1820 * it is called by the transport-independent code to deliver a cell to a
1821 * channel for transmission.
1824 void
1825 channel_write_cell(channel_t *chan, cell_t *cell)
1827 cell_queue_entry_t q;
1829 tor_assert(chan);
1830 tor_assert(cell);
1832 if (CHANNEL_IS_CLOSING(chan)) {
1833 log_debug(LD_CHANNEL, "Discarding cell_t %p on closing channel %p with "
1834 "global ID "U64_FORMAT, cell, chan,
1835 U64_PRINTF_ARG(chan->global_identifier));
1836 tor_free(cell);
1837 return;
1840 log_debug(LD_CHANNEL,
1841 "Writing cell_t %p to channel %p with global ID "
1842 U64_FORMAT,
1843 cell, chan, U64_PRINTF_ARG(chan->global_identifier));
1845 q.type = CELL_QUEUE_FIXED;
1846 q.u.fixed.cell = cell;
1847 channel_write_cell_queue_entry(chan, &q);
1849 /* Update the queue size estimate */
1850 channel_update_xmit_queue_size(chan);
1854 * Write a packed cell to a channel
1856 * Write a packed cell to a channel using the write_cell() method. This is
1857 * called by the transport-independent code to deliver a packed cell to a
1858 * channel for transmission.
1861 void
1862 channel_write_packed_cell(channel_t *chan, packed_cell_t *packed_cell)
1864 cell_queue_entry_t q;
1866 tor_assert(chan);
1867 tor_assert(packed_cell);
1869 if (CHANNEL_IS_CLOSING(chan)) {
1870 log_debug(LD_CHANNEL, "Discarding packed_cell_t %p on closing channel %p "
1871 "with global ID "U64_FORMAT, packed_cell, chan,
1872 U64_PRINTF_ARG(chan->global_identifier));
1873 packed_cell_free(packed_cell);
1874 return;
1877 log_debug(LD_CHANNEL,
1878 "Writing packed_cell_t %p to channel %p with global ID "
1879 U64_FORMAT,
1880 packed_cell, chan,
1881 U64_PRINTF_ARG(chan->global_identifier));
1883 q.type = CELL_QUEUE_PACKED;
1884 q.u.packed.packed_cell = packed_cell;
1885 channel_write_cell_queue_entry(chan, &q);
1887 /* Update the queue size estimate */
1888 channel_update_xmit_queue_size(chan);
1892 * Write a variable-length cell to a channel
1894 * Write a variable-length cell to a channel using the write_cell() method.
1895 * This is equivalent to the pre-channels
1896 * connection_or_write_var_cell_to_buf(); it's called by the transport-
1897 * independent code to deliver a var_cell to a channel for transmission.
1900 void
1901 channel_write_var_cell(channel_t *chan, var_cell_t *var_cell)
1903 cell_queue_entry_t q;
1905 tor_assert(chan);
1906 tor_assert(var_cell);
1908 if (CHANNEL_IS_CLOSING(chan)) {
1909 log_debug(LD_CHANNEL, "Discarding var_cell_t %p on closing channel %p "
1910 "with global ID "U64_FORMAT, var_cell, chan,
1911 U64_PRINTF_ARG(chan->global_identifier));
1912 var_cell_free(var_cell);
1913 return;
1916 log_debug(LD_CHANNEL,
1917 "Writing var_cell_t %p to channel %p with global ID "
1918 U64_FORMAT,
1919 var_cell, chan,
1920 U64_PRINTF_ARG(chan->global_identifier));
1922 q.type = CELL_QUEUE_VAR;
1923 q.u.var.var_cell = var_cell;
1924 channel_write_cell_queue_entry(chan, &q);
1926 /* Update the queue size estimate */
1927 channel_update_xmit_queue_size(chan);
1931 * Change channel state
1933 * This internal and subclass use only function is used to change channel
1934 * state, performing all transition validity checks and whatever actions
1935 * are appropriate to the state transition in question.
1938 void
1939 channel_change_state(channel_t *chan, channel_state_t to_state)
1941 channel_state_t from_state;
1942 unsigned char was_active, is_active;
1943 unsigned char was_in_id_map, is_in_id_map;
1945 tor_assert(chan);
1946 from_state = chan->state;
1948 tor_assert(channel_state_is_valid(from_state));
1949 tor_assert(channel_state_is_valid(to_state));
1950 tor_assert(channel_state_can_transition(chan->state, to_state));
1952 /* Check for no-op transitions */
1953 if (from_state == to_state) {
1954 log_debug(LD_CHANNEL,
1955 "Got no-op transition from \"%s\" to itself on channel %p"
1956 "(global ID " U64_FORMAT ")",
1957 channel_state_to_string(to_state),
1958 chan, U64_PRINTF_ARG(chan->global_identifier));
1959 return;
1962 /* If we're going to a closing or closed state, we must have a reason set */
1963 if (to_state == CHANNEL_STATE_CLOSING ||
1964 to_state == CHANNEL_STATE_CLOSED ||
1965 to_state == CHANNEL_STATE_ERROR) {
1966 tor_assert(chan->reason_for_closing != CHANNEL_NOT_CLOSING);
1970 * We need to maintain the queues here for some transitions:
1971 * when we enter CHANNEL_STATE_OPEN (especially from CHANNEL_STATE_MAINT)
1972 * we may have a backlog of cells to transmit, so drain the queues in
1973 * that case, and when going to CHANNEL_STATE_CLOSED the subclass
1974 * should have made sure to finish sending things (or gone to
1975 * CHANNEL_STATE_ERROR if not possible), so we assert for that here.
1978 log_debug(LD_CHANNEL,
1979 "Changing state of channel %p (global ID " U64_FORMAT
1980 ") from \"%s\" to \"%s\"",
1981 chan,
1982 U64_PRINTF_ARG(chan->global_identifier),
1983 channel_state_to_string(chan->state),
1984 channel_state_to_string(to_state));
1986 chan->state = to_state;
1988 /* Need to add to the right lists if the channel is registered */
1989 if (chan->registered) {
1990 was_active = !(from_state == CHANNEL_STATE_CLOSED ||
1991 from_state == CHANNEL_STATE_ERROR);
1992 is_active = !(to_state == CHANNEL_STATE_CLOSED ||
1993 to_state == CHANNEL_STATE_ERROR);
1995 /* Need to take off active list and put on finished list? */
1996 if (was_active && !is_active) {
1997 if (active_channels) smartlist_remove(active_channels, chan);
1998 if (!finished_channels) finished_channels = smartlist_new();
1999 smartlist_add(finished_channels, chan);
2001 /* Need to put on active list? */
2002 else if (!was_active && is_active) {
2003 if (finished_channels) smartlist_remove(finished_channels, chan);
2004 if (!active_channels) active_channels = smartlist_new();
2005 smartlist_add(active_channels, chan);
2008 if (!tor_digest_is_zero(chan->identity_digest)) {
2009 /* Now we need to handle the identity map */
2010 was_in_id_map = !(from_state == CHANNEL_STATE_CLOSING ||
2011 from_state == CHANNEL_STATE_CLOSED ||
2012 from_state == CHANNEL_STATE_ERROR);
2013 is_in_id_map = !(to_state == CHANNEL_STATE_CLOSING ||
2014 to_state == CHANNEL_STATE_CLOSED ||
2015 to_state == CHANNEL_STATE_ERROR);
2017 if (!was_in_id_map && is_in_id_map) channel_add_to_digest_map(chan);
2018 else if (was_in_id_map && !is_in_id_map)
2019 channel_remove_from_digest_map(chan);
2024 * If we're going to a closed/closing state, we don't need scheduling any
2025 * more; in CHANNEL_STATE_MAINT we can't accept writes.
2027 if (to_state == CHANNEL_STATE_CLOSING ||
2028 to_state == CHANNEL_STATE_CLOSED ||
2029 to_state == CHANNEL_STATE_ERROR) {
2030 scheduler_release_channel(chan);
2031 } else if (to_state == CHANNEL_STATE_MAINT) {
2032 scheduler_channel_doesnt_want_writes(chan);
2036 * If we're closing, this channel no longer counts toward the global
2037 * estimated queue size; if we're open, it now does.
2039 if ((to_state == CHANNEL_STATE_CLOSING ||
2040 to_state == CHANNEL_STATE_CLOSED ||
2041 to_state == CHANNEL_STATE_ERROR) &&
2042 (from_state == CHANNEL_STATE_OPEN ||
2043 from_state == CHANNEL_STATE_MAINT)) {
2044 estimated_total_queue_size -= chan->bytes_in_queue;
2048 * If we're opening, this channel now does count toward the global
2049 * estimated queue size.
2051 if ((to_state == CHANNEL_STATE_OPEN ||
2052 to_state == CHANNEL_STATE_MAINT) &&
2053 !(from_state == CHANNEL_STATE_OPEN ||
2054 from_state == CHANNEL_STATE_MAINT)) {
2055 estimated_total_queue_size += chan->bytes_in_queue;
2058 /* Tell circuits if we opened and stuff */
2059 if (to_state == CHANNEL_STATE_OPEN) {
2060 channel_do_open_actions(chan);
2061 chan->has_been_open = 1;
2063 /* Check for queued cells to process */
2064 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
2065 channel_process_cells(chan);
2066 if (! TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue))
2067 channel_flush_cells(chan);
2068 } else if (to_state == CHANNEL_STATE_CLOSED ||
2069 to_state == CHANNEL_STATE_ERROR) {
2070 /* Assert that all queues are empty */
2071 tor_assert(TOR_SIMPLEQ_EMPTY(&chan->incoming_queue));
2072 tor_assert(TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue));
2077 * Change channel listener state
2079 * This internal and subclass use only function is used to change channel
2080 * listener state, performing all transition validity checks and whatever
2081 * actions are appropriate to the state transition in question.
2084 void
2085 channel_listener_change_state(channel_listener_t *chan_l,
2086 channel_listener_state_t to_state)
2088 channel_listener_state_t from_state;
2089 unsigned char was_active, is_active;
2091 tor_assert(chan_l);
2092 from_state = chan_l->state;
2094 tor_assert(channel_listener_state_is_valid(from_state));
2095 tor_assert(channel_listener_state_is_valid(to_state));
2096 tor_assert(channel_listener_state_can_transition(chan_l->state, to_state));
2098 /* Check for no-op transitions */
2099 if (from_state == to_state) {
2100 log_debug(LD_CHANNEL,
2101 "Got no-op transition from \"%s\" to itself on channel "
2102 "listener %p (global ID " U64_FORMAT ")",
2103 channel_listener_state_to_string(to_state),
2104 chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
2105 return;
2108 /* If we're going to a closing or closed state, we must have a reason set */
2109 if (to_state == CHANNEL_LISTENER_STATE_CLOSING ||
2110 to_state == CHANNEL_LISTENER_STATE_CLOSED ||
2111 to_state == CHANNEL_LISTENER_STATE_ERROR) {
2112 tor_assert(chan_l->reason_for_closing != CHANNEL_LISTENER_NOT_CLOSING);
2116 * We need to maintain the queues here for some transitions:
2117 * when we enter CHANNEL_STATE_OPEN (especially from CHANNEL_STATE_MAINT)
2118 * we may have a backlog of cells to transmit, so drain the queues in
2119 * that case, and when going to CHANNEL_STATE_CLOSED the subclass
2120 * should have made sure to finish sending things (or gone to
2121 * CHANNEL_STATE_ERROR if not possible), so we assert for that here.
2124 log_debug(LD_CHANNEL,
2125 "Changing state of channel listener %p (global ID " U64_FORMAT
2126 "from \"%s\" to \"%s\"",
2127 chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
2128 channel_listener_state_to_string(chan_l->state),
2129 channel_listener_state_to_string(to_state));
2131 chan_l->state = to_state;
2133 /* Need to add to the right lists if the channel listener is registered */
2134 if (chan_l->registered) {
2135 was_active = !(from_state == CHANNEL_LISTENER_STATE_CLOSED ||
2136 from_state == CHANNEL_LISTENER_STATE_ERROR);
2137 is_active = !(to_state == CHANNEL_LISTENER_STATE_CLOSED ||
2138 to_state == CHANNEL_LISTENER_STATE_ERROR);
2140 /* Need to take off active list and put on finished list? */
2141 if (was_active && !is_active) {
2142 if (active_listeners) smartlist_remove(active_listeners, chan_l);
2143 if (!finished_listeners) finished_listeners = smartlist_new();
2144 smartlist_add(finished_listeners, chan_l);
2146 /* Need to put on active list? */
2147 else if (!was_active && is_active) {
2148 if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
2149 if (!active_listeners) active_listeners = smartlist_new();
2150 smartlist_add(active_listeners, chan_l);
2154 if (to_state == CHANNEL_LISTENER_STATE_CLOSED ||
2155 to_state == CHANNEL_LISTENER_STATE_ERROR) {
2156 /* Assert that the queue is empty */
2157 tor_assert(!(chan_l->incoming_list) ||
2158 smartlist_len(chan_l->incoming_list) == 0);
2163 * Try to flush cells to the lower layer
2165 * this is called by the lower layer to indicate that it wants more cells;
2166 * it will try to write up to num_cells cells from the channel's cell queue or
2167 * from circuits active on that channel, or as many as it has available if
2168 * num_cells == -1.
2171 #define MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED 256
2173 MOCK_IMPL(ssize_t,
2174 channel_flush_some_cells, (channel_t *chan, ssize_t num_cells))
2176 unsigned int unlimited = 0;
2177 ssize_t flushed = 0;
2178 int num_cells_from_circs, clamped_num_cells;
2179 int q_len_before, q_len_after;
2181 tor_assert(chan);
2183 if (num_cells < 0) unlimited = 1;
2184 if (!unlimited && num_cells <= flushed) goto done;
2186 /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
2187 if (CHANNEL_IS_OPEN(chan)) {
2188 /* Try to flush as much as we can that's already queued */
2189 flushed += channel_flush_some_cells_from_outgoing_queue(chan,
2190 (unlimited ? -1 : num_cells - flushed));
2191 if (!unlimited && num_cells <= flushed) goto done;
2193 if (circuitmux_num_cells(chan->cmux) > 0) {
2194 /* Calculate number of cells, including clamp */
2195 if (unlimited) {
2196 clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
2197 } else {
2198 if (num_cells - flushed >
2199 MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED) {
2200 clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
2201 } else {
2202 clamped_num_cells = (int)(num_cells - flushed);
2207 * Keep track of the change in queue size; we have to count cells
2208 * channel_flush_from_first_active_circuit() writes out directly,
2209 * but not double-count ones we might get later in
2210 * channel_flush_some_cells_from_outgoing_queue()
2212 q_len_before = chan_cell_queue_len(&(chan->outgoing_queue));
2214 /* Try to get more cells from any active circuits */
2215 num_cells_from_circs = channel_flush_from_first_active_circuit(
2216 chan, clamped_num_cells);
2218 q_len_after = chan_cell_queue_len(&(chan->outgoing_queue));
2221 * If it claims we got some, adjust the flushed counter and consider
2222 * processing the queue again
2224 if (num_cells_from_circs > 0) {
2226 * Adjust flushed by the number of cells counted in
2227 * num_cells_from_circs that didn't go to the cell queue.
2230 if (q_len_after > q_len_before) {
2231 num_cells_from_circs -= (q_len_after - q_len_before);
2232 if (num_cells_from_circs < 0) num_cells_from_circs = 0;
2235 flushed += num_cells_from_circs;
2237 /* Now process the queue if necessary */
2239 if ((q_len_after > q_len_before) &&
2240 (unlimited || (flushed < num_cells))) {
2241 flushed += channel_flush_some_cells_from_outgoing_queue(chan,
2242 (unlimited ? -1 : num_cells - flushed));
2248 done:
2249 return flushed;
2253 * Flush cells from just the channel's outgoing cell queue
2255 * This gets called from channel_flush_some_cells() above to flush cells
2256 * just from the queue without trying for active_circuits.
2259 static ssize_t
2260 channel_flush_some_cells_from_outgoing_queue(channel_t *chan,
2261 ssize_t num_cells)
2263 unsigned int unlimited = 0;
2264 ssize_t flushed = 0;
2265 cell_queue_entry_t *q = NULL;
2266 size_t cell_size;
2267 int free_q = 0, handed_off = 0;
2269 tor_assert(chan);
2270 tor_assert(chan->write_cell);
2271 tor_assert(chan->write_packed_cell);
2272 tor_assert(chan->write_var_cell);
2274 if (num_cells < 0) unlimited = 1;
2275 if (!unlimited && num_cells <= flushed) return 0;
2277 /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
2278 if (CHANNEL_IS_OPEN(chan)) {
2279 while ((unlimited || num_cells > flushed) &&
2280 NULL != (q = TOR_SIMPLEQ_FIRST(&chan->outgoing_queue))) {
2281 free_q = 0;
2282 handed_off = 0;
2284 if (1) {
2285 /* Figure out how big it is for statistical purposes */
2286 cell_size = channel_get_cell_queue_entry_size(chan, q);
2288 * Okay, we have a good queue entry, try to give it to the lower
2289 * layer.
2291 switch (q->type) {
2292 case CELL_QUEUE_FIXED:
2293 if (q->u.fixed.cell) {
2294 if (chan->write_cell(chan,
2295 q->u.fixed.cell)) {
2296 ++flushed;
2297 channel_timestamp_xmit(chan);
2298 ++(chan->n_cells_xmitted);
2299 chan->n_bytes_xmitted += cell_size;
2300 free_q = 1;
2301 handed_off = 1;
2303 /* Else couldn't write it; leave it on the queue */
2304 } else {
2305 /* This shouldn't happen */
2306 log_info(LD_CHANNEL,
2307 "Saw broken cell queue entry of type CELL_QUEUE_FIXED "
2308 "with no cell on channel %p "
2309 "(global ID " U64_FORMAT ").",
2310 chan, U64_PRINTF_ARG(chan->global_identifier));
2311 /* Throw it away */
2312 free_q = 1;
2313 handed_off = 0;
2315 break;
2316 case CELL_QUEUE_PACKED:
2317 if (q->u.packed.packed_cell) {
2318 if (chan->write_packed_cell(chan,
2319 q->u.packed.packed_cell)) {
2320 ++flushed;
2321 channel_timestamp_xmit(chan);
2322 ++(chan->n_cells_xmitted);
2323 chan->n_bytes_xmitted += cell_size;
2324 free_q = 1;
2325 handed_off = 1;
2327 /* Else couldn't write it; leave it on the queue */
2328 } else {
2329 /* This shouldn't happen */
2330 log_info(LD_CHANNEL,
2331 "Saw broken cell queue entry of type CELL_QUEUE_PACKED "
2332 "with no cell on channel %p "
2333 "(global ID " U64_FORMAT ").",
2334 chan, U64_PRINTF_ARG(chan->global_identifier));
2335 /* Throw it away */
2336 free_q = 1;
2337 handed_off = 0;
2339 break;
2340 case CELL_QUEUE_VAR:
2341 if (q->u.var.var_cell) {
2342 if (chan->write_var_cell(chan,
2343 q->u.var.var_cell)) {
2344 ++flushed;
2345 channel_timestamp_xmit(chan);
2346 ++(chan->n_cells_xmitted);
2347 chan->n_bytes_xmitted += cell_size;
2348 free_q = 1;
2349 handed_off = 1;
2351 /* Else couldn't write it; leave it on the queue */
2352 } else {
2353 /* This shouldn't happen */
2354 log_info(LD_CHANNEL,
2355 "Saw broken cell queue entry of type CELL_QUEUE_VAR "
2356 "with no cell on channel %p "
2357 "(global ID " U64_FORMAT ").",
2358 chan, U64_PRINTF_ARG(chan->global_identifier));
2359 /* Throw it away */
2360 free_q = 1;
2361 handed_off = 0;
2363 break;
2364 default:
2365 /* Unknown type, log and free it */
2366 log_info(LD_CHANNEL,
2367 "Saw an unknown cell queue entry type %d on channel %p "
2368 "(global ID " U64_FORMAT "; ignoring it."
2369 " Someone should fix this.",
2370 q->type, chan, U64_PRINTF_ARG(chan->global_identifier));
2371 free_q = 1;
2372 handed_off = 0;
2376 * if free_q is set, we used it and should remove the queue entry;
2377 * we have to do the free down here so TOR_SIMPLEQ_REMOVE_HEAD isn't
2378 * accessing freed memory
2380 if (free_q) {
2381 TOR_SIMPLEQ_REMOVE_HEAD(&chan->outgoing_queue, next);
2383 * ...and we handed a cell off to the lower layer, so we should
2384 * update the counters.
2386 ++n_channel_cells_passed_to_lower_layer;
2387 --n_channel_cells_in_queues;
2388 n_channel_bytes_passed_to_lower_layer += cell_size;
2389 n_channel_bytes_in_queues -= cell_size;
2390 channel_assert_counter_consistency();
2391 /* Update the channel's queue size too */
2392 chan->bytes_in_queue -= cell_size;
2393 /* Finally, free q */
2394 cell_queue_entry_free(q, handed_off);
2395 q = NULL;
2397 /* No cell removed from list, so we can't go on any further */
2398 else break;
2403 /* Did we drain the queue? */
2404 if (TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue)) {
2405 channel_timestamp_drained(chan);
2408 /* Update the estimate queue size */
2409 channel_update_xmit_queue_size(chan);
2411 return flushed;
2415 * Flush as many cells as we possibly can from the queue
2417 * This tries to flush as many cells from the queue as the lower layer
2418 * will take. It just calls channel_flush_some_cells_from_outgoing_queue()
2419 * in unlimited mode.
2422 void
2423 channel_flush_cells(channel_t *chan)
2425 channel_flush_some_cells_from_outgoing_queue(chan, -1);
2429 * Check if any cells are available
2431 * This gets used from the lower layer to check if any more cells are
2432 * available.
2436 channel_more_to_flush(channel_t *chan)
2438 tor_assert(chan);
2440 /* Check if we have any queued */
2441 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
2442 return 1;
2444 /* Check if any circuits would like to queue some */
2445 if (circuitmux_num_cells(chan->cmux) > 0) return 1;
2447 /* Else no */
2448 return 0;
2452 * Notify the channel we're done flushing the output in the lower layer
2454 * Connection.c will call this when we've flushed the output; there's some
2455 * dirreq-related maintenance to do.
2458 void
2459 channel_notify_flushed(channel_t *chan)
2461 tor_assert(chan);
2463 if (chan->dirreq_id != 0)
2464 geoip_change_dirreq_state(chan->dirreq_id,
2465 DIRREQ_TUNNELED,
2466 DIRREQ_CHANNEL_BUFFER_FLUSHED);
2470 * Process the queue of incoming channels on a listener
2472 * Use a listener's registered callback to process as many entries in the
2473 * queue of incoming channels as possible.
2476 void
2477 channel_listener_process_incoming(channel_listener_t *listener)
2479 tor_assert(listener);
2482 * CHANNEL_LISTENER_STATE_CLOSING permitted because we drain the queue
2483 * while closing a listener.
2485 tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING ||
2486 listener->state == CHANNEL_LISTENER_STATE_CLOSING);
2487 tor_assert(listener->listener);
2489 log_debug(LD_CHANNEL,
2490 "Processing queue of incoming connections for channel "
2491 "listener %p (global ID " U64_FORMAT ")",
2492 listener, U64_PRINTF_ARG(listener->global_identifier));
2494 if (!(listener->incoming_list)) return;
2496 SMARTLIST_FOREACH_BEGIN(listener->incoming_list,
2497 channel_t *, chan) {
2498 tor_assert(chan);
2500 log_debug(LD_CHANNEL,
2501 "Handling incoming channel %p (" U64_FORMAT ") "
2502 "for listener %p (" U64_FORMAT ")",
2503 chan,
2504 U64_PRINTF_ARG(chan->global_identifier),
2505 listener,
2506 U64_PRINTF_ARG(listener->global_identifier));
2507 /* Make sure this is set correctly */
2508 channel_mark_incoming(chan);
2509 listener->listener(listener, chan);
2510 } SMARTLIST_FOREACH_END(chan);
2512 smartlist_free(listener->incoming_list);
2513 listener->incoming_list = NULL;
2517 * Take actions required when a channel becomes open
2519 * Handle actions we should do when we know a channel is open; a lot of
2520 * this comes from the old connection_or_set_state_open() of connection_or.c.
2522 * Because of this mechanism, future channel_t subclasses should take care
2523 * not to change a channel to from CHANNEL_STATE_OPENING to CHANNEL_STATE_OPEN
2524 * until there is positive confirmation that the network is operational.
2525 * In particular, anything UDP-based should not make this transition until a
2526 * packet is received from the other side.
2529 void
2530 channel_do_open_actions(channel_t *chan)
2532 tor_addr_t remote_addr;
2533 int started_here;
2534 time_t now = time(NULL);
2535 int close_origin_circuits = 0;
2537 tor_assert(chan);
2539 started_here = channel_is_outgoing(chan);
2541 if (started_here) {
2542 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
2543 rep_hist_note_connect_succeeded(chan->identity_digest, now);
2544 if (entry_guard_register_connect_status(
2545 chan->identity_digest, 1, 0, now) < 0) {
2546 /* Close any circuits pending on this channel. We leave it in state
2547 * 'open' though, because it didn't actually *fail* -- we just
2548 * chose not to use it. */
2549 log_debug(LD_OR,
2550 "New entry guard was reachable, but closing this "
2551 "connection so we can retry the earlier entry guards.");
2552 close_origin_circuits = 1;
2554 router_set_status(chan->identity_digest, 1);
2555 } else {
2556 /* only report it to the geoip module if it's not a known router */
2557 if (!router_get_by_id_digest(chan->identity_digest)) {
2558 if (channel_get_addr_if_possible(chan, &remote_addr)) {
2559 char *transport_name = NULL;
2560 if (chan->get_transport_name(chan, &transport_name) < 0)
2561 transport_name = NULL;
2563 geoip_note_client_seen(GEOIP_CLIENT_CONNECT,
2564 &remote_addr, transport_name,
2565 now);
2566 tor_free(transport_name);
2568 /* Otherwise the underlying transport can't tell us this, so skip it */
2572 circuit_n_chan_done(chan, 1, close_origin_circuits);
2576 * Queue an incoming channel on a listener
2578 * Internal and subclass use only function to queue an incoming channel from
2579 * a listener. A subclass of channel_listener_t should call this when a new
2580 * incoming channel is created.
2583 void
2584 channel_listener_queue_incoming(channel_listener_t *listener,
2585 channel_t *incoming)
2587 int need_to_queue = 0;
2589 tor_assert(listener);
2590 tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING);
2591 tor_assert(incoming);
2593 log_debug(LD_CHANNEL,
2594 "Queueing incoming channel %p (global ID " U64_FORMAT ") on "
2595 "channel listener %p (global ID " U64_FORMAT ")",
2596 incoming, U64_PRINTF_ARG(incoming->global_identifier),
2597 listener, U64_PRINTF_ARG(listener->global_identifier));
2599 /* Do we need to queue it, or can we just call the listener right away? */
2600 if (!(listener->listener)) need_to_queue = 1;
2601 if (listener->incoming_list &&
2602 (smartlist_len(listener->incoming_list) > 0))
2603 need_to_queue = 1;
2605 /* If we need to queue and have no queue, create one */
2606 if (need_to_queue && !(listener->incoming_list)) {
2607 listener->incoming_list = smartlist_new();
2610 /* Bump the counter and timestamp it */
2611 channel_listener_timestamp_active(listener);
2612 channel_listener_timestamp_accepted(listener);
2613 ++(listener->n_accepted);
2615 /* If we don't need to queue, process it right away */
2616 if (!need_to_queue) {
2617 tor_assert(listener->listener);
2618 listener->listener(listener, incoming);
2621 * Otherwise, we need to queue; queue and then process the queue if
2622 * we can.
2624 else {
2625 tor_assert(listener->incoming_list);
2626 smartlist_add(listener->incoming_list, incoming);
2627 if (listener->listener) channel_listener_process_incoming(listener);
2632 * Process queued incoming cells
2634 * Process as many queued cells as we can from the incoming
2635 * cell queue.
2638 void
2639 channel_process_cells(channel_t *chan)
2641 cell_queue_entry_t *q;
2642 tor_assert(chan);
2643 tor_assert(CHANNEL_IS_CLOSING(chan) || CHANNEL_IS_MAINT(chan) ||
2644 CHANNEL_IS_OPEN(chan));
2646 log_debug(LD_CHANNEL,
2647 "Processing as many incoming cells as we can for channel %p",
2648 chan);
2650 /* Nothing we can do if we have no registered cell handlers */
2651 if (!(chan->cell_handler ||
2652 chan->var_cell_handler)) return;
2653 /* Nothing we can do if we have no cells */
2654 if (TOR_SIMPLEQ_EMPTY(&chan->incoming_queue)) return;
2657 * Process cells until we're done or find one we have no current handler
2658 * for.
2660 * We must free the cells here after calling the handler, since custody
2661 * of the buffer was given to the channel layer when they were queued;
2662 * see comments on memory management in channel_queue_cell() and in
2663 * channel_queue_var_cell() below.
2665 while (NULL != (q = TOR_SIMPLEQ_FIRST(&chan->incoming_queue))) {
2666 tor_assert(q);
2667 tor_assert(q->type == CELL_QUEUE_FIXED ||
2668 q->type == CELL_QUEUE_VAR);
2670 if (q->type == CELL_QUEUE_FIXED &&
2671 chan->cell_handler) {
2672 /* Handle a fixed-length cell */
2673 TOR_SIMPLEQ_REMOVE_HEAD(&chan->incoming_queue, next);
2674 tor_assert(q->u.fixed.cell);
2675 log_debug(LD_CHANNEL,
2676 "Processing incoming cell_t %p for channel %p (global ID "
2677 U64_FORMAT ")",
2678 q->u.fixed.cell, chan,
2679 U64_PRINTF_ARG(chan->global_identifier));
2680 chan->cell_handler(chan, q->u.fixed.cell);
2681 tor_free(q->u.fixed.cell);
2682 tor_free(q);
2683 } else if (q->type == CELL_QUEUE_VAR &&
2684 chan->var_cell_handler) {
2685 /* Handle a variable-length cell */
2686 TOR_SIMPLEQ_REMOVE_HEAD(&chan->incoming_queue, next);
2687 tor_assert(q->u.var.var_cell);
2688 log_debug(LD_CHANNEL,
2689 "Processing incoming var_cell_t %p for channel %p (global ID "
2690 U64_FORMAT ")",
2691 q->u.var.var_cell, chan,
2692 U64_PRINTF_ARG(chan->global_identifier));
2693 chan->var_cell_handler(chan, q->u.var.var_cell);
2694 tor_free(q->u.var.var_cell);
2695 tor_free(q);
2696 } else {
2697 /* Can't handle this one */
2698 break;
2704 * Queue incoming cell
2706 * This should be called by a channel_t subclass to queue an incoming fixed-
2707 * length cell for processing, and process it if possible.
2710 void
2711 channel_queue_cell(channel_t *chan, cell_t *cell)
2713 int need_to_queue = 0;
2714 cell_queue_entry_t *q;
2715 cell_t *cell_copy = NULL;
2717 tor_assert(chan);
2718 tor_assert(cell);
2719 tor_assert(CHANNEL_IS_OPEN(chan));
2721 /* Do we need to queue it, or can we just call the handler right away? */
2722 if (!(chan->cell_handler)) need_to_queue = 1;
2723 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
2724 need_to_queue = 1;
2726 /* Timestamp for receiving */
2727 channel_timestamp_recv(chan);
2729 /* Update the counters */
2730 ++(chan->n_cells_recved);
2731 chan->n_bytes_recved += get_cell_network_size(chan->wide_circ_ids);
2733 /* If we don't need to queue we can just call cell_handler */
2734 if (!need_to_queue) {
2735 tor_assert(chan->cell_handler);
2736 log_debug(LD_CHANNEL,
2737 "Directly handling incoming cell_t %p for channel %p "
2738 "(global ID " U64_FORMAT ")",
2739 cell, chan,
2740 U64_PRINTF_ARG(chan->global_identifier));
2741 chan->cell_handler(chan, cell);
2742 } else {
2744 * Otherwise queue it and then process the queue if possible.
2746 * We queue a copy, not the original pointer - it might have been on the
2747 * stack in connection_or_process_cells_from_inbuf() (or another caller
2748 * if we ever have a subclass other than channel_tls_t), or be freed
2749 * there after we return. This is the uncommon case; the non-copying
2750 * fast path occurs in the if (!need_to_queue) case above when the
2751 * upper layer has installed cell handlers.
2753 cell_copy = tor_malloc_zero(sizeof(cell_t));
2754 memcpy(cell_copy, cell, sizeof(cell_t));
2755 q = cell_queue_entry_new_fixed(cell_copy);
2756 log_debug(LD_CHANNEL,
2757 "Queueing incoming cell_t %p for channel %p "
2758 "(global ID " U64_FORMAT ")",
2759 cell, chan,
2760 U64_PRINTF_ARG(chan->global_identifier));
2761 TOR_SIMPLEQ_INSERT_TAIL(&chan->incoming_queue, q, next);
2762 if (chan->cell_handler ||
2763 chan->var_cell_handler) {
2764 channel_process_cells(chan);
2770 * Queue incoming variable-length cell
2772 * This should be called by a channel_t subclass to queue an incoming
2773 * variable-length cell for processing, and process it if possible.
2776 void
2777 channel_queue_var_cell(channel_t *chan, var_cell_t *var_cell)
2779 int need_to_queue = 0;
2780 cell_queue_entry_t *q;
2781 var_cell_t *cell_copy = NULL;
2783 tor_assert(chan);
2784 tor_assert(var_cell);
2785 tor_assert(CHANNEL_IS_OPEN(chan));
2787 /* Do we need to queue it, or can we just call the handler right away? */
2788 if (!(chan->var_cell_handler)) need_to_queue = 1;
2789 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
2790 need_to_queue = 1;
2792 /* Timestamp for receiving */
2793 channel_timestamp_recv(chan);
2795 /* Update the counter */
2796 ++(chan->n_cells_recved);
2797 chan->n_bytes_recved += get_var_cell_header_size(chan->wide_circ_ids) +
2798 var_cell->payload_len;
2800 /* If we don't need to queue we can just call cell_handler */
2801 if (!need_to_queue) {
2802 tor_assert(chan->var_cell_handler);
2803 log_debug(LD_CHANNEL,
2804 "Directly handling incoming var_cell_t %p for channel %p "
2805 "(global ID " U64_FORMAT ")",
2806 var_cell, chan,
2807 U64_PRINTF_ARG(chan->global_identifier));
2808 chan->var_cell_handler(chan, var_cell);
2809 } else {
2811 * Otherwise queue it and then process the queue if possible.
2813 * We queue a copy, not the original pointer - it might have been on the
2814 * stack in connection_or_process_cells_from_inbuf() (or another caller
2815 * if we ever have a subclass other than channel_tls_t), or be freed
2816 * there after we return. This is the uncommon case; the non-copying
2817 * fast path occurs in the if (!need_to_queue) case above when the
2818 * upper layer has installed cell handlers.
2820 cell_copy = var_cell_copy(var_cell);
2821 q = cell_queue_entry_new_var(cell_copy);
2822 log_debug(LD_CHANNEL,
2823 "Queueing incoming var_cell_t %p for channel %p "
2824 "(global ID " U64_FORMAT ")",
2825 var_cell, chan,
2826 U64_PRINTF_ARG(chan->global_identifier));
2827 TOR_SIMPLEQ_INSERT_TAIL(&chan->incoming_queue, q, next);
2828 if (chan->cell_handler ||
2829 chan->var_cell_handler) {
2830 channel_process_cells(chan);
2835 /** If <b>packed_cell</b> on <b>chan</b> is a destroy cell, then set
2836 * *<b>circid_out</b> to its circuit ID, and return true. Otherwise, return
2837 * false. */
2838 /* XXXX Move this function. */
2840 packed_cell_is_destroy(channel_t *chan,
2841 const packed_cell_t *packed_cell,
2842 circid_t *circid_out)
2844 if (chan->wide_circ_ids) {
2845 if (packed_cell->body[4] == CELL_DESTROY) {
2846 *circid_out = ntohl(get_uint32(packed_cell->body));
2847 return 1;
2849 } else {
2850 if (packed_cell->body[2] == CELL_DESTROY) {
2851 *circid_out = ntohs(get_uint16(packed_cell->body));
2852 return 1;
2855 return 0;
2859 * Assert that the global channel stats counters are internally consistent
2862 static void
2863 channel_assert_counter_consistency(void)
2865 tor_assert(n_channel_cells_queued ==
2866 (n_channel_cells_in_queues + n_channel_cells_passed_to_lower_layer));
2867 tor_assert(n_channel_bytes_queued ==
2868 (n_channel_bytes_in_queues + n_channel_bytes_passed_to_lower_layer));
2871 /* DOCDOC */
2872 static int
2873 is_destroy_cell(channel_t *chan,
2874 const cell_queue_entry_t *q, circid_t *circid_out)
2876 *circid_out = 0;
2877 switch (q->type) {
2878 case CELL_QUEUE_FIXED:
2879 if (q->u.fixed.cell->command == CELL_DESTROY) {
2880 *circid_out = q->u.fixed.cell->circ_id;
2881 return 1;
2883 break;
2884 case CELL_QUEUE_VAR:
2885 if (q->u.var.var_cell->command == CELL_DESTROY) {
2886 *circid_out = q->u.var.var_cell->circ_id;
2887 return 1;
2889 break;
2890 case CELL_QUEUE_PACKED:
2891 return packed_cell_is_destroy(chan, q->u.packed.packed_cell, circid_out);
2893 return 0;
2897 * Send destroy cell on a channel
2899 * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
2900 * onto channel <b>chan</b>. Don't perform range-checking on reason:
2901 * we may want to propagate reasons from other cells.
2905 channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
2907 tor_assert(chan);
2908 if (circ_id == 0) {
2909 log_warn(LD_BUG, "Attempted to send a destroy cell for circID 0 "
2910 "on a channel " U64_FORMAT " at %p in state %s (%d)",
2911 U64_PRINTF_ARG(chan->global_identifier),
2912 chan, channel_state_to_string(chan->state),
2913 chan->state);
2914 return 0;
2917 /* Check to make sure we can send on this channel first */
2918 if (!CHANNEL_CONDEMNED(chan) && chan->cmux) {
2919 channel_note_destroy_pending(chan, circ_id);
2920 circuitmux_append_destroy_cell(chan, chan->cmux, circ_id, reason);
2921 log_debug(LD_OR,
2922 "Sending destroy (circID %u) on channel %p "
2923 "(global ID " U64_FORMAT ")",
2924 (unsigned)circ_id, chan,
2925 U64_PRINTF_ARG(chan->global_identifier));
2926 } else {
2927 log_warn(LD_BUG,
2928 "Someone called channel_send_destroy() for circID %u "
2929 "on a channel " U64_FORMAT " at %p in state %s (%d)",
2930 (unsigned)circ_id, U64_PRINTF_ARG(chan->global_identifier),
2931 chan, channel_state_to_string(chan->state),
2932 chan->state);
2935 return 0;
2939 * Dump channel statistics to the log
2941 * This is called from dumpstats() in main.c and spams the log with
2942 * statistics on channels.
2945 void
2946 channel_dumpstats(int severity)
2948 if (all_channels && smartlist_len(all_channels) > 0) {
2949 tor_log(severity, LD_GENERAL,
2950 "Channels have queued " U64_FORMAT " bytes in " U64_FORMAT " cells, "
2951 "and handed " U64_FORMAT " bytes in " U64_FORMAT " cells to the lower"
2952 " layer.",
2953 U64_PRINTF_ARG(n_channel_bytes_queued),
2954 U64_PRINTF_ARG(n_channel_cells_queued),
2955 U64_PRINTF_ARG(n_channel_bytes_passed_to_lower_layer),
2956 U64_PRINTF_ARG(n_channel_cells_passed_to_lower_layer));
2957 tor_log(severity, LD_GENERAL,
2958 "There are currently " U64_FORMAT " bytes in " U64_FORMAT " cells "
2959 "in channel queues.",
2960 U64_PRINTF_ARG(n_channel_bytes_in_queues),
2961 U64_PRINTF_ARG(n_channel_cells_in_queues));
2962 tor_log(severity, LD_GENERAL,
2963 "Dumping statistics about %d channels:",
2964 smartlist_len(all_channels));
2965 tor_log(severity, LD_GENERAL,
2966 "%d are active, and %d are done and waiting for cleanup",
2967 (active_channels != NULL) ?
2968 smartlist_len(active_channels) : 0,
2969 (finished_channels != NULL) ?
2970 smartlist_len(finished_channels) : 0);
2972 SMARTLIST_FOREACH(all_channels, channel_t *, chan,
2973 channel_dump_statistics(chan, severity));
2975 tor_log(severity, LD_GENERAL,
2976 "Done spamming about channels now");
2977 } else {
2978 tor_log(severity, LD_GENERAL,
2979 "No channels to dump");
2984 * Dump channel listener statistics to the log
2986 * This is called from dumpstats() in main.c and spams the log with
2987 * statistics on channel listeners.
2990 void
2991 channel_listener_dumpstats(int severity)
2993 if (all_listeners && smartlist_len(all_listeners) > 0) {
2994 tor_log(severity, LD_GENERAL,
2995 "Dumping statistics about %d channel listeners:",
2996 smartlist_len(all_listeners));
2997 tor_log(severity, LD_GENERAL,
2998 "%d are active and %d are done and waiting for cleanup",
2999 (active_listeners != NULL) ?
3000 smartlist_len(active_listeners) : 0,
3001 (finished_listeners != NULL) ?
3002 smartlist_len(finished_listeners) : 0);
3004 SMARTLIST_FOREACH(all_listeners, channel_listener_t *, chan_l,
3005 channel_listener_dump_statistics(chan_l, severity));
3007 tor_log(severity, LD_GENERAL,
3008 "Done spamming about channel listeners now");
3009 } else {
3010 tor_log(severity, LD_GENERAL,
3011 "No channel listeners to dump");
3016 * Set the cmux policy on all active channels
3019 void
3020 channel_set_cmux_policy_everywhere(circuitmux_policy_t *pol)
3022 if (!active_channels) return;
3024 SMARTLIST_FOREACH_BEGIN(active_channels, channel_t *, curr) {
3025 if (curr->cmux) {
3026 circuitmux_set_policy(curr->cmux, pol);
3028 } SMARTLIST_FOREACH_END(curr);
3032 * Clean up channels
3034 * This gets called periodically from run_scheduled_events() in main.c;
3035 * it cleans up after closed channels.
3038 void
3039 channel_run_cleanup(void)
3041 channel_t *tmp = NULL;
3043 /* Check if we need to do anything */
3044 if (!finished_channels || smartlist_len(finished_channels) == 0) return;
3046 /* Iterate through finished_channels and get rid of them */
3047 SMARTLIST_FOREACH_BEGIN(finished_channels, channel_t *, curr) {
3048 tmp = curr;
3049 /* Remove it from the list */
3050 SMARTLIST_DEL_CURRENT(finished_channels, curr);
3051 /* Also unregister it */
3052 channel_unregister(tmp);
3053 /* ... and free it */
3054 channel_free(tmp);
3055 } SMARTLIST_FOREACH_END(curr);
3059 * Clean up channel listeners
3061 * This gets called periodically from run_scheduled_events() in main.c;
3062 * it cleans up after closed channel listeners.
3065 void
3066 channel_listener_run_cleanup(void)
3068 channel_listener_t *tmp = NULL;
3070 /* Check if we need to do anything */
3071 if (!finished_listeners || smartlist_len(finished_listeners) == 0) return;
3073 /* Iterate through finished_channels and get rid of them */
3074 SMARTLIST_FOREACH_BEGIN(finished_listeners, channel_listener_t *, curr) {
3075 tmp = curr;
3076 /* Remove it from the list */
3077 SMARTLIST_DEL_CURRENT(finished_listeners, curr);
3078 /* Also unregister it */
3079 channel_listener_unregister(tmp);
3080 /* ... and free it */
3081 channel_listener_free(tmp);
3082 } SMARTLIST_FOREACH_END(curr);
3086 * Free a list of channels for channel_free_all()
3089 static void
3090 channel_free_list(smartlist_t *channels, int mark_for_close)
3092 if (!channels) return;
3094 SMARTLIST_FOREACH_BEGIN(channels, channel_t *, curr) {
3095 /* Deregister and free it */
3096 tor_assert(curr);
3097 log_debug(LD_CHANNEL,
3098 "Cleaning up channel %p (global ID " U64_FORMAT ") "
3099 "in state %s (%d)",
3100 curr, U64_PRINTF_ARG(curr->global_identifier),
3101 channel_state_to_string(curr->state), curr->state);
3102 /* Detach circuits early so they can find the channel */
3103 if (curr->cmux) {
3104 circuitmux_detach_all_circuits(curr->cmux, NULL);
3106 SMARTLIST_DEL_CURRENT(channels, curr);
3107 channel_unregister(curr);
3108 if (mark_for_close) {
3109 if (!CHANNEL_CONDEMNED(curr)) {
3110 channel_mark_for_close(curr);
3112 channel_force_free(curr);
3113 } else channel_free(curr);
3114 } SMARTLIST_FOREACH_END(curr);
3118 * Free a list of channel listeners for channel_free_all()
3121 static void
3122 channel_listener_free_list(smartlist_t *listeners, int mark_for_close)
3124 if (!listeners) return;
3126 SMARTLIST_FOREACH_BEGIN(listeners, channel_listener_t *, curr) {
3127 /* Deregister and free it */
3128 tor_assert(curr);
3129 log_debug(LD_CHANNEL,
3130 "Cleaning up channel listener %p (global ID " U64_FORMAT ") "
3131 "in state %s (%d)",
3132 curr, U64_PRINTF_ARG(curr->global_identifier),
3133 channel_listener_state_to_string(curr->state), curr->state);
3134 channel_listener_unregister(curr);
3135 if (mark_for_close) {
3136 if (!(curr->state == CHANNEL_LISTENER_STATE_CLOSING ||
3137 curr->state == CHANNEL_LISTENER_STATE_CLOSED ||
3138 curr->state == CHANNEL_LISTENER_STATE_ERROR)) {
3139 channel_listener_mark_for_close(curr);
3141 channel_listener_force_free(curr);
3142 } else channel_listener_free(curr);
3143 } SMARTLIST_FOREACH_END(curr);
3147 * Close all channels and free everything
3149 * This gets called from tor_free_all() in main.c to clean up on exit.
3150 * It will close all registered channels and free associated storage,
3151 * then free the all_channels, active_channels, listening_channels and
3152 * finished_channels lists and also channel_identity_map.
3155 void
3156 channel_free_all(void)
3158 log_debug(LD_CHANNEL,
3159 "Shutting down channels...");
3161 /* First, let's go for finished channels */
3162 if (finished_channels) {
3163 channel_free_list(finished_channels, 0);
3164 smartlist_free(finished_channels);
3165 finished_channels = NULL;
3168 /* Now the finished listeners */
3169 if (finished_listeners) {
3170 channel_listener_free_list(finished_listeners, 0);
3171 smartlist_free(finished_listeners);
3172 finished_listeners = NULL;
3175 /* Now all active channels */
3176 if (active_channels) {
3177 channel_free_list(active_channels, 1);
3178 smartlist_free(active_channels);
3179 active_channels = NULL;
3182 /* Now all active listeners */
3183 if (active_listeners) {
3184 channel_listener_free_list(active_listeners, 1);
3185 smartlist_free(active_listeners);
3186 active_listeners = NULL;
3189 /* Now all channels, in case any are left over */
3190 if (all_channels) {
3191 channel_free_list(all_channels, 1);
3192 smartlist_free(all_channels);
3193 all_channels = NULL;
3196 /* Now all listeners, in case any are left over */
3197 if (all_listeners) {
3198 channel_listener_free_list(all_listeners, 1);
3199 smartlist_free(all_listeners);
3200 all_listeners = NULL;
3203 /* Now free channel_identity_map */
3204 log_debug(LD_CHANNEL,
3205 "Freeing channel_identity_map");
3206 /* Geez, anything still left over just won't die ... let it leak then */
3207 HT_CLEAR(channel_idmap, &channel_identity_map);
3209 log_debug(LD_CHANNEL,
3210 "Done cleaning up after channels");
3214 * Connect to a given addr/port/digest
3216 * This sets up a new outgoing channel; in the future if multiple
3217 * channel_t subclasses are available, this is where the selection policy
3218 * should go. It may also be desirable to fold port into tor_addr_t
3219 * or make a new type including a tor_addr_t and port, so we have a
3220 * single abstract object encapsulating all the protocol details of
3221 * how to contact an OR.
3224 channel_t *
3225 channel_connect(const tor_addr_t *addr, uint16_t port,
3226 const char *id_digest)
3228 return channel_tls_connect(addr, port, id_digest);
3232 * Decide which of two channels to prefer for extending a circuit
3234 * This function is called while extending a circuit and returns true iff
3235 * a is 'better' than b. The most important criterion here is that a
3236 * canonical channel is always better than a non-canonical one, but the
3237 * number of circuits and the age are used as tie-breakers.
3239 * This is based on the former connection_or_is_better() of connection_or.c
3243 channel_is_better(time_t now, channel_t *a, channel_t *b,
3244 int forgive_new_connections)
3246 int a_grace, b_grace;
3247 int a_is_canonical, b_is_canonical;
3248 int a_has_circs, b_has_circs;
3251 * Do not definitively deprecate a new channel with no circuits on it
3252 * until this much time has passed.
3254 #define NEW_CHAN_GRACE_PERIOD (15*60)
3256 tor_assert(a);
3257 tor_assert(b);
3259 /* Check if one is canonical and the other isn't first */
3260 a_is_canonical = channel_is_canonical(a);
3261 b_is_canonical = channel_is_canonical(b);
3263 if (a_is_canonical && !b_is_canonical) return 1;
3264 if (!a_is_canonical && b_is_canonical) return 0;
3267 * Okay, if we're here they tied on canonicity. Next we check if
3268 * they have any circuits, and if one does and the other doesn't,
3269 * we prefer the one that does, unless we are forgiving and the
3270 * one that has no circuits is in its grace period.
3273 a_has_circs = (channel_num_circuits(a) > 0);
3274 b_has_circs = (channel_num_circuits(b) > 0);
3275 a_grace = (forgive_new_connections &&
3276 (now < channel_when_created(a) + NEW_CHAN_GRACE_PERIOD));
3277 b_grace = (forgive_new_connections &&
3278 (now < channel_when_created(b) + NEW_CHAN_GRACE_PERIOD));
3280 if (a_has_circs && !b_has_circs && !b_grace) return 1;
3281 if (!a_has_circs && b_has_circs && !a_grace) return 0;
3283 /* They tied on circuits too; just prefer whichever is newer */
3285 if (channel_when_created(a) > channel_when_created(b)) return 1;
3286 else return 0;
3290 * Get a channel to extend a circuit
3292 * Pick a suitable channel to extend a circuit to given the desired digest
3293 * the address we believe is correct for that digest; this tries to see
3294 * if we already have one for the requested endpoint, but if there is no good
3295 * channel, set *msg_out to a message describing the channel's state
3296 * and our next action, and set *launch_out to a boolean indicated whether
3297 * the caller should try to launch a new channel with channel_connect().
3300 channel_t *
3301 channel_get_for_extend(const char *digest,
3302 const tor_addr_t *target_addr,
3303 const char **msg_out,
3304 int *launch_out)
3306 channel_t *chan, *best = NULL;
3307 int n_inprogress_goodaddr = 0, n_old = 0;
3308 int n_noncanonical = 0, n_possible = 0;
3309 time_t now = approx_time();
3311 tor_assert(msg_out);
3312 tor_assert(launch_out);
3314 chan = channel_find_by_remote_digest(digest);
3316 /* Walk the list, unrefing the old one and refing the new at each
3317 * iteration.
3319 for (; chan; chan = channel_next_with_digest(chan)) {
3320 tor_assert(tor_memeq(chan->identity_digest,
3321 digest, DIGEST_LEN));
3323 if (CHANNEL_CONDEMNED(chan))
3324 continue;
3326 /* Never return a channel on which the other end appears to be
3327 * a client. */
3328 if (channel_is_client(chan)) {
3329 continue;
3332 /* Never return a non-open connection. */
3333 if (!CHANNEL_IS_OPEN(chan)) {
3334 /* If the address matches, don't launch a new connection for this
3335 * circuit. */
3336 if (channel_matches_target_addr_for_extend(chan, target_addr))
3337 ++n_inprogress_goodaddr;
3338 continue;
3341 /* Never return a connection that shouldn't be used for circs. */
3342 if (channel_is_bad_for_new_circs(chan)) {
3343 ++n_old;
3344 continue;
3347 /* Never return a non-canonical connection using a recent link protocol
3348 * if the address is not what we wanted.
3350 * The channel_is_canonical_is_reliable() function asks the lower layer
3351 * if we should trust channel_is_canonical(). The below is from the
3352 * comments of the old circuit_or_get_for_extend() and applies when
3353 * the lower-layer transport is channel_tls_t.
3355 * (For old link protocols, we can't rely on is_canonical getting
3356 * set properly if we're talking to the right address, since we might
3357 * have an out-of-date descriptor, and we will get no NETINFO cell to
3358 * tell us about the right address.)
3360 if (!channel_is_canonical(chan) &&
3361 channel_is_canonical_is_reliable(chan) &&
3362 !channel_matches_target_addr_for_extend(chan, target_addr)) {
3363 ++n_noncanonical;
3364 continue;
3367 ++n_possible;
3369 if (!best) {
3370 best = chan; /* If we have no 'best' so far, this one is good enough. */
3371 continue;
3374 if (channel_is_better(now, chan, best, 0))
3375 best = chan;
3378 if (best) {
3379 *msg_out = "Connection is fine; using it.";
3380 *launch_out = 0;
3381 return best;
3382 } else if (n_inprogress_goodaddr) {
3383 *msg_out = "Connection in progress; waiting.";
3384 *launch_out = 0;
3385 return NULL;
3386 } else if (n_old || n_noncanonical) {
3387 *msg_out = "Connections all too old, or too non-canonical. "
3388 " Launching a new one.";
3389 *launch_out = 1;
3390 return NULL;
3391 } else {
3392 *msg_out = "Not connected. Connecting.";
3393 *launch_out = 1;
3394 return NULL;
3399 * Describe the transport subclass for a channel
3401 * Invoke a method to get a string description of the lower-layer
3402 * transport for this channel.
3405 const char *
3406 channel_describe_transport(channel_t *chan)
3408 tor_assert(chan);
3409 tor_assert(chan->describe_transport);
3411 return chan->describe_transport(chan);
3415 * Describe the transport subclass for a channel listener
3417 * Invoke a method to get a string description of the lower-layer
3418 * transport for this channel listener.
3421 const char *
3422 channel_listener_describe_transport(channel_listener_t *chan_l)
3424 tor_assert(chan_l);
3425 tor_assert(chan_l->describe_transport);
3427 return chan_l->describe_transport(chan_l);
3431 * Return the number of entries in <b>queue</b>
3433 STATIC int
3434 chan_cell_queue_len(const chan_cell_queue_t *queue)
3436 int r = 0;
3437 cell_queue_entry_t *cell;
3438 TOR_SIMPLEQ_FOREACH(cell, queue, next)
3439 ++r;
3440 return r;
3444 * Dump channel statistics
3446 * Dump statistics for one channel to the log
3449 MOCK_IMPL(void,
3450 channel_dump_statistics, (channel_t *chan, int severity))
3452 double avg, interval, age;
3453 time_t now = time(NULL);
3454 tor_addr_t remote_addr;
3455 int have_remote_addr;
3456 char *remote_addr_str;
3458 tor_assert(chan);
3460 age = (double)(now - chan->timestamp_created);
3462 tor_log(severity, LD_GENERAL,
3463 "Channel " U64_FORMAT " (at %p) with transport %s is in state "
3464 "%s (%d)",
3465 U64_PRINTF_ARG(chan->global_identifier), chan,
3466 channel_describe_transport(chan),
3467 channel_state_to_string(chan->state), chan->state);
3468 tor_log(severity, LD_GENERAL,
3469 " * Channel " U64_FORMAT " was created at " U64_FORMAT
3470 " (" U64_FORMAT " seconds ago) "
3471 "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3472 U64_PRINTF_ARG(chan->global_identifier),
3473 U64_PRINTF_ARG(chan->timestamp_created),
3474 U64_PRINTF_ARG(now - chan->timestamp_created),
3475 U64_PRINTF_ARG(chan->timestamp_active),
3476 U64_PRINTF_ARG(now - chan->timestamp_active));
3478 /* Handle digest and nickname */
3479 if (!tor_digest_is_zero(chan->identity_digest)) {
3480 if (chan->nickname) {
3481 tor_log(severity, LD_GENERAL,
3482 " * Channel " U64_FORMAT " says it is connected "
3483 "to an OR with digest %s and nickname %s",
3484 U64_PRINTF_ARG(chan->global_identifier),
3485 hex_str(chan->identity_digest, DIGEST_LEN),
3486 chan->nickname);
3487 } else {
3488 tor_log(severity, LD_GENERAL,
3489 " * Channel " U64_FORMAT " says it is connected "
3490 "to an OR with digest %s and no known nickname",
3491 U64_PRINTF_ARG(chan->global_identifier),
3492 hex_str(chan->identity_digest, DIGEST_LEN));
3494 } else {
3495 if (chan->nickname) {
3496 tor_log(severity, LD_GENERAL,
3497 " * Channel " U64_FORMAT " does not know the digest"
3498 " of the OR it is connected to, but reports its nickname is %s",
3499 U64_PRINTF_ARG(chan->global_identifier),
3500 chan->nickname);
3501 } else {
3502 tor_log(severity, LD_GENERAL,
3503 " * Channel " U64_FORMAT " does not know the digest"
3504 " or the nickname of the OR it is connected to",
3505 U64_PRINTF_ARG(chan->global_identifier));
3509 /* Handle remote address and descriptions */
3510 have_remote_addr = channel_get_addr_if_possible(chan, &remote_addr);
3511 if (have_remote_addr) {
3512 char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
3513 remote_addr_str = tor_dup_addr(&remote_addr);
3514 tor_log(severity, LD_GENERAL,
3515 " * Channel " U64_FORMAT " says its remote address"
3516 " is %s, and gives a canonical description of \"%s\" and an "
3517 "actual description of \"%s\"",
3518 U64_PRINTF_ARG(chan->global_identifier),
3519 safe_str(remote_addr_str),
3520 safe_str(channel_get_canonical_remote_descr(chan)),
3521 safe_str(actual));
3522 tor_free(remote_addr_str);
3523 tor_free(actual);
3524 } else {
3525 char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
3526 tor_log(severity, LD_GENERAL,
3527 " * Channel " U64_FORMAT " does not know its remote "
3528 "address, but gives a canonical description of \"%s\" and an "
3529 "actual description of \"%s\"",
3530 U64_PRINTF_ARG(chan->global_identifier),
3531 channel_get_canonical_remote_descr(chan),
3532 actual);
3533 tor_free(actual);
3536 /* Handle marks */
3537 tor_log(severity, LD_GENERAL,
3538 " * Channel " U64_FORMAT " has these marks: %s %s %s "
3539 "%s %s %s",
3540 U64_PRINTF_ARG(chan->global_identifier),
3541 channel_is_bad_for_new_circs(chan) ?
3542 "bad_for_new_circs" : "!bad_for_new_circs",
3543 channel_is_canonical(chan) ?
3544 "canonical" : "!canonical",
3545 channel_is_canonical_is_reliable(chan) ?
3546 "is_canonical_is_reliable" :
3547 "!is_canonical_is_reliable",
3548 channel_is_client(chan) ?
3549 "client" : "!client",
3550 channel_is_local(chan) ?
3551 "local" : "!local",
3552 channel_is_incoming(chan) ?
3553 "incoming" : "outgoing");
3555 /* Describe queues */
3556 tor_log(severity, LD_GENERAL,
3557 " * Channel " U64_FORMAT " has %d queued incoming cells"
3558 " and %d queued outgoing cells",
3559 U64_PRINTF_ARG(chan->global_identifier),
3560 chan_cell_queue_len(&chan->incoming_queue),
3561 chan_cell_queue_len(&chan->outgoing_queue));
3563 /* Describe circuits */
3564 tor_log(severity, LD_GENERAL,
3565 " * Channel " U64_FORMAT " has %d active circuits out of"
3566 " %d in total",
3567 U64_PRINTF_ARG(chan->global_identifier),
3568 (chan->cmux != NULL) ?
3569 circuitmux_num_active_circuits(chan->cmux) : 0,
3570 (chan->cmux != NULL) ?
3571 circuitmux_num_circuits(chan->cmux) : 0);
3573 /* Describe timestamps */
3574 tor_log(severity, LD_GENERAL,
3575 " * Channel " U64_FORMAT " was last used by a "
3576 "client at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3577 U64_PRINTF_ARG(chan->global_identifier),
3578 U64_PRINTF_ARG(chan->timestamp_client),
3579 U64_PRINTF_ARG(now - chan->timestamp_client));
3580 tor_log(severity, LD_GENERAL,
3581 " * Channel " U64_FORMAT " was last drained at "
3582 U64_FORMAT " (" U64_FORMAT " seconds ago)",
3583 U64_PRINTF_ARG(chan->global_identifier),
3584 U64_PRINTF_ARG(chan->timestamp_drained),
3585 U64_PRINTF_ARG(now - chan->timestamp_drained));
3586 tor_log(severity, LD_GENERAL,
3587 " * Channel " U64_FORMAT " last received a cell "
3588 "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3589 U64_PRINTF_ARG(chan->global_identifier),
3590 U64_PRINTF_ARG(chan->timestamp_recv),
3591 U64_PRINTF_ARG(now - chan->timestamp_recv));
3592 tor_log(severity, LD_GENERAL,
3593 " * Channel " U64_FORMAT " last transmitted a cell "
3594 "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3595 U64_PRINTF_ARG(chan->global_identifier),
3596 U64_PRINTF_ARG(chan->timestamp_xmit),
3597 U64_PRINTF_ARG(now - chan->timestamp_xmit));
3599 /* Describe counters and rates */
3600 tor_log(severity, LD_GENERAL,
3601 " * Channel " U64_FORMAT " has received "
3602 U64_FORMAT " bytes in " U64_FORMAT " cells and transmitted "
3603 U64_FORMAT " bytes in " U64_FORMAT " cells",
3604 U64_PRINTF_ARG(chan->global_identifier),
3605 U64_PRINTF_ARG(chan->n_bytes_recved),
3606 U64_PRINTF_ARG(chan->n_cells_recved),
3607 U64_PRINTF_ARG(chan->n_bytes_xmitted),
3608 U64_PRINTF_ARG(chan->n_cells_xmitted));
3609 if (now > chan->timestamp_created &&
3610 chan->timestamp_created > 0) {
3611 if (chan->n_bytes_recved > 0) {
3612 avg = (double)(chan->n_bytes_recved) / age;
3613 tor_log(severity, LD_GENERAL,
3614 " * Channel " U64_FORMAT " has averaged %f "
3615 "bytes received per second",
3616 U64_PRINTF_ARG(chan->global_identifier), avg);
3618 if (chan->n_cells_recved > 0) {
3619 avg = (double)(chan->n_cells_recved) / age;
3620 if (avg >= 1.0) {
3621 tor_log(severity, LD_GENERAL,
3622 " * Channel " U64_FORMAT " has averaged %f "
3623 "cells received per second",
3624 U64_PRINTF_ARG(chan->global_identifier), avg);
3625 } else if (avg >= 0.0) {
3626 interval = 1.0 / avg;
3627 tor_log(severity, LD_GENERAL,
3628 " * Channel " U64_FORMAT " has averaged %f "
3629 "seconds between received cells",
3630 U64_PRINTF_ARG(chan->global_identifier), interval);
3633 if (chan->n_bytes_xmitted > 0) {
3634 avg = (double)(chan->n_bytes_xmitted) / age;
3635 tor_log(severity, LD_GENERAL,
3636 " * Channel " U64_FORMAT " has averaged %f "
3637 "bytes transmitted per second",
3638 U64_PRINTF_ARG(chan->global_identifier), avg);
3640 if (chan->n_cells_xmitted > 0) {
3641 avg = (double)(chan->n_cells_xmitted) / age;
3642 if (avg >= 1.0) {
3643 tor_log(severity, LD_GENERAL,
3644 " * Channel " U64_FORMAT " has averaged %f "
3645 "cells transmitted per second",
3646 U64_PRINTF_ARG(chan->global_identifier), avg);
3647 } else if (avg >= 0.0) {
3648 interval = 1.0 / avg;
3649 tor_log(severity, LD_GENERAL,
3650 " * Channel " U64_FORMAT " has averaged %f "
3651 "seconds between transmitted cells",
3652 U64_PRINTF_ARG(chan->global_identifier), interval);
3657 /* Dump anything the lower layer has to say */
3658 channel_dump_transport_statistics(chan, severity);
3662 * Dump channel listener statistics
3664 * Dump statistics for one channel listener to the log
3667 void
3668 channel_listener_dump_statistics(channel_listener_t *chan_l, int severity)
3670 double avg, interval, age;
3671 time_t now = time(NULL);
3673 tor_assert(chan_l);
3675 age = (double)(now - chan_l->timestamp_created);
3677 tor_log(severity, LD_GENERAL,
3678 "Channel listener " U64_FORMAT " (at %p) with transport %s is in "
3679 "state %s (%d)",
3680 U64_PRINTF_ARG(chan_l->global_identifier), chan_l,
3681 channel_listener_describe_transport(chan_l),
3682 channel_listener_state_to_string(chan_l->state), chan_l->state);
3683 tor_log(severity, LD_GENERAL,
3684 " * Channel listener " U64_FORMAT " was created at " U64_FORMAT
3685 " (" U64_FORMAT " seconds ago) "
3686 "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3687 U64_PRINTF_ARG(chan_l->global_identifier),
3688 U64_PRINTF_ARG(chan_l->timestamp_created),
3689 U64_PRINTF_ARG(now - chan_l->timestamp_created),
3690 U64_PRINTF_ARG(chan_l->timestamp_active),
3691 U64_PRINTF_ARG(now - chan_l->timestamp_active));
3693 tor_log(severity, LD_GENERAL,
3694 " * Channel listener " U64_FORMAT " last accepted an incoming "
3695 "channel at " U64_FORMAT " (" U64_FORMAT " seconds ago) "
3696 "and has accepted " U64_FORMAT " channels in total",
3697 U64_PRINTF_ARG(chan_l->global_identifier),
3698 U64_PRINTF_ARG(chan_l->timestamp_accepted),
3699 U64_PRINTF_ARG(now - chan_l->timestamp_accepted),
3700 U64_PRINTF_ARG(chan_l->n_accepted));
3703 * If it's sensible to do so, get the rate of incoming channels on this
3704 * listener
3706 if (now > chan_l->timestamp_created &&
3707 chan_l->timestamp_created > 0 &&
3708 chan_l->n_accepted > 0) {
3709 avg = (double)(chan_l->n_accepted) / age;
3710 if (avg >= 1.0) {
3711 tor_log(severity, LD_GENERAL,
3712 " * Channel listener " U64_FORMAT " has averaged %f incoming "
3713 "channels per second",
3714 U64_PRINTF_ARG(chan_l->global_identifier), avg);
3715 } else if (avg >= 0.0) {
3716 interval = 1.0 / avg;
3717 tor_log(severity, LD_GENERAL,
3718 " * Channel listener " U64_FORMAT " has averaged %f seconds "
3719 "between incoming channels",
3720 U64_PRINTF_ARG(chan_l->global_identifier), interval);
3724 /* Dump anything the lower layer has to say */
3725 channel_listener_dump_transport_statistics(chan_l, severity);
3729 * Invoke transport-specific stats dump for channel
3731 * If there is a lower-layer statistics dump method, invoke it
3734 void
3735 channel_dump_transport_statistics(channel_t *chan, int severity)
3737 tor_assert(chan);
3739 if (chan->dumpstats) chan->dumpstats(chan, severity);
3743 * Invoke transport-specific stats dump for channel listener
3745 * If there is a lower-layer statistics dump method, invoke it
3748 void
3749 channel_listener_dump_transport_statistics(channel_listener_t *chan_l,
3750 int severity)
3752 tor_assert(chan_l);
3754 if (chan_l->dumpstats) chan_l->dumpstats(chan_l, severity);
3758 * Return text description of the remote endpoint
3760 * This function return a test provided by the lower layer of the remote
3761 * endpoint for this channel; it should specify the actual address connected
3762 * to/from.
3764 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
3765 * may invalidate the return value from this function.
3767 const char *
3768 channel_get_actual_remote_descr(channel_t *chan)
3770 tor_assert(chan);
3771 tor_assert(chan->get_remote_descr);
3773 /* Param 1 indicates the actual description */
3774 return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL);
3778 * Return the text address of the remote endpoint.
3780 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
3781 * may invalidate the return value from this function.
3783 const char *
3784 channel_get_actual_remote_address(channel_t *chan)
3786 /* Param 1 indicates the actual description */
3787 return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY);
3791 * Return text description of the remote endpoint canonical address
3793 * This function return a test provided by the lower layer of the remote
3794 * endpoint for this channel; it should use the known canonical address for
3795 * this OR's identity digest if possible.
3797 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
3798 * may invalidate the return value from this function.
3800 const char *
3801 channel_get_canonical_remote_descr(channel_t *chan)
3803 tor_assert(chan);
3804 tor_assert(chan->get_remote_descr);
3806 /* Param 0 indicates the canonicalized description */
3807 return chan->get_remote_descr(chan, 0);
3811 * Get remote address if possible.
3813 * Write the remote address out to a tor_addr_t if the underlying transport
3814 * supports this operation, and return 1. Return 0 if the underlying transport
3815 * doesn't let us do this.
3818 channel_get_addr_if_possible(channel_t *chan, tor_addr_t *addr_out)
3820 tor_assert(chan);
3821 tor_assert(addr_out);
3823 if (chan->get_remote_addr)
3824 return chan->get_remote_addr(chan, addr_out);
3825 /* Else no support, method not implemented */
3826 else return 0;
3830 * Check if there are outgoing queue writes on this channel
3832 * Indicate if either we have queued cells, or if not, whether the underlying
3833 * lower-layer transport thinks it has an output queue.
3837 channel_has_queued_writes(channel_t *chan)
3839 int has_writes = 0;
3841 tor_assert(chan);
3842 tor_assert(chan->has_queued_writes);
3844 if (! TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue)) {
3845 has_writes = 1;
3846 } else {
3847 /* Check with the lower layer */
3848 has_writes = chan->has_queued_writes(chan);
3851 return has_writes;
3855 * Check the is_bad_for_new_circs flag
3857 * This function returns the is_bad_for_new_circs flag of the specified
3858 * channel.
3862 channel_is_bad_for_new_circs(channel_t *chan)
3864 tor_assert(chan);
3866 return chan->is_bad_for_new_circs;
3870 * Mark a channel as bad for new circuits
3872 * Set the is_bad_for_new_circs_flag on chan.
3875 void
3876 channel_mark_bad_for_new_circs(channel_t *chan)
3878 tor_assert(chan);
3880 chan->is_bad_for_new_circs = 1;
3884 * Get the client flag
3886 * This returns the client flag of a channel, which will be set if
3887 * command_process_create_cell() in command.c thinks this is a connection
3888 * from a client.
3892 channel_is_client(channel_t *chan)
3894 tor_assert(chan);
3896 return chan->is_client;
3900 * Set the client flag
3902 * Mark a channel as being from a client
3905 void
3906 channel_mark_client(channel_t *chan)
3908 tor_assert(chan);
3910 chan->is_client = 1;
3914 * Get the canonical flag for a channel
3916 * This returns the is_canonical for a channel; this flag is determined by
3917 * the lower layer and can't be set in a transport-independent way.
3921 channel_is_canonical(channel_t *chan)
3923 tor_assert(chan);
3924 tor_assert(chan->is_canonical);
3926 return chan->is_canonical(chan, 0);
3930 * Test if the canonical flag is reliable
3932 * This function asks if the lower layer thinks it's safe to trust the
3933 * result of channel_is_canonical()
3937 channel_is_canonical_is_reliable(channel_t *chan)
3939 tor_assert(chan);
3940 tor_assert(chan->is_canonical);
3942 return chan->is_canonical(chan, 1);
3946 * Test incoming flag
3948 * This function gets the incoming flag; this is set when a listener spawns
3949 * a channel. If this returns true the channel was remotely initiated.
3953 channel_is_incoming(channel_t *chan)
3955 tor_assert(chan);
3957 return chan->is_incoming;
3961 * Set the incoming flag
3963 * This function is called when a channel arrives on a listening channel
3964 * to mark it as incoming.
3967 void
3968 channel_mark_incoming(channel_t *chan)
3970 tor_assert(chan);
3972 chan->is_incoming = 1;
3976 * Test local flag
3978 * This function gets the local flag; the lower layer should set this when
3979 * setting up the channel if is_local_addr() is true for all of the
3980 * destinations it will communicate with on behalf of this channel. It's
3981 * used to decide whether to declare the network reachable when seeing incoming
3982 * traffic on the channel.
3986 channel_is_local(channel_t *chan)
3988 tor_assert(chan);
3990 return chan->is_local;
3994 * Set the local flag
3996 * This internal-only function should be called by the lower layer if the
3997 * channel is to a local address. See channel_is_local() above or the
3998 * description of the is_local bit in channel.h
4001 void
4002 channel_mark_local(channel_t *chan)
4004 tor_assert(chan);
4006 chan->is_local = 1;
4010 * Mark a channel as remote
4012 * This internal-only function should be called by the lower layer if the
4013 * channel is not to a local address but has previously been marked local.
4014 * See channel_is_local() above or the description of the is_local bit in
4015 * channel.h
4018 void
4019 channel_mark_remote(channel_t *chan)
4021 tor_assert(chan);
4023 chan->is_local = 0;
4027 * Test outgoing flag
4029 * This function gets the outgoing flag; this is the inverse of the incoming
4030 * bit set when a listener spawns a channel. If this returns true the channel
4031 * was locally initiated.
4035 channel_is_outgoing(channel_t *chan)
4037 tor_assert(chan);
4039 return !(chan->is_incoming);
4043 * Mark a channel as outgoing
4045 * This function clears the incoming flag and thus marks a channel as
4046 * outgoing.
4049 void
4050 channel_mark_outgoing(channel_t *chan)
4052 tor_assert(chan);
4054 chan->is_incoming = 0;
4057 /************************
4058 * Flow control queries *
4059 ***********************/
4062 * Get the latest estimate for the total queue size of all open channels
4065 uint64_t
4066 channel_get_global_queue_estimate(void)
4068 return estimated_total_queue_size;
4072 * Estimate the number of writeable cells
4074 * Ask the lower layer for an estimate of how many cells it can accept, and
4075 * then subtract the length of our outgoing_queue, if any, to produce an
4076 * estimate of the number of cells this channel can accept for writes.
4080 channel_num_cells_writeable(channel_t *chan)
4082 int result;
4084 tor_assert(chan);
4085 tor_assert(chan->num_cells_writeable);
4087 if (chan->state == CHANNEL_STATE_OPEN) {
4088 /* Query lower layer */
4089 result = chan->num_cells_writeable(chan);
4090 /* Subtract cell queue length, if any */
4091 result -= chan_cell_queue_len(&chan->outgoing_queue);
4092 if (result < 0) result = 0;
4093 } else {
4094 /* No cells are writeable in any other state */
4095 result = 0;
4098 return result;
4101 /*********************
4102 * Timestamp updates *
4103 ********************/
4106 * Update the created timestamp for a channel
4108 * This updates the channel's created timestamp and should only be called
4109 * from channel_init().
4112 void
4113 channel_timestamp_created(channel_t *chan)
4115 time_t now = time(NULL);
4117 tor_assert(chan);
4119 chan->timestamp_created = now;
4123 * Update the created timestamp for a channel listener
4125 * This updates the channel listener's created timestamp and should only be
4126 * called from channel_init_listener().
4129 void
4130 channel_listener_timestamp_created(channel_listener_t *chan_l)
4132 time_t now = time(NULL);
4134 tor_assert(chan_l);
4136 chan_l->timestamp_created = now;
4140 * Update the last active timestamp for a channel
4142 * This function updates the channel's last active timestamp; it should be
4143 * called by the lower layer whenever there is activity on the channel which
4144 * does not lead to a cell being transmitted or received; the active timestamp
4145 * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
4146 * but it should be updated for things like the v3 handshake and stuff that
4147 * produce activity only visible to the lower layer.
4150 void
4151 channel_timestamp_active(channel_t *chan)
4153 time_t now = time(NULL);
4155 tor_assert(chan);
4157 chan->timestamp_active = now;
4161 * Update the last active timestamp for a channel listener
4164 void
4165 channel_listener_timestamp_active(channel_listener_t *chan_l)
4167 time_t now = time(NULL);
4169 tor_assert(chan_l);
4171 chan_l->timestamp_active = now;
4175 * Update the last accepted timestamp.
4177 * This function updates the channel listener's last accepted timestamp; it
4178 * should be called whenever a new incoming channel is accepted on a
4179 * listener.
4182 void
4183 channel_listener_timestamp_accepted(channel_listener_t *chan_l)
4185 time_t now = time(NULL);
4187 tor_assert(chan_l);
4189 chan_l->timestamp_active = now;
4190 chan_l->timestamp_accepted = now;
4194 * Update client timestamp
4196 * This function is called by relay.c to timestamp a channel that appears to
4197 * be used as a client.
4200 void
4201 channel_timestamp_client(channel_t *chan)
4203 time_t now = time(NULL);
4205 tor_assert(chan);
4207 chan->timestamp_client = now;
4211 * Update the last drained timestamp
4213 * This is called whenever we transmit a cell which leaves the outgoing cell
4214 * queue completely empty. It also updates the xmit time and the active time.
4217 void
4218 channel_timestamp_drained(channel_t *chan)
4220 time_t now = time(NULL);
4222 tor_assert(chan);
4224 chan->timestamp_active = now;
4225 chan->timestamp_drained = now;
4226 chan->timestamp_xmit = now;
4230 * Update the recv timestamp
4232 * This is called whenever we get an incoming cell from the lower layer.
4233 * This also updates the active timestamp.
4236 void
4237 channel_timestamp_recv(channel_t *chan)
4239 time_t now = time(NULL);
4241 tor_assert(chan);
4243 chan->timestamp_active = now;
4244 chan->timestamp_recv = now;
4248 * Update the xmit timestamp
4249 * This is called whenever we pass an outgoing cell to the lower layer. This
4250 * also updates the active timestamp.
4253 void
4254 channel_timestamp_xmit(channel_t *chan)
4256 time_t now = time(NULL);
4258 tor_assert(chan);
4260 chan->timestamp_active = now;
4261 chan->timestamp_xmit = now;
4264 /***************************************************************
4265 * Timestamp queries - see above for definitions of timestamps *
4266 **************************************************************/
4269 * Query created timestamp for a channel
4272 time_t
4273 channel_when_created(channel_t *chan)
4275 tor_assert(chan);
4277 return chan->timestamp_created;
4281 * Query created timestamp for a channel listener
4284 time_t
4285 channel_listener_when_created(channel_listener_t *chan_l)
4287 tor_assert(chan_l);
4289 return chan_l->timestamp_created;
4293 * Query last active timestamp for a channel
4296 time_t
4297 channel_when_last_active(channel_t *chan)
4299 tor_assert(chan);
4301 return chan->timestamp_active;
4305 * Query last active timestamp for a channel listener
4308 time_t
4309 channel_listener_when_last_active(channel_listener_t *chan_l)
4311 tor_assert(chan_l);
4313 return chan_l->timestamp_active;
4317 * Query last accepted timestamp for a channel listener
4320 time_t
4321 channel_listener_when_last_accepted(channel_listener_t *chan_l)
4323 tor_assert(chan_l);
4325 return chan_l->timestamp_accepted;
4329 * Query client timestamp
4332 time_t
4333 channel_when_last_client(channel_t *chan)
4335 tor_assert(chan);
4337 return chan->timestamp_client;
4341 * Query drained timestamp
4344 time_t
4345 channel_when_last_drained(channel_t *chan)
4347 tor_assert(chan);
4349 return chan->timestamp_drained;
4353 * Query recv timestamp
4356 time_t
4357 channel_when_last_recv(channel_t *chan)
4359 tor_assert(chan);
4361 return chan->timestamp_recv;
4365 * Query xmit timestamp
4368 time_t
4369 channel_when_last_xmit(channel_t *chan)
4371 tor_assert(chan);
4373 return chan->timestamp_xmit;
4377 * Query accepted counter
4380 uint64_t
4381 channel_listener_count_accepted(channel_listener_t *chan_l)
4383 tor_assert(chan_l);
4385 return chan_l->n_accepted;
4389 * Query received cell counter
4392 uint64_t
4393 channel_count_recved(channel_t *chan)
4395 tor_assert(chan);
4397 return chan->n_cells_recved;
4401 * Query transmitted cell counter
4404 uint64_t
4405 channel_count_xmitted(channel_t *chan)
4407 tor_assert(chan);
4409 return chan->n_cells_xmitted;
4413 * Check if a channel matches an extend_info_t
4415 * This function calls the lower layer and asks if this channel matches a
4416 * given extend_info_t.
4420 channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
4422 tor_assert(chan);
4423 tor_assert(chan->matches_extend_info);
4424 tor_assert(extend_info);
4426 return chan->matches_extend_info(chan, extend_info);
4430 * Check if a channel matches a given target address; return true iff we do.
4432 * This function calls into the lower layer and asks if this channel thinks
4433 * it matches a given target address for circuit extension purposes.
4437 channel_matches_target_addr_for_extend(channel_t *chan,
4438 const tor_addr_t *target)
4440 tor_assert(chan);
4441 tor_assert(chan->matches_target);
4442 tor_assert(target);
4444 return chan->matches_target(chan, target);
4448 * Return the total number of circuits used by a channel
4450 * @param chan Channel to query
4451 * @return Number of circuits using this as n_chan or p_chan
4454 unsigned int
4455 channel_num_circuits(channel_t *chan)
4457 tor_assert(chan);
4459 return chan->num_n_circuits +
4460 chan->num_p_circuits;
4464 * Set up circuit ID generation
4466 * This is called when setting up a channel and replaces the old
4467 * connection_or_set_circid_type()
4469 MOCK_IMPL(void,
4470 channel_set_circid_type,(channel_t *chan,
4471 crypto_pk_t *identity_rcvd,
4472 int consider_identity))
4474 int started_here;
4475 crypto_pk_t *our_identity;
4477 tor_assert(chan);
4479 started_here = channel_is_outgoing(chan);
4481 if (! consider_identity) {
4482 if (started_here)
4483 chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
4484 else
4485 chan->circ_id_type = CIRC_ID_TYPE_LOWER;
4486 return;
4489 our_identity = started_here ?
4490 get_tlsclient_identity_key() : get_server_identity_key();
4492 if (identity_rcvd) {
4493 if (crypto_pk_cmp_keys(our_identity, identity_rcvd) < 0) {
4494 chan->circ_id_type = CIRC_ID_TYPE_LOWER;
4495 } else {
4496 chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
4498 } else {
4499 chan->circ_id_type = CIRC_ID_TYPE_NEITHER;
4504 * Update the estimated number of bytes queued to transmit for this channel,
4505 * and notify the scheduler. The estimate includes both the channel queue and
4506 * the queue size reported by the lower layer, and an overhead estimate
4507 * optionally provided by the lower layer.
4510 void
4511 channel_update_xmit_queue_size(channel_t *chan)
4513 uint64_t queued, adj;
4514 double overhead;
4516 tor_assert(chan);
4517 tor_assert(chan->num_bytes_queued);
4520 * First, get the number of bytes we have queued without factoring in
4521 * lower-layer overhead.
4523 queued = chan->num_bytes_queued(chan) + chan->bytes_in_queue;
4524 /* Next, adjust by the overhead factor, if any is available */
4525 if (chan->get_overhead_estimate) {
4526 overhead = chan->get_overhead_estimate(chan);
4527 if (overhead >= 1.0f) {
4528 queued *= overhead;
4529 } else {
4530 /* Ignore silly overhead factors */
4531 log_notice(LD_CHANNEL, "Ignoring silly overhead factor %f", overhead);
4535 /* Now, compare to the previous estimate */
4536 if (queued > chan->bytes_queued_for_xmit) {
4537 adj = queued - chan->bytes_queued_for_xmit;
4538 log_debug(LD_CHANNEL,
4539 "Increasing queue size for channel " U64_FORMAT " by " U64_FORMAT
4540 " from " U64_FORMAT " to " U64_FORMAT,
4541 U64_PRINTF_ARG(chan->global_identifier),
4542 U64_PRINTF_ARG(adj),
4543 U64_PRINTF_ARG(chan->bytes_queued_for_xmit),
4544 U64_PRINTF_ARG(queued));
4545 /* Update the channel's estimate */
4546 chan->bytes_queued_for_xmit = queued;
4548 /* Update the global queue size estimate if appropriate */
4549 if (chan->state == CHANNEL_STATE_OPEN ||
4550 chan->state == CHANNEL_STATE_MAINT) {
4551 estimated_total_queue_size += adj;
4552 log_debug(LD_CHANNEL,
4553 "Increasing global queue size by " U64_FORMAT " for channel "
4554 U64_FORMAT ", new size is " U64_FORMAT,
4555 U64_PRINTF_ARG(adj), U64_PRINTF_ARG(chan->global_identifier),
4556 U64_PRINTF_ARG(estimated_total_queue_size));
4557 /* Tell the scheduler we're increasing the queue size */
4558 scheduler_adjust_queue_size(chan, 1, adj);
4560 } else if (queued < chan->bytes_queued_for_xmit) {
4561 adj = chan->bytes_queued_for_xmit - queued;
4562 log_debug(LD_CHANNEL,
4563 "Decreasing queue size for channel " U64_FORMAT " by " U64_FORMAT
4564 " from " U64_FORMAT " to " U64_FORMAT,
4565 U64_PRINTF_ARG(chan->global_identifier),
4566 U64_PRINTF_ARG(adj),
4567 U64_PRINTF_ARG(chan->bytes_queued_for_xmit),
4568 U64_PRINTF_ARG(queued));
4569 /* Update the channel's estimate */
4570 chan->bytes_queued_for_xmit = queued;
4572 /* Update the global queue size estimate if appropriate */
4573 if (chan->state == CHANNEL_STATE_OPEN ||
4574 chan->state == CHANNEL_STATE_MAINT) {
4575 estimated_total_queue_size -= adj;
4576 log_debug(LD_CHANNEL,
4577 "Decreasing global queue size by " U64_FORMAT " for channel "
4578 U64_FORMAT ", new size is " U64_FORMAT,
4579 U64_PRINTF_ARG(adj), U64_PRINTF_ARG(chan->global_identifier),
4580 U64_PRINTF_ARG(estimated_total_queue_size));
4581 /* Tell the scheduler we're decreasing the queue size */
4582 scheduler_adjust_queue_size(chan, -1, adj);